【发布时间】:2019-08-19 07:20:57
【问题描述】:
我的 Vue 应用程序有一个 Django REST Framework API 后端。我正在尝试为匿名用户使用 Django 会话,但是 Django 没有发送或 Axios 无法读取会话 cookie。
通过检查Session.objects.all().count()正在创建一个新会话
我正在尝试使用 JWTAuthentication 为经过身份验证的用户存储购物车数据,SessionAuthentication 用于匿名用户。
# settings.py
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_WHITELIST = (
'localhost:8080',
'127.0.0.1:8080',
)
SESSION_COOKIE_HTTPONLY = False
我尝试在settings.py 中切换SESSION_COOKIE_HTTPONLY,但仍然看不到cookie。
在截获响应时发送 CSRF cookie 但不包括会话 cookie。
import axios from 'axios'
import Cookie from 'js-cookie'
axios.defaults.xsrfCookieName = 'csrftoken'
axios.defaults.xsrfHeaderName = 'X-CSRFToken'
axios.defaults.withCredentials = true
axios.interceptors.response.use(response => {
const sessionCookie = Cookie.get()
console.log('Cookie', sessionCookie)
return response
})
在我的 DRF API 测试中,我可以看到会话 cookie 在响应中。
Set-Cookie: sessionid=zgndujlppk4rnn6gymgg1czhv1u0rqfc; expires=Thu, 11 Apr 2019 11:27:32 GMT; HttpOnly; Max-Age=1209600; Path=/; SameSite=Lax
class Test(APITestCase):
def test_get(self):
response = self.client.get('/store/1/')
print(response.cookies['sessionid']
【问题讨论】: