首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在django rest框架中使用http cookie?

如何在django rest框架中使用http cookie?
EN

Stack Overflow用户
提问于 2020-08-12 04:44:08
回答 1查看 2.6K关注 0票数 5

我读到了与将jwt令牌存储在本地存储中有关的一些问题,这就是为什么我试图将令牌存储在仅限于http的cookie中。我正在使用以下方法。

代码语言:javascript
运行
复制
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的正确方法吗?

代码语言:javascript
运行
复制
response = Response()
response.set_cookie(key='token', value=encoded, httponly=True)
response.data = {
    'user': email,
}
return response

在此之后,每当我从客户端收到请求(使用React )时,我就可以在django视图中使用request.COOKIES['token']访问cookie。使用此方法,我可以编写自己的身份验证函数,但我不认为这是一种完美的方法,因为一般来说,我们在授权头中传递令牌,它根据令牌设置request.user,如果使用这种方法,我将不能使用postman进行测试,django rest框架IsAuthenticated类也会查找request.user and request.user.is_authenticated的真实值。

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

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

EN

回答 1

Stack Overflow用户

发布于 2021-02-18 20:16:23

答案1:

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

虽然localStorage可以通过javascript (而不是HttpOnly cookie)访问,并使其易受XSS攻击。因此,我认为使用httponly cookies + CSRF是最安全的方法,甚至在TokenAuthentication中也是在客户端存储令牌的最安全方式。但是,DRF和其他我看过的流行库并不很好地支持这一点。

答案2:

不,因为您不能从客户端使用httponly javascript检索cookie,这是httponly cookie.So的一个很大的优势--这个cookie只能通过http(s)请求访问。确保两边的withCredentials都是True

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63369903

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档