Django:set-cookie 导致 cookie 存储在后端而不是前端
Django: set-cookie causes cookies to be stored in the backend instead of the frontend
- example.com 是前端 (Next.js)
- api.example.com 是后端 (Django)
出于某种原因,cookie 存储在后端域中。
这不允许 front-end 访问存储的 cookie。
我已经使用以下方法实现了身份验证 API,但据我所知,
没有更改存储 cookie 的域的设置。
- django-cors-headers
- dj-rest-auth
- djangorestframework-simplejwt
CORS_ALLOWED_ORIGINS = ['https://example.com']
CORS_ALLOW_CREDENTIALS = True
如何在 front-end 域上存储 cookie?
我认为您正在寻找 SESSION_COOKIE_DOMAIN
The domain to use for session cookies. Set this to a string such as
"example.com" for cross-domain cookies, or use None for a standard
domain cookie.
To use cross-domain cookies with CSRF_USE_SESSIONS, you must include a
leading dot (e.g. ".example.com") to accommodate the CSRF middleware’s
referer checking.
Be cautious when updating this setting on a production site. If you
update this setting to enable cross-domain cookies on a site that
previously used standard domain cookies, existing user cookies will be
set to the old domain. This may result in them being unable to log in
as long as these cookies persist.
还有 response.set_cookie
也有一个 domain
参数
- example.com 是前端 (Next.js)
- api.example.com 是后端 (Django)
出于某种原因,cookie 存储在后端域中。
这不允许 front-end 访问存储的 cookie。
我已经使用以下方法实现了身份验证 API,但据我所知, 没有更改存储 cookie 的域的设置。
- django-cors-headers
- dj-rest-auth
- djangorestframework-simplejwt
CORS_ALLOWED_ORIGINS = ['https://example.com']
CORS_ALLOW_CREDENTIALS = True
如何在 front-end 域上存储 cookie?
我认为您正在寻找 SESSION_COOKIE_DOMAIN
The domain to use for session cookies. Set this to a string such as "example.com" for cross-domain cookies, or use None for a standard domain cookie.
To use cross-domain cookies with CSRF_USE_SESSIONS, you must include a leading dot (e.g. ".example.com") to accommodate the CSRF middleware’s referer checking.
Be cautious when updating this setting on a production site. If you update this setting to enable cross-domain cookies on a site that previously used standard domain cookies, existing user cookies will be set to the old domain. This may result in them being unable to log in as long as these cookies persist.
还有 response.set_cookie
也有一个 domain
参数