|
| 1 | +from flask import Flask, jsonify, request |
| 2 | +from flask_jwt_extended import JWTManager, jwt_required, \ |
| 3 | + create_access_token, get_jwt_identity |
| 4 | + |
| 5 | +app = Flask(__name__) |
| 6 | +app.secret_key = 'super-secret' # Change this! |
| 7 | + |
| 8 | +# Setup the Flask-JWT-Extended extension |
| 9 | +jwt = JWTManager(app) |
| 10 | + |
| 11 | + |
| 12 | +# This is a simple example of a complex object that we could build |
| 13 | +# a JWT from. In practice, this will normally be something that |
| 14 | +# requires a lookup from disk (such as SQLAlchemy) |
| 15 | +class UserObject: |
| 16 | + def __init__(self, username, roles): |
| 17 | + self.username = username |
| 18 | + self.roles = roles |
| 19 | + |
| 20 | + |
| 21 | +# This method will get whatever object is passed into the |
| 22 | +# create_access_token method. |
| 23 | +@jwt.user_claims_loader |
| 24 | +def add_claims_to_access_token(user): |
| 25 | + return {'roles': user.roles} |
| 26 | + |
| 27 | + |
| 28 | +@app.route('/login', methods=['POST']) |
| 29 | +def login(): |
| 30 | + username = request.json.get('username', None) |
| 31 | + password = request.json.get('password', None) |
| 32 | + if username != 'test' and password != 'test': |
| 33 | + return jsonify({"msg": "Bad username or password"}), 401 |
| 34 | + |
| 35 | + # Create an example UserObject |
| 36 | + user = UserObject(username='test', roles=['foo', 'bar']) |
| 37 | + |
| 38 | + # We can now pass this complex object directly to the |
| 39 | + # create_access_token method. This will allow us to access |
| 40 | + # the properties of this object in the user_claims_loader |
| 41 | + # function. Because this object is not json serializable itself, |
| 42 | + # we also need to provide a way to get some which is json |
| 43 | + # serializable and represents the identity of this token from |
| 44 | + # the complex object. We pass a function to the optional |
| 45 | + # identity_lookup kwarg, which tells the create_access_token |
| 46 | + # function how to get the identity from this object |
| 47 | + access_token = create_access_token( |
| 48 | + identity=user, |
| 49 | + identity_lookup=lambda u: u.username |
| 50 | + ) |
| 51 | + |
| 52 | + ret = {'access_token': access_token} |
| 53 | + return jsonify(ret), 200 |
| 54 | + |
| 55 | + |
| 56 | +@app.route('/protected', methods=['GET']) |
| 57 | +@jwt_required |
| 58 | +def protected(): |
| 59 | + current_user = get_jwt_identity() |
| 60 | + return jsonify({'hello_from': current_user}), 200 |
| 61 | + |
| 62 | +if __name__ == '__main__': |
| 63 | + app.run() |
0 commit comments