5

我阅读了一些与在本地存储中存储 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 视图中访问 c​​ookie。使用它我可以编写自己的身份验证函数,但我认为这不是一个完美的方法,因为通常,我们在 Authorization 标头中传递令牌,它request.user基于令牌设置,如果我使用这种方法,我将无法使用postman for testing 和 django rest frameworksIsAuthenticated类也寻找request.user and request.user.is_authenticatedTrue 值。

问题2:如果令牌存储在httponly cookie中,如何将令牌作为授权标头从客户端传递?

请帮我。我对仅使用 http 的 cookie 的工作流程感到有些困惑,因为我通常将令牌存储在本地存储中,并且更容易检索令牌并从前端传递它。

4

1 回答 1

0

答案1:

是的,这是设置httponly标志 cookie 的好方法,因为 httpOnlycookie 无法访问JavaScript。如果没有httponly标志 cookie,它很容易受到CSRF攻击。

WhilelocalStorage可以通过javascript(而不是HttpOnlycookie)访问,并使其容易受到XSS攻击。所以我认为使用httponly cookies+CSRF是最安全的方式,即使在 TokenAuthentication 中用于在客户端存储令牌。DRF但是,这并没有得到我看过的其他流行库的很好支持。

答案 2:

不,因为你不能通过从客户端httponly使用来检索 cookie。这是 cookiejavascript的一大优势。httponly所以这个 cookie 只能通过http(s)请求访问。确保withCredentials适用True于双方。

我个人使用djangorestframework-simplejwt包在cookie中设置(access token+CSRF令牌)httponly并使用CustomAuthentication类获取。 检查这个

于 2021-02-18T20:16:23.293 回答