我阅读了一些与在本地存储中存储 jwt 令牌相关的问题,这就是我尝试将令牌存储在 http-only cookie 中的原因。我正在使用以下方法。
from rest_framework.views import APIView
from rest_framework.response import Response
import jwt
from django.conf import settings
from rest_framework import status
class LoginView(APIView):
def post(self, request, format=None):
email = request.data['email']
password = request.data['password']
# dummy user authentication
if email == 'email' and password == 'password':
encoded = jwt.encode(
{'email': email}, settings.SECRET_KEY, algorithm='HS256')
response = Response()
response.set_cookie(key='token', value=encoded, httponly=True)
response.data = {
'user': email,
}
return response
else:
return Response({'error': 'wrong credentials'}, status=status.HTTP_401_UNAUTHORIZED)
问题 1:这是使用 django rest 框架设置 httponly cookie 的正确方法吗?
response = Response()
response.set_cookie(key='token', value=encoded, httponly=True)
response.data = {
'user': email,
}
return response
在此之后,每次我收到来自客户端的请求(使用带有 axios 的 React)时,我都可以request.COOKIES['token']
在 django 视图中访问 cookie。使用它我可以编写自己的身份验证函数,但我认为这不是一个完美的方法,因为通常,我们在 Authorization 标头中传递令牌,它request.user
基于令牌设置,如果我使用这种方法,我将无法使用postman for testing 和 django rest frameworksIsAuthenticated
类也寻找request.user and request.user.is_authenticated
True 值。
问题2:如果令牌存储在httponly cookie中,如何将令牌作为授权标头从客户端传递?
请帮我。我对仅使用 http 的 cookie 的工作流程感到有些困惑,因为我通常将令牌存储在本地存储中,并且更容易检索令牌并从前端传递它。