【发布时间】:2020-12-01 19:28:33
【问题描述】:
我阅读了一些与在本地存储中存储 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
之后,每次我收到来自客户端的请求(使用 React 和 axios)时,我都可以在 django 视图中使用 request.COOKIES['token'] 访问 cookie。使用它我可以编写自己的身份验证函数,但我认为这不是一个完美的方法,因为通常,我们在 Authorization 标头中传递令牌,它根据令牌设置request.user,如果我使用这种方法,我不会无法使用 postman 进行测试和 django rest 框架 IsAuthenticated 类也寻找 request.user and request.user.is_authenticated 的 True 值。
问题2:如果令牌存储在httponly cookie中,如何将令牌作为授权头从客户端传递?
请帮助我。我对仅使用 http 的 cookie 的工作流程有点困惑,因为我通常将令牌存储在本地存储中,并且更容易检索令牌并从前端传递它。
【问题讨论】:
-
你有解决这个问题的办法吗?
-
还没有,@ArkaGhosh
-
@ArkaGhosh 你可以关注这个procoding.org/jwt-token-as-httponly-cookie-in-django
标签: python django authentication django-rest-framework cookie-httponly