gpt4 book ai didi

django-rest-framework 使用 HttpOnly Cookie

转载 作者:行者123 更新时间:2023-12-04 15:06:02 24 4
gpt4 key购买 nike

使用后djangorestframework-jwt一年多来以一种不安全的方式,我终于决定我想让它以一种更安全的方式工作。
我到处都读过不利于在本地客户端(例如本地存储)中保存 JWT token 的内容,并且最好的解决方案是改用 HttpOnly cookie。
我知道 HttpOnly cookie 确实是一个 cookie,可以保存但不能被浏览器读取。所以我认为它可以像下面这样使用:

  • get_token:客户端通过发送用户名和密码向服务器请求授权 token :如果用户名和密码有效,则服务器以 httpOnly cookie 响应,客户端可以存储但不能读取该cookie。
  • 客户端从现在开始执行的每个请求都被授权,因为在 HttpOnly cookie 中有一个有效的授权 token 。
  • refresh_token:一旦客户端需要刷新token,它只需要请求一个refresh_token:如果发送的cookie包含一个有效的token,服务器将响应一个带有新token的更新的HttpOnly cookie。

  • 我现在正在尝试通过使用 HttpOnly cookie 来使用 djangorestframework-jwt,而 JWT_AUTH_COOKIE 配置似乎是最合适的配置:

    You can set JWT_AUTH_COOKIE a string if you want to use http cookies in addition to the Authorization header as a valid transport for the token. The string you set here will be used as the cookie name that will be set in the response headers when requesting a token. The token validation procedure will also look into this cookie, if set. The 'Authorization' header takes precedence if both the header and the cookie are present in the request.

    Default is None and no cookie is set when creating tokens nor accepted when validating them.


    在给 JWT_AUTH_COOKIE 一个字符串值之后,我收到了一个 httpOnly cookie,如预期的那样。
    问题:
    当我调用 refreshToken 时,我得到以下响应:
    {"token":["This field is required."]}
    没错,我没有在请求的 HEADER 中发送任何 token ,这就是我想要的,因为客户端不应该将它保存在任何地方。
    这就是我感到困惑的地方:
    如果我从现在开始对客户端对服务器的每个请求都没有错,那么应该将 cookie 添加到请求中。
    服务器不应该在看到 Header 中没有传递任何 token 后检查 cookie 吗?如果不是这样,它应该如何工作?
    如果有人想为改进做出贡献,还在这里发布了一个 Github 问题: https://github.com/jpadilla/django-rest-framework-jwt/issues/482

    最佳答案

    您观察到的问题是正确的,因为尚未使用 cookie 实现刷新 token API。

    这可能是代码本身的错误。但是没有什么能限制你解决这个问题。

    您也可以修补 View 以处理基于 cookie 的身份验证。将以下代码添加到您的 urls.py 的顶部它会处理同样的事情

    from rest_framework_jwt.settings import api_settings

    if api_settings.JWT_AUTH_COOKIE:
    from rest_framework_jwt.authentication import JSONWebTokenAuthentication
    from rest_framework_jwt.serializers import RefreshJSONWebTokenSerializer
    from rest_framework_jwt.views import RefreshJSONWebToken

    RefreshJSONWebTokenSerializer._declared_fields.pop('token')

    class RefreshJSONWebTokenSerializerCookieBased(RefreshJSONWebTokenSerializer):
    def validate(self, attrs):
    if 'token' not in attrs:
    if api_settings.JWT_AUTH_COOKIE:
    attrs['token'] = JSONWebTokenAuthentication().get_jwt_value(self.context['request'])
    return super(RefreshJSONWebTokenSerializerCookieBased, self).validate(attrs)

    RefreshJSONWebToken.serializer_class = RefreshJSONWebTokenSerializerCookieBased

    Refresh working with cookies

    关于django-rest-framework 使用 HttpOnly Cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56587690/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com