Skip to content

Commit 6f85731

Browse files
committed
Docs for better jwt user identity with complex objects (refs #11)
1 parent 10780a1 commit 6f85731

File tree

2 files changed

+15
-14
lines changed

2 files changed

+15
-14
lines changed

docs/tokens_from_complex_object.rst

+4-4
Original file line numberDiff line numberDiff line change
@@ -17,10 +17,10 @@ this user has. This isn't a huge deal, but obviously it could be more efficient.
1717
This extension provides the ability to pass any object to the **create_access_token**
1818
method, which will then be passed to the **user_claims_loader** method. This lets
1919
us access the database only once. However, as we still need the identity to be
20-
a JSON serializable object unique to this user, we need
21-
to take an addition step and use the optional **identity_lookup** kwarg in the
22-
**create_access_token** method. This lets us tell the system how to get the identity from
23-
an object.
20+
a JSON serializable object unique to this user. We have a second jwt decorator
21+
we can use for this, **user_identity_loader**. This lets you create a function
22+
which takes any object passed in to the **create_access_token** and return
23+
a json serializable identity from that object.
2424

2525
Here is an example of this in action
2626

examples/tokens_from_complex_objects.py

+11-10
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,14 @@ def add_claims_to_access_token(user):
2525
return {'roles': user.roles}
2626

2727

28+
# This method will also get whatever object is passed into the
29+
# create_access_token method, and let us define what the identity
30+
# should be for this object
31+
@jwt.user_identity_loader
32+
def user_identity_lookup(user):
33+
return user.username
34+
35+
2836
@app.route('/login', methods=['POST'])
2937
def login():
3038
username = request.json.get('username', None)
@@ -38,17 +46,10 @@ def login():
3846
# We can now pass this complex object directly to the
3947
# create_access_token method. This will allow us to access
4048
# 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
49+
# function, and get the identity of this object from the
50+
# user_identity_loader function.
4651
# 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+
access_token = create_access_token(identity=user)
5253
ret = {'access_token': access_token}
5354
return jsonify(ret), 200
5455

0 commit comments

Comments
 (0)