withwithCredentials的Ajax调用:true不在请求中发送cookie [英] Ajax call with withCredentials: true is not sending cookie in request

查看:138
本文介绍了withwithCredentials的Ajax调用:true不在请求中发送cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的情况: example.com 是用户正在访问的django页面.会话由服务器设置.现在,我在另一个名为 xyz.com 的域上有一个前端应用程序,现在,我需要在 example.com 上调用API,因此我试图使用 withCredentials:true .但它似乎并未在请求中发送Cookie'sessionId'.

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.

我已经看到了一些堆栈溢出的答案,但是建议的答案不起作用. link1 链接3

I have already seen some stack overflow answers, but suggested answers are not working. link1 link2 link3

我一直在尝试的是:我的后端是用Django编写的,因此我尝试设置

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'

我正在使用Ajax在example.com上进行api调用

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);
 }
});

推荐答案

我正在回答我的问题,以便在有人遇到相同情况时提供帮助.

I am answering to my question so that it can help in case if someone is stuck at same situation.

我发现在Django中, SESSION_COOKIE_SAMESITE 默认是 Lax .

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.

在GitHub场景中,当以下情况允许会话cookie遵循来自外部网站的常规链接并被屏蔽倾向于CSRF的请求方法(例如POST).

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).

所以我必须在设置中将其设置为无",以允许浏览器发送cookie.

So I had to set it to None in settings to allow browser sending cookie.

SESSION_COOKIE_SAMESITE = None

在docs 此处

这篇关于withwithCredentials的Ajax调用:true不在请求中发送cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆