使用刷新令牌颁发新的访问令牌后继续请求流



我无法弄清楚在刷新Flask应用程序中过期的JWT令牌后如何继续请求流。

我将access tokenrefresh token存储在各自的 cookie 中。

这是我的流程现在的样子:

下面是我的装饰器函数,用于检查JWT令牌的有效性

def check_valid_jwt(f):
    @wraps(f)
    def wrapper():
        print(request.cookies)
        if 'access_token_cookie' in request.cookies:
            print('Verify Signature')
            # some code that verifies the JWT signature
            print('Signature verification successful')
            # some code that extracts claims from the token
            if time.time() > claims['exp']:
                print('Token is expired')
                # some code that get the new access token using refresh token
                # What am I supposed to do here after I get the refresh token and continue the request while adding the new token to access_token cookie?
            return f()
    return wrapper

以下是受保护终结点的外观:

@check_valid_jwt
def secretpage():
    return render_template("/home/secret_page.html")

获得刷新令牌后,我想继续请求流并在 cookie 中添加新的access token,但如果我check_valid_jwt装饰器函数中添加它,secretpage处理程序将不知道已经发出了新的access token

我如何做到这一点,如果发布了新的access token,它就会被添加到响应中。我在这里完整吗,这不是Authentication流程的工作方式?

最好的方法是为 JWT 身份验证创建一个中间件,而不是装饰器

from flask import Flask

class JWTAuthMiddleware(object):
    def __init__(self, app):
        self.app = app  
    def __call__(self, environ, start_response):
        access_token = environ.get('HTTP_AUTHORIZATION', None)
        # validate access token here and get new one if required by using refresh token
        # you can also update the invalid token in the header here if you want
        environ['HTTP_AUTHORIZATION'] = 'new access token'
        return self.app(environ, start_response)

现在用这个包装实际的 wsgi 应用程序

app = Flask(__name__)
app.wsgi_app = JWTAuthMiddleware(app.wsgi_app)

最新更新