Skip to content

Commit 8e358c9

Browse files
committed
Complete the "Claims mapping" section with real example
1 parent 1fa4dbb commit 8e358c9

File tree

1 file changed

+49
-2
lines changed

1 file changed

+49
-2
lines changed

docs/references/tutorials.md

Lines changed: 49 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,8 @@ the documentation.
99

1010
## User authentication
1111

12-
For the basic authentication, you must already have generated the client ID and secret to configure
13-
your `OAuth2Middleware` with at least one client configuration.
12+
By following the [integration](/integration/integration) docs, for the basic authentication, you must already have
13+
generated the client ID and secret to configure your `OAuth2Middleware` with at least one client configuration.
1414

1515
1. Go to the developer console or settings of your OAuth2 identity provider and generate new client credentials.
1616
2. Provide the [client configuration](/integration/configuration#oauth2client) with the obtained client ID and secret
@@ -28,6 +28,53 @@ contain the user information obtained from the IDP.
2828

2929
## Claims mapping
3030

31+
The `Claims` class includes permanent attributes like `display_name`, `identity`, `picture`, and `email`. It also allows
32+
for custom attributes. Each attribute can either be a string or a callable function that takes user data and returns a
33+
string. Suppose the user data obtained from IDP looks like follows, and you need to map the corresponding attributes for
34+
the user provisioning and other stuff.
35+
36+
```json
37+
{
38+
"id": 54321,
39+
"sub": "1234567890",
40+
"name": "John Doe",
41+
"provider": "github",
42+
"emails": [
43+
44+
],
45+
"avatar_url": "https://example.com/john.doe.png"
46+
}
47+
```
48+
49+
It looks easy for the `picture` and `display_name` attributes, but how to map `email` from `emails` or create a
50+
unique `identity` attribute. Well, that is where the callable functions come in handy. You can use the `lambda` function
51+
to map the attributes as follows.
52+
53+
```python
54+
Claims(
55+
picture="image",
56+
display_name="avatar_url",
57+
email=lambda u: u.emails[0],
58+
identity=lambda u: f"{u.provider}:{u.sub}",
59+
)
60+
```
61+
62+
::: info NOTE
63+
64+
Not all IDPs provide the `first_name` and the `last_name` attributes already joined as in the example or the `email` as
65+
a list. So you are given the flexibility using transformer function to map the attributes as you want.
66+
67+
```mermaid
68+
flowchart LR
69+
IDPUserData("display_name string")
70+
FastAPIUserData("first_name string\nlast_name string")
71+
Transform[["transform into desired format"]]
72+
FastAPIUserData --> Transform
73+
Transform --> IDPUserData
74+
```
75+
76+
:::
77+
3178
## CSRF protection
3279

3380
## PKCE support

0 commit comments

Comments
 (0)