【问题标题】:How to use http only cookie with django rest framework?如何在 django rest 框架中使用 http only cookie?
【发布时间】: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 的工作流程有点困惑,因为我通常将令牌存储在本地存储中,并且更容易检索令牌并从前端传递它。

【问题讨论】:

标签: python django authentication django-rest-framework cookie-httponly


【解决方案1】:

答案 1:

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

虽然localStorage 可通过javascript(与HttpOnly cookie 相对)访问,但它容易受到XSS 攻击。 所以我认为使用httponly cookies + CSRF 是最安全的方式,即使在 TokenAuthentication 中用于在客户端存储令牌。但是,DRF 和我查看过的其他流行库并没有很好地支持这一点。

答案 2:

不,因为您无法从客户端使用javascript 检索httponly cookie。这是httponly cookie 的一大优势。所以此cookie 只能通过http(s) 请求访问。 确保双方的withCredentials 为True。

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

【讨论】:

    猜你喜欢
    • 2021-11-06
    • 2016-02-17
    • 2021-12-28
    • 2018-04-08
    • 2021-12-05
    • 1970-01-01
    • 1970-01-01
    • 2021-02-19
    • 2017-02-22
    相关资源
    最近更新 更多