React 中缺少 Cookie,但 Django 中没有
Cookies missing in React but not in Django
我使用 SimpleJWT 和 RestFramework 进行身份验证。登录完成后,令牌存储在 cookie 中,请求发送到 React 中的登录 api。
class CustomTokenObtainPairView(TokenObtainPairView):
def post(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
try:
serializer.is_valid(raise_exception=True)
except TokenError as e:
raise InvalidToken(e.args[0])
# set access token in browser with Httponly cookie.
res = Response(serializer.validated_data, status=status.HTTP_200_OK)
access_token = serializer.validated_data['access']
res.set_cookie("access_token", access_token, max_age=settings.SIMPLE_JWT.get('ACCESS_TOKEN_LIFETIME').total_seconds(),samesite='Lax',secure=False, httponly=True)
return res
从 Django 访问的 Cookie:
print(request.COOKIES)
returns:
{'userVisitedBefore': 'true', 'tabstyle': 'html-tab', 'csrftoken': 'NECdxoDLb6fszteb8dB11ELh9l2keYUuHM13AaRAxHUHX45GJ9URloJnia9GrqCS', 'sessionid': 'jjafw09sok8wa05756ntjNr6nwxhg6q0', 'access_token': 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1niJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNjM0NTY1ODk0LCJpYXQiOjE2MzQ1NjQ5OTQsImp0aSI6Ijc1ZGY0Njc4MzY1ZDRlNjc5NDM1NTRlMTgzMTU5Nzc1IiwidXNlcl9pZCI6MX0.2Ew92rRIRvoxylpgRu4uGnRGdOuoPV7NSgmGxzS6bnw'}
从 React 访问的 Cookie:
const cookies = new Cookies();
console.log(cookies.getAll([]))
returns 这个 没有 access_token 和会话 ID:
{userVisitedBefore: 'true', tabstyle: 'html-tab', csrftoken: 'NECdxoDLb6fszteb8dB11ELh9l2keYUuhM13AaRAxHUHX45GJ9URloJnia9GrqCS'}
对于任何感兴趣的人:我的“解决方案”是通过 universal-cookie 将令牌保存在 Cookie 中,然后可以从 Django Views 和 React Frontend 访问它。此外,我没有通过 CustomTokenObtainView 保存它们,而是直接将它们保存在 React 登录组件中,如下所示:
axiosInstance
.post(`api/token/`, {
email: formData.email,
password: formData.password,
})
.then((res) => {
cookies.set('access_token', localStorage.getItem('access_token'), { path: '/'});
axiosInstance.defaults.headers['Authorization'] = 'JWT ' + localStorage.getItem('access_token');
history.push("");
location.reload();
}).catch(err => console.log(err));
我使用 SimpleJWT 和 RestFramework 进行身份验证。登录完成后,令牌存储在 cookie 中,请求发送到 React 中的登录 api。
class CustomTokenObtainPairView(TokenObtainPairView):
def post(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
try:
serializer.is_valid(raise_exception=True)
except TokenError as e:
raise InvalidToken(e.args[0])
# set access token in browser with Httponly cookie.
res = Response(serializer.validated_data, status=status.HTTP_200_OK)
access_token = serializer.validated_data['access']
res.set_cookie("access_token", access_token, max_age=settings.SIMPLE_JWT.get('ACCESS_TOKEN_LIFETIME').total_seconds(),samesite='Lax',secure=False, httponly=True)
return res
从 Django 访问的 Cookie:
print(request.COOKIES)
returns:
{'userVisitedBefore': 'true', 'tabstyle': 'html-tab', 'csrftoken': 'NECdxoDLb6fszteb8dB11ELh9l2keYUuHM13AaRAxHUHX45GJ9URloJnia9GrqCS', 'sessionid': 'jjafw09sok8wa05756ntjNr6nwxhg6q0', 'access_token': 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1niJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNjM0NTY1ODk0LCJpYXQiOjE2MzQ1NjQ5OTQsImp0aSI6Ijc1ZGY0Njc4MzY1ZDRlNjc5NDM1NTRlMTgzMTU5Nzc1IiwidXNlcl9pZCI6MX0.2Ew92rRIRvoxylpgRu4uGnRGdOuoPV7NSgmGxzS6bnw'}
从 React 访问的 Cookie:
const cookies = new Cookies();
console.log(cookies.getAll([]))
returns 这个 没有 access_token 和会话 ID:
{userVisitedBefore: 'true', tabstyle: 'html-tab', csrftoken: 'NECdxoDLb6fszteb8dB11ELh9l2keYUuhM13AaRAxHUHX45GJ9URloJnia9GrqCS'}
对于任何感兴趣的人:我的“解决方案”是通过 universal-cookie 将令牌保存在 Cookie 中,然后可以从 Django Views 和 React Frontend 访问它。此外,我没有通过 CustomTokenObtainView 保存它们,而是直接将它们保存在 React 登录组件中,如下所示:
axiosInstance
.post(`api/token/`, {
email: formData.email,
password: formData.password,
})
.then((res) => {
cookies.set('access_token', localStorage.getItem('access_token'), { path: '/'});
axiosInstance.defaults.headers['Authorization'] = 'JWT ' + localStorage.getItem('access_token');
history.push("");
location.reload();
}).catch(err => console.log(err));