第二章 基本使用

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

    在最简单的模式下,flask_jwt_extend 没有多少东西可以使用。我们只需要通过 create_access_token()新建一个JWT字符串,通过jwt_required()装饰器去保护那些需要有效token的访问点(endpoint),通过get_jwt_identity()函数获取jwt中的identitiy。

    from flask import Flask, jsonify, request
    from flask_jwt_extended import (
        JWTManager, jwt_required, create_access_token,
        get_jwt_identity
    )
    
    app = Flask(__name__)
    
    # 设置flask - jwt-extend
    app.config['JWT_SECRET_KEY'] = 'super-secret'  # Change this!
    jwt = JWTManager(app)
    
    
    # 提供访问创建令牌环的方法. 
    #The create_access_token()函数是用来生成令牌,
    # 你可以选择把生成的令牌返回给调用者
    @app.route('/login', methods=['POST'])
    def login():
        if not request.is_json:
            return jsonify({"msg": "Missing JSON in request"}), 400
    
        username = request.json.get('username', None)
        password = request.json.get('password', None)
        if not username:
            return jsonify({"msg": "Missing username parameter"}), 400
        if not password:
            return jsonify({"msg": "Missing password parameter"}), 400
    
        if username != 'test' or password != 'test':
            return jsonify({"msg": "Bad username or password"}), 401
    
        # Identity 参数可以是任何json序列化的数据
        access_token = create_access_token(identity=username)
        return jsonify(access_token=access_token), 200
    
    
    # 使用jwt_required装饰器来保护那些需要有效token的视图
    @app.route('/protected', methods=['GET'])
    @jwt_required
    def protected():
        # Access the identity of the current user with get_jwt_identity
        current_user = get_jwt_identity()
        return jsonify(logged_in_as=current_user), 200
    
    
    if __name__ == '__main__':
        app.run()
    

    To access a jwt_required protected view, all we have to do is send in the JWT with the request. By default, this is done with an authorization header that looks like:
    为了访问被jwt_required保护的视图,我们要做的就是把jwt字符串连同request请求一起发送到服务器端,默认情况下,我们通过一个如下所示的认证头部来完成:

    Authorization: Bearer <access_token>
    

    我们可以通过curl命令来测试上面的代码:

    $ curl http://localhost:5000/protected
    {
      "msg": "Missing Authorization Header"
    }
    
    $ curl -H "Content-Type: application/json" -X POST \
      -d '{"username":"test","password":"test"}' http://localhost:5000/login
    {
      "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmcmVzaCI6dHJ1ZSwianRpIjoiZjhmNDlmMjUtNTQ4OS00NmRjLTkyOWUtZTU2Y2QxOGZhNzRlIiwidXNlcl9jbGFpbXMiOnt9LCJuYmYiOjE0NzQ0NzQ3OTEsImlhdCI6MTQ3NDQ3NDc5MSwiaWRlbnRpdHkiOiJ0ZXN0IiwiZXhwIjoxNDc0NDc1NjkxLCJ0eXBlIjoiYWNjZXNzIn0.vCy0Sec61i9prcGIRRCbG8e9NV6_wFH2ICFgUGCLKpc"
    }
    
    $ export ACCESS="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmcmVzaCI6dHJ1ZSwianRpIjoiZjhmNDlmMjUtNTQ4OS00NmRjLTkyOWUtZTU2Y2QxOGZhNzRlIiwidXNlcl9jbGFpbXMiOnt9LCJuYmYiOjE0NzQ0NzQ3OTEsImlhdCI6MTQ3NDQ3NDc5MSwiaWRlbnRpdHkiOiJ0ZXN0IiwiZXhwIjoxNDc0NDc1NjkxLCJ0eXBlIjoiYWNjZXNzIn0.vCy0Sec61i9prcGIRRCbG8e9NV6_wFH2ICFgUGCLKpc"
    
    $ curl -H "Authorization: Bearer $ACCESS" http://localhost:5000/protected
    {
      "logged_in_as": "test"
    }
    

    相关文章

      网友评论

        本文标题:第二章 基本使用

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