第八章 Refresh Tokens

Flask-JWT-Extended 支持开箱即用的刷新token,一旦旧的访问令牌过期,就可以使用这些长期可用的token(refresh token)创建新的访问令牌。刷新令牌(refresh token)不能访问受jwt_required()保护的端点,访问令牌(access token)也不能访问受jwt_refresh_token_required()保护的端点。通过将访问令牌设置为较短的生存期(请参阅配置选项),并利用refresh令牌,我们可以帮助减少在访问令牌被窃取时可能造成的损害。但是,如果攻击者染指了refresh token,他们可以继续生成新的访问令牌并访问受保护的端点,就好像他就是那个用户一样。我们可以通过使用下一节讨论的fresh令牌模式来帮助解决这个问题。
下面是一个使用访问和刷新令牌的例子:

from flask import Flask, jsonify, request
from flask_jwt_extended import (
    JWTManager, jwt_required, create_access_token,
    jwt_refresh_token_required, create_refresh_token,
    get_jwt_identity
)

app = Flask(__name__)

app.config['JWT_SECRET_KEY'] = 'super-secret'  # Change this!
jwt = JWTManager(app)


@app.route('/login', methods=['POST'])
def login():
    username = request.json.get('username', None)
    password = request.json.get('password', None)
    if username != 'test' or password != 'test':
        return jsonify({"msg": "Bad username or password"}), 401

    # Use create_access_token() and create_refresh_token() to create our
    # access and refresh tokens
    ret = {
        'access_token': create_access_token(identity=username),
        'refresh_token': create_refresh_token(identity=username)
    }
    return jsonify(ret), 200


# The jwt_refresh_token_required decorator insures a valid refresh
# token is present in the request before calling this endpoint. We
# can use the get_jwt_identity() function to get the identity of
# the refresh token, and use the create_access_token() function again
# to make a new access token for this identity.
@app.route('/refresh', methods=['POST'])
@jwt_refresh_token_required
def refresh():
    current_user = get_jwt_identity()
    ret = {
        'access_token': create_access_token(identity=current_user)
    }
    return jsonify(ret), 200


@app.route('/protected', methods=['GET'])
@jwt_required
def protected():
    username = get_jwt_identity()
    return jsonify(logged_in_as=username), 200


if __name__ == '__main__':
    app.run()

你可能感兴趣的:(第八章 Refresh Tokens)