首页 > 解决方案 > Django Graphql 的自动刷新令牌中间件

问题描述

我正在尝试在前端使用带有 Apollo Client 的 React 和在后端使用 Django GraphQl 来构建一个站点,并且我正在使用带有 jwt 令牌的 django-graphql-auth 来处理身份验证。

现在我正在尝试编写一个中间件,通过 http 标头获取访问和刷新令牌,如果访问令牌使用刷新令牌过期,我想刷新令牌。

我能够执行基本步骤,例如从请求中获取访问和刷新令牌,但无法弄清楚如何刷新访问令牌。

def refreshTokenMiddleWare(get_response):
# this middleware functionality is check the validity of the 
# token and if the access token is expired then the access token
# is refreshed and set the appropriate headers

def middleware(request):
    # implement the logic

    # get token and refresh token
    AUTH_HEADER = request.headers.get('authorization')
    refreshToken = request.headers.get('X-Refresh-Token')
    token = get_http_authorization(request)

    # check if the tokens are valid
    try:
        payload = jwt_settings.JWT_DECODE_HANDLER(token)
    except jwt.ExpiredSignature: 
        pass
        
    except jwt.DecodeError:
        raise exceptions.JSONWebTokenError(_('Error decoding signature'))
    except jwt.InvalidTokenError:
        raise exceptions.JSONWebTokenError(_('Invalid token')) 
    # check if token is expired

        # refresh token
        # add appropriate headers
    
    response = get_response(request)
    return response
return middleware

如果发生 jwt.ExpiredSignature 错误,我无法弄清楚要写什么。任何帮助将不胜感激。提前致谢。

标签: djangographqljwtrefresh-token

解决方案


推荐阅读