问题
My scenario:
example.com is a django page which is being visited by user. session is set by server. Now, I have frontend app on another domain called xyz.com, Now, I need to call APIs on example.com, so I am trying to make ajax call with withCredentials: true
. but it does not seems to sending cookie 'sessionId' in request.
I have already seen some stack overflow answers, but suggested answers are not working. link1 link2 link3
What I have been trying : My backend is written in Django, so I tried setting
CORS_ALLOW_CREDENTIALS = True
# Cross Origin Request Settings (CROS)
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_METHODS = (
'GET',
'POST',
'PUT',
'PATCH',
'DELETE',
'OPTIONS'
)
CORS_ALLOW_HEADERS = (
'x-requested-with',
'content-type',
'accept',
'origin',
'authorization',
'x-csrftoken',
'cache',
'cookie',
)
CORS_ORIGIN_WHITELIST = [
'*'
]
SESSION_COOKIE_HTTPONLY = False
SESSION_COOKIE_DOMAIN = 'example.com'
I am using ajax to make api calls on example.com
jQuery.ajax({
url: "http://example.com/api/v1/admin/settings/",
dataType: 'json',
xhrFields: { withCredentials: true },
success: function(data) {
console.log(data);
}
});
回答1:
I am answering to my question so that it can help in case if someone is stuck at same situation.
I found out that in django SESSION_COOKIE_SAMESITE
is by default Lax
.
'Lax' (default): provides a balance between security and usability for websites that want to maintain user’s logged-in session after the user arrives from an external link.
In the GitHub scenario, the session cookie would be allowed when following a regular link from an external website and be blocked in CSRF-prone request methods (e.g. POST).
So I had to set it to None in settings to allow browser sending cookie.
SESSION_COOKIE_SAMESITE = None
refer docs here
来源:https://stackoverflow.com/questions/53052611/ajax-call-with-withcredentials-true-is-not-sending-cookie-in-request