【问题标题】:How to reset JWT token in Django after user changes password?用户更改密码后如何在 Django 中重置 JWT 令牌?
【发布时间】:2020-05-13 19:51:03
【问题描述】:

我的问题是,当有人重置他或她的密码时,我想刷新或过期 JWT 令牌。我的项目在 Django rest 框架中,所以我需要的只是一个关于如何发生的示例。我需要能够使所有其他令牌无效

最热烈的问候。

【问题讨论】:

    标签: django django-rest-framework jwt change-password


    【解决方案1】:

    默认情况下,如果您不更新会话身份验证,则用户将被注销。 如果你想更新会话身份验证,这里是代码

    from django.contrib.auth import update_session_auth_hash
    
    #after you change password for User- user
    update_session_auth_hash(request, user)
    

    【讨论】:

    • 这会使旧的 jwt 令牌过期吗?
    • 我想让现有的令牌无效
    • 自动失效了,你有没有尝试去其他链接。
    【解决方案2】:

    您需要覆盖默认令牌生成过程。

    def jwt_create_payload(user):
        """
        Create JWT claims token.
    
        To be more standards-compliant please refer to the official JWT standards
        specification: https://tools.ietf.org/html/rfc7519#section-4.1
        """
    
        issued_at_time = datetime.utcnow()
        expiration_time = issued_at_time + api_settings.JWT_EXPIRATION_DELTA
    
        payload = {
            'user_id': user.pk,
            'username': '%s-%s' % (user.username + user.password),
            'iat': unix_epoch(issued_at_time),
            'exp': expiration_time
        }
    
        # It's common practice to have user object attached to profile objects.
        # If you have some other implementation feel free to create your own
        # `jwt_create_payload` method with custom payload.
        if hasattr(user, 'profile'):
            payload['user_profile_id'] = user.profile.pk if user.profile else None,
    
        # Include original issued at time for a brand new token
        # to allow token refresh
        if api_settings.JWT_ALLOW_REFRESH:
            payload['orig_iat'] = unix_epoch(issued_at_time)
    
        if api_settings.JWT_AUDIENCE is not None:
            payload['aud'] = api_settings.JWT_AUDIENCE
    
        if api_settings.JWT_ISSUER is not None:
            payload['iss'] = api_settings.JWT_ISSUER
    
        return payload
    

    根据新的jwt_create_payload 函数更新您的设置中的JWT_PAYLOAD_HANDLER 参数。当您更改密码时,您的令牌将失效。

    【讨论】:

    • 感谢我朋友的帮助,但这对任何想要重置密码的人都有效吗?
    • 一个 JWT 令牌是基于 payload 值生成的。当其中任何一个发生变化时,令牌就会过期。当密码改变时(当然相应的加密密码也会过期)JWT token 会过期。
    猜你喜欢
    • 2021-12-29
    • 2020-03-27
    • 2012-03-19
    • 2018-02-24
    • 1970-01-01
    • 2020-02-11
    • 2023-03-27
    • 1970-01-01
    • 2015-10-11
    相关资源
    最近更新 更多