@@ -72,6 +72,55 @@ $ curl --write-out "%{http_code}\n" -H "Authorization: Bearer $ACCESS" http://lo
7272```
7373However, this is only the tip of the iceberg for what we can do
7474
75+
76+ ### Adding Custom Claims to the Access Token
77+ You may want to store additional information in the access token. Perhaps you want
78+ to save the access roles this user has so you can access them in the view functions
79+ (without having to make a database call each time). This can be done with the
80+ user_claims_loader, and access with the 'get_jwt_claims()' method in a protected endpoint
81+ ``` python
82+ from flask import Flask, jsonify, request
83+ from flask_jwt_extended import JWTManager, jwt_required, create_access_token, \
84+ get_jwt_claims
85+
86+ app = Flask(__name__ )
87+ app.secret_key = ' super-secret' # Change this!
88+ jwt = JWTManager(app)
89+
90+
91+ @jwt.user_claims_loader
92+ def add_claims_to_access_token (identity ):
93+ # These must be json serializable
94+ return {
95+ ' hello' : identity,
96+ ' foo' : [' bar' , ' baz' ]
97+ }
98+
99+
100+ @app.route (' /login' , methods = [' POST' ])
101+ def login ():
102+ username = request.json.get(' username' , None )
103+ password = request.json.get(' password' , None )
104+ if username != ' test' and password != ' test' :
105+ return jsonify({" msg" : " Bad username or password" }), 401
106+
107+ ret = {' access_token' : create_access_token(username)}
108+ return jsonify(ret), 200
109+
110+
111+ @app.route (' /protected' , methods = [' GET' ])
112+ @jwt_required
113+ def protected ():
114+ claims = get_jwt_claims()
115+ return jsonify({
116+ ' hello_is' : claims[' hello' ],
117+ ' foo_is' : claims[' foo' ]
118+ }), 200
119+
120+ if __name__ == ' __main__' :
121+ app.run()
122+ ```
123+
75124### Refresh Tokens
76125Flask-JWT-Extended supports [ refresh tokens] (https://auth0.com/blog/refresh-tokens-what-are-they-and-when-to-use-them/ )
77126out of the box. These are longer lived token which cannot access a jwt_required protected
@@ -271,9 +320,6 @@ The available loader functions are:
271320* needs_fresh_token_loader
272321* revoked_token_loader (see Blacklist and Token Revoking bellow)
273322
274- ### Adding Custom Claims to the Access Token
275- TODO
276-
277323### Options
278324TODO
279325
0 commit comments