第四章 在JWT token中存储自定义数据

作者: suenism | 来源:发表于2020-02-15 22:05 被阅读0次

    您可能希望在访问令牌(access token)中存储其他信息,并且这些信息可以在在受保护的视图中访问。以上需求可以使用user_claims_loader()装饰器实现,并可以使用get_jwt_claims()函数在受保护的端点中访问数据。
    将数据存储在访问令牌中有助于提高性能。如果您将数据存储在令牌中,那么下次需要在受保护的端点中使用数据时,就不需要从磁盘查找数据。但是,您应该注意在令牌中放入了什么数据。任何能够读取令牌的人都可以轻松地查看访问令牌中的任何数据。不要在访问令牌中存储敏感信息(例如用户名和密码等)!

    from flask import Flask, jsonify, request
    from flask_jwt_extended import (
        JWTManager, jwt_required, create_access_token,
        get_jwt_claims
    )
    
    app = Flask(__name__)
    
    app.config['JWT_SECRET_KEY'] = 'super-secret'  # Change this!
    jwt = JWTManager(app)
    
    
    # Using the user_claims_loader, we can specify a method that will be
    # called when creating access tokens, and add these claims to the said
    # token. This method is passed the identity of who the token is being
    # created for, and must return data that is json serializable
    @jwt.user_claims_loader
    def add_claims_to_access_token(identity):
        return {
            'hello': identity,
            'foo': ['bar', 'baz']
        }
    
    
    @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
    
        ret = {'access_token': create_access_token(username)}
        return jsonify(ret), 200
    
    
    # In a protected view, get the claims you added to the jwt with the
    # get_jwt_claims() method
    @app.route('/protected', methods=['GET'])
    @jwt_required
    def protected():
        claims = get_jwt_claims()
        return jsonify({
            'hello_is': claims['hello'],
            'foo_is': claims['foo']
        }), 200
    
    
    if __name__ == '__main__':
        app.run()
    

    相关文章

      网友评论

        本文标题:第四章 在JWT token中存储自定义数据

        本文链接:https://www.haomeiwen.com/subject/ufkufhtx.html