fastapi-identity-model 0.2.3__tar.gz → 0.4.0a1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. {fastapi_identity_model-0.2.3 → fastapi_identity_model-0.4.0a1}/.gitignore +11 -2
  2. fastapi_identity_model-0.4.0a1/CHANGELOG.md +286 -0
  3. fastapi_identity_model-0.4.0a1/PKG-INFO +241 -0
  4. fastapi_identity_model-0.4.0a1/README.md +211 -0
  5. {fastapi_identity_model-0.2.3 → fastapi_identity_model-0.4.0a1}/fastapi_identity_model/__init__.py +9 -2
  6. fastapi_identity_model-0.4.0a1/fastapi_identity_model/config.py +155 -0
  7. fastapi_identity_model-0.4.0a1/fastapi_identity_model/config_helpers.py +92 -0
  8. {fastapi_identity_model-0.2.3 → fastapi_identity_model-0.4.0a1}/fastapi_identity_model/dependencies.py +59 -29
  9. fastapi_identity_model-0.4.0a1/fastapi_identity_model/middleware.py +608 -0
  10. fastapi_identity_model-0.4.0a1/fastapi_identity_model/options.py +269 -0
  11. {fastapi_identity_model-0.2.3 → fastapi_identity_model-0.4.0a1}/fastapi_identity_model/rp.py +218 -66
  12. fastapi_identity_model-0.4.0a1/fastapi_identity_model/token_manager.py +330 -0
  13. fastapi_identity_model-0.4.0a1/fastapi_identity_model/ws.py +290 -0
  14. {fastapi_identity_model-0.2.3 → fastapi_identity_model-0.4.0a1}/pyproject.toml +15 -8
  15. fastapi_identity_model-0.4.0a1/tests/test_config.py +185 -0
  16. fastapi_identity_model-0.4.0a1/tests/test_dependencies.py +162 -0
  17. fastapi_identity_model-0.4.0a1/tests/test_http_client_passthrough.py +287 -0
  18. {fastapi_identity_model-0.2.3 → fastapi_identity_model-0.4.0a1}/tests/test_middleware.py +133 -27
  19. fastapi_identity_model-0.4.0a1/tests/test_middleware_token_binding.py +1308 -0
  20. fastapi_identity_model-0.4.0a1/tests/test_oidc_settings_from_env.py +208 -0
  21. fastapi_identity_model-0.4.0a1/tests/test_rp.py +914 -0
  22. {fastapi_identity_model-0.2.3 → fastapi_identity_model-0.4.0a1}/tests/test_security_cnf_bound_as_bearer.py +16 -22
  23. {fastapi_identity_model-0.2.3 → fastapi_identity_model-0.4.0a1}/tests/test_security_error_oracle.py +2 -2
  24. {fastapi_identity_model-0.2.3 → fastapi_identity_model-0.4.0a1}/tests/test_security_id_token_substitution.py +2 -2
  25. fastapi_identity_model-0.4.0a1/tests/test_token_manager.py +428 -0
  26. fastapi_identity_model-0.4.0a1/tests/test_ws.py +277 -0
  27. fastapi_identity_model-0.2.3/CHANGELOG.md +0 -94
  28. fastapi_identity_model-0.2.3/PKG-INFO +0 -139
  29. fastapi_identity_model-0.2.3/README.md +0 -109
  30. fastapi_identity_model-0.2.3/fastapi_identity_model/config.py +0 -83
  31. fastapi_identity_model-0.2.3/fastapi_identity_model/middleware.py +0 -287
  32. fastapi_identity_model-0.2.3/fastapi_identity_model/token_manager.py +0 -162
  33. fastapi_identity_model-0.2.3/tests/test_config.py +0 -76
  34. fastapi_identity_model-0.2.3/tests/test_dependencies.py +0 -107
  35. fastapi_identity_model-0.2.3/tests/test_rp.py +0 -398
  36. fastapi_identity_model-0.2.3/tests/test_token_manager.py +0 -150
  37. {fastapi_identity_model-0.2.3 → fastapi_identity_model-0.4.0a1}/fastapi_identity_model/py.typed +0 -0
@@ -157,10 +157,16 @@ token_characterization_*.md
157
157
  .claude/review-*.patch
158
158
  .claude/pre-review-sha.txt
159
159
 
160
- # Conformance plan export zips + per-test RP logs (binary evidence artifacts;
161
- # preserved via CI upload-artifact, not committed)
160
+ # Conformance plan export zips, certification packages, and per-test RP logs
161
+ # (binary evidence artifacts; preserved via CI upload-artifact and retained by
162
+ # the OIDF portal, not committed). The parent-directory patterns matter because
163
+ # browser downloads of certification packages land in conformance/results/
164
+ # rather than hosted/, which previously left them as untracked noise.
162
165
  conformance/results/hosted/*.zip
166
+ conformance/results/hosted/*.pdf
163
167
  conformance/results/hosted/rp-logs/
168
+ conformance/results/*.zip
169
+ conformance/results/*.pdf
164
170
 
165
171
  # Ralph orchestrator runtime state
166
172
  .ralph/
@@ -187,3 +193,6 @@ mutmut-stats.json
187
193
 
188
194
  # moon build cache — never commit (tracked cache poisons affected-detection)
189
195
  .moon/cache/
196
+
197
+ # Pinned checkout of the blind-peer-review plugin (see .github/workflows/claude.yml)
198
+ .review-plugin/
@@ -0,0 +1,286 @@
1
+ # Changelog
2
+
3
+ All notable changes to `fastapi-identity-model` are documented here. This project
4
+ adheres to [Semantic Versioning](https://semver.org/) and is released
5
+ independently of the core `py-identity-model` library. Releases from 0.2.0 on
6
+ are generated by python-semantic-release from `(fastapi)`-scoped commits and
7
+ inserted below the marker.
8
+
9
+ <!-- psr: next release -->
10
+
11
+ ## v0.4.0-a.1 (2026-11-26)
12
+
13
+ ### Bug Fixes
14
+
15
+ - **fastapi**: A ConfigurationException during validation is a server error
16
+ ([`f0b3dbb`](https://github.com/jamescrowley321/identity-model/commit/f0b3dbb400b01e1e5ab6134f7a452e36a6d000ce))
17
+
18
+ - **fastapi**: Accept expires_in sent as a string of digits
19
+ ([`03d3f53`](https://github.com/jamescrowley321/identity-model/commit/03d3f5365efebf463786af38315e38e1ec36230b))
20
+
21
+ - **fastapi**: Classify token-validation failures by exception type
22
+ ([`653a1d5`](https://github.com/jamescrowley321/identity-model/commit/653a1d547a7298b8a628c2d990995f31928860ba))
23
+
24
+ - **fastapi**: Drop default ports from expected_origin and validate the certificate header name
25
+ ([`854d75a`](https://github.com/jamescrowley321/identity-model/commit/854d75a3e413cf7a3db18b002b3528308c4ab7f5))
26
+
27
+ - **fastapi**: Expose the failure kind via opt-in diagnostics header
28
+ ([`f999ba9`](https://github.com/jamescrowley321/identity-model/commit/f999ba94ce4939d92f0e6bf6c8759a554fc133cf))
29
+
30
+ - **fastapi**: Fail the login closed on a signed UserInfo response
31
+ ([`a64f426`](https://github.com/jamescrowley321/identity-model/commit/a64f42658aae717945cf02c21ed33cbd32b37222))
32
+
33
+ - **fastapi**: Fail the login when UserInfo has no sub
34
+ ([`287adf2`](https://github.com/jamescrowley321/identity-model/commit/287adf2bdaff08789b4a73760673c0b9dbd36b9c))
35
+
36
+ - **fastapi**: Keep a rotated refresh token and map fetch outages to 502
37
+ ([`5197f90`](https://github.com/jamescrowley321/identity-model/commit/5197f90fa4fee555c88da3be229354fffba8e0b7))
38
+
39
+ - **fastapi**: Keep a rotated refresh token from a rejected refresh response
40
+ ([`a44d8ea`](https://github.com/jamescrowley321/identity-model/commit/a44d8eac28b635d815f846ec9dc13a9e1697273c))
41
+
42
+ - **fastapi**: Keep client_secret out of OIDCSettings repr
43
+ ([`c1baf06`](https://github.com/jamescrowley321/identity-model/commit/c1baf06179eee2fe057e97ee0a8099350b56c65f))
44
+
45
+ - **fastapi**: Keep the rotated refresh token on a missing access token
46
+ ([`455c6bb`](https://github.com/jamescrowley321/identity-model/commit/455c6bb2f7e14c9aea4f52036fd5864492f2e199))
47
+
48
+ - **fastapi**: Log a ConfigurationException rejection at warning level
49
+ ([`d2d31a4`](https://github.com/jamescrowley321/identity-model/commit/d2d31a450491845c36adeafec063ea9b4f75bc69))
50
+
51
+ - **fastapi**: Look up the default replay cache on every check
52
+ ([`62f2971`](https://github.com/jamescrowley321/identity-model/commit/62f29715a99c24b56fd66a89118bf1fb70012ecb))
53
+
54
+ - **fastapi**: One default DPoP replay cache per process
55
+ ([`91251e3`](https://github.com/jamescrowley321/identity-model/commit/91251e3638138d8fc8a9d4f1243f4a488a70dc16))
56
+
57
+ - **fastapi**: Only an unusable replay cache is a 500
58
+ ([`583f525`](https://github.com/jamescrowley321/identity-model/commit/583f52503c36bc4d7b0330cb06ccde05d15f99e8))
59
+
60
+ - **fastapi**: Pass the core refresh error through verbatim
61
+ ([`fa284f0`](https://github.com/jamescrowley321/identity-model/commit/fa284f07fbfff915c54eec227e98ffef8d85f42e))
62
+
63
+ - **fastapi**: Redact refresh failure diagnostics
64
+ ([`7a3302e`](https://github.com/jamescrowley321/identity-model/commit/7a3302ea83b1af6f197af0693a739159f745a494))
65
+
66
+ - **fastapi**: Refuse a negative expires_in and compute the expiry once
67
+ ([`d374fe1`](https://github.com/jamescrowley321/identity-model/commit/d374fe1846ec438f3ad5b1c4e941ddb1e07f3d28))
68
+
69
+ - **fastapi**: Refuse a refresh response whose expires_in is not a number of seconds
70
+ ([`08fb978`](https://github.com/jamescrowley321/identity-model/commit/08fb97863e6d75fb97db8fc91305e7b875804675))
71
+
72
+ - **fastapi**: Refuse an expires_in no expiry date can be computed from
73
+ ([`ea491eb`](https://github.com/jamescrowley321/identity-model/commit/ea491eb24f2860b3ac3a74c6f0f4440949f52034))
74
+
75
+ - **fastapi**: Refuse folded certificate headers and non-ASCII origin hosts
76
+ ([`26cbea8`](https://github.com/jamescrowley321/identity-model/commit/26cbea846d4661bac9415d8ca0fa713c5bca2ef3))
77
+
78
+ - **fastapi**: Rename OIDCSettings.audience to audience_override
79
+ ([`8e82c33`](https://github.com/jamescrowley321/identity-model/commit/8e82c330638353f73935df2188ff39b34f57a3ca))
80
+
81
+ - **fastapi**: Report an unexplained rejected refresh response as REFRESH_FAILED
82
+ ([`56bb974`](https://github.com/jamescrowley321/identity-model/commit/56bb974b8490a4140dd516d450c106b7da0a3cff))
83
+
84
+ - **fastapi**: Resolve the default audience on read
85
+ ([`7448002`](https://github.com/jamescrowley321/identity-model/commit/7448002181bcda624ccf600ce08cf6b8ae983616))
86
+
87
+ - **fastapi**: RFC 6750 challenges, RFC 9207 iss check, token_type checks
88
+ ([`1b8185a`](https://github.com/jamescrowley321/identity-model/commit/1b8185a6fb4b81341fbef25f1cd064dac47fcb44))
89
+
90
+ - **fastapi**: Share one replay cache per OIDCSettings
91
+ ([`c0eabc0`](https://github.com/jamescrowley321/identity-model/commit/c0eabc0129d954bd731f4f666cc1c91ff809c55e))
92
+
93
+ - **fastapi**: Treat an empty OIDC_AUDIENCE as unset
94
+ ([`34d0bee`](https://github.com/jamescrowley321/identity-model/commit/34d0bee41184ad00ff9e5a30487233f02ca98c7f))
95
+
96
+ - **fastapi**: Type-check validate_azp and recommend it with trusted_audiences
97
+ ([`3944495`](https://github.com/jamescrowley321/identity-model/commit/394449570b3b1d2d3a5716b81711c7e2bc660aa4))
98
+
99
+ - **fastapi**: Validate client_certificate_header against the RFC 9110 token grammar
100
+ ([`83004e6`](https://github.com/jamescrowley321/identity-model/commit/83004e6aff25b8a69407d0fd81073e5e41541df6))
101
+
102
+ ### Build System
103
+
104
+ - **fastapi**: Require py-identity-model 5
105
+ ([`754adf8`](https://github.com/jamescrowley321/identity-model/commit/754adf8d62a7e98c6b02cf77c1a682a4fb175baf))
106
+
107
+ ### Documentation
108
+
109
+ - **fastapi**: Document oidc_settings_from_env and http_client
110
+ ([`c71a34f`](https://github.com/jamescrowley321/identity-model/commit/c71a34fbae6a0734871072af015bb4940bd24dc1))
111
+
112
+ - **fastapi**: Link the upgrade notes to #1136
113
+ ([`c6ad90f`](https://github.com/jamescrowley321/identity-model/commit/c6ad90fa03f8e59142b1f69433da96fabaadb01d))
114
+
115
+ - **fastapi**: Read expected_audience in the README and example app
116
+ ([`0fde963`](https://github.com/jamescrowley321/identity-model/commit/0fde963a5a2bb306e7bc7dd456852c5bffa13e34))
117
+
118
+ - **fastapi**: The callback 502 covers fetch transport failures
119
+ ([`1fa60e7`](https://github.com/jamescrowley321/identity-model/commit/1fa60e724f2611be864d3f88da0fd8d37fe18b68))
120
+
121
+ - **fastapi**: The certificate header must carry the leaf certificate only
122
+ ([`c357a19`](https://github.com/jamescrowley321/identity-model/commit/c357a196d5cfd5c4b9aaa8ea3e65f21a645ce4c6))
123
+
124
+ ### Features
125
+
126
+ - **fastapi**: Accept the DPoP scheme and enforce sender-constrained tokens
127
+ ([`f486c02`](https://github.com/jamescrowley321/identity-model/commit/f486c02559df4ddf15071930c1bac476d74ec120))
128
+
129
+ - **fastapi**: Answer an ID Token nonce rejection with "Nonce mismatch"
130
+ ([`f36f4da`](https://github.com/jamescrowley321/identity-model/commit/f36f4daea884ee1abcb65ba3e8c56025ced8c6fc))
131
+
132
+ - **fastapi**: OIDCSettings takes the issuer
133
+ ([`de7aa3c`](https://github.com/jamescrowley321/identity-model/commit/de7aa3cd58c9c74289f8e9c17f0656f651a260d2))
134
+
135
+ - **fastapi**: Pass an app-supplied http_client through to the library
136
+ ([`1f0fc33`](https://github.com/jamescrowley321/identity-model/commit/1f0fc33c48dddba263fac220eb15ce8fc2c21fa3))
137
+
138
+ - **fastapi**: Take a validation cache on the middleware and WS authenticator
139
+ ([`fd403bb`](https://github.com/jamescrowley321/identity-model/commit/fd403bb30d4d8526d74bf32a8306e8c956690ee3))
140
+
141
+ - **fastapi**: Trusted_audiences and validate_azp for the login callback
142
+ ([`f17ed24`](https://github.com/jamescrowley321/identity-model/commit/f17ed24ac451d5668c86a429da239adbc70e9ebc))
143
+
144
+ - **fastapi**: Wire OIDCSettings.required_binding and share one AuthOptions
145
+ ([`a85c8a7`](https://github.com/jamescrowley321/identity-model/commit/a85c8a791e88d7f9a7017183514fa0b4d3525415))
146
+
147
+ ### Refactoring
148
+
149
+ - **fastapi**: Freeze OIDCSettings and make AuthOptions keyword-only
150
+ ([`f909052`](https://github.com/jamescrowley321/identity-model/commit/f9090525fe097361aaa6b70eed35793dc886826a))
151
+
152
+ - **fastapi**: Move OIDCSettings.from_env to an optional helper
153
+ ([`87c59c4`](https://github.com/jamescrowley321/identity-model/commit/87c59c4551a5e142b392161856bc12429279aa8c))
154
+
155
+ ### Testing
156
+
157
+ - **fastapi**: Cover an absent and a non-ASCII nonce at the login callback
158
+ ([`72b10e9`](https://github.com/jamescrowley321/identity-model/commit/72b10e9d8b6dacc486d668d77cad89b04c485bfa))
159
+
160
+ - **fastapi**: Cover OIDCSettings required_binding coercion directly
161
+ ([`c7b5019`](https://github.com/jamescrowley321/identity-model/commit/c7b501964c810e30d56106610f037ec8aa6b4f42))
162
+
163
+ - **fastapi**: Give the fake UserInfo response an error_kind
164
+ ([`865ec87`](https://github.com/jamescrowley321/identity-model/commit/865ec877de9da0466ae2363a8fa5c0bacd19f360))
165
+
166
+ - **fastapi**: Request the token endpoint fixture by name
167
+ ([`372f727`](https://github.com/jamescrowley321/identity-model/commit/372f727632510652fc9a9c91d660da031f1fdad6))
168
+
169
+ ### Breaking Changes
170
+
171
+ - **fastapi**: Fastapi-identity-model now requires py-identity-model>=5.0.0,<6.
172
+
173
+ - **fastapi**: OIDCSettings is frozen and both OIDCSettings and AuthOptions take keyword arguments
174
+ only. Build a changed copy with dataclasses.replace, which re-runs validation.
175
+
176
+ - **fastapi**: OIDCSettings.discovery_url, the DISCOVERY_URL env var and the discovery_url=
177
+ arguments are replaced by the issuer.
178
+
179
+
180
+ ## v0.3.0 (2026-09-05)
181
+
182
+ ### Features
183
+
184
+ - **fastapi**: Authenticate WebSockets, fix exclusion foot-guns and login self-block
185
+ ([#604](https://github.com/jamescrowley321/identity-model/pull/604),
186
+ [`6a88c56`](https://github.com/jamescrowley321/identity-model/commit/6a88c56f5798f2dbfda6a7c2c5f19535eea817ab))
187
+
188
+ ### Testing
189
+
190
+ - **fastapi**: Address fresh-context adversarial review findings
191
+ ([#604](https://github.com/jamescrowley321/identity-model/pull/604),
192
+ [`6a88c56`](https://github.com/jamescrowley321/identity-model/commit/6a88c56f5798f2dbfda6a7c2c5f19535eea817ab))
193
+
194
+ - **fastapi**: Integration + red-team coverage for WS auth, exclusion, RP composition
195
+ ([#604](https://github.com/jamescrowley321/identity-model/pull/604),
196
+ [`6a88c56`](https://github.com/jamescrowley321/identity-model/commit/6a88c56f5798f2dbfda6a7c2c5f19535eea817ab))
197
+
198
+ - **fastapi**: Wire test_ws_correctness into a gated target
199
+ ([#604](https://github.com/jamescrowley321/identity-model/pull/604),
200
+ [`6a88c56`](https://github.com/jamescrowley321/identity-model/commit/6a88c56f5798f2dbfda6a7c2c5f19535eea817ab))
201
+
202
+
203
+ ## v0.2.3 (2026-09-04)
204
+
205
+ ### Bug Fixes
206
+
207
+ - **fastapi**: Don't reflect provider/library error internals from the RP callback
208
+ ([#622](https://github.com/jamescrowley321/identity-model/pull/622),
209
+ [`2480587`](https://github.com/jamescrowley321/identity-model/commit/2480587a1ef28837ce9b36f928dcd8cef26e07cd))
210
+
211
+ ### Testing
212
+
213
+ - **fastapi**: Cover the two genericized error branches
214
+ ([#622](https://github.com/jamescrowley321/identity-model/pull/622),
215
+ [`2480587`](https://github.com/jamescrowley321/identity-model/commit/2480587a1ef28837ce9b36f928dcd8cef26e07cd))
216
+
217
+
218
+ ## v0.2.2 (2026-08-22)
219
+
220
+ ### Bug Fixes
221
+
222
+ - **fastapi**: Return 503 (not 401) when the OIDC provider is unreachable
223
+ ([`26f425d`](https://github.com/jamescrowley321/identity-model/commit/26f425d61ea5e21a365d9e71fbdac0292224d5b5))
224
+
225
+
226
+ ## v0.2.1 (2026-08-10)
227
+
228
+ ### Bug Fixes
229
+
230
+ - **fastapi**: Uniform 401 body across validation failures (F-18, CWE-209)
231
+ ([#508](https://github.com/jamescrowley321/identity-model/pull/508),
232
+ [`d4e8aed`](https://github.com/jamescrowley321/identity-model/commit/d4e8aedcd9e2622aab9139ae5f6b09e2e2c1eaf0))
233
+
234
+
235
+ ## v0.2.0 (2026-08-09)
236
+
237
+ ### Features
238
+
239
+ - **fastapi**: Opt-in access-token-marker enforcement (F-07)
240
+ ([`4e0eb10`](https://github.com/jamescrowley321/identity-model/commit/4e0eb10aea9c6451614b5b6cfaa4b2c410f3496b))
241
+
242
+
243
+ ## 0.1.0 (2026-07-08)
244
+
245
+ Initial release. Extracted and hardened from the `py-identity-model` FastAPI
246
+ example, then driven through the OIDF conformance suite: the RP router passes
247
+ the same local Basic RP, Config RP, and Form Post RP plans the core library is
248
+ certified against (13/13, 5/5, 13/13 — regression stage, see #437).
249
+
250
+ ### Added
251
+ - `TokenValidationMiddleware` — resource-server Bearer-token validation that
252
+ attaches a `ClaimsPrincipal` to `request.state`.
253
+ - `Depends` helpers: `get_current_user`, `get_claims`, `get_token`,
254
+ `get_claim_value`, `get_claim_values`, `require_claim`, `require_scope`.
255
+ - `build_oidc_router` — mountable relying-party login flow (authorization code +
256
+ PKCE) with state/nonce, ID-token validation, and UserInfo `sub` verification.
257
+ - `POST /callback` on the RP router — OAuth 2.0 `form_post` response mode,
258
+ sharing the exact GET validation path (parsed with stdlib `parse_qsl`; no
259
+ `python-multipart` dependency). Requires the session cookie to be issued
260
+ with `same_site="none"` in real browsers.
261
+ - `build_oidc_router(fetch_userinfo=False)` — skip the UserInfo round-trip and
262
+ anchor identity on the validated ID token.
263
+ - `OIDCSettings` — typed configuration with `from_env()`.
264
+ - `TokenManager` — access-token refresh lifecycle over the native async refresh grant.
265
+
266
+ ### Changed vs. the former example
267
+ - Middleware returns **503** for a discovery/JWKS/network fault and **500** for a
268
+ genuinely unexpected error, instead of masking either as a 401.
269
+ - `TokenManager` uses the async discovery + native `aio.refresh_token` grant
270
+ (removes a blocking sync call in async context and a hand-rolled token POST).
271
+
272
+ ### Security
273
+ - The RP router rejects a discovery document whose issuer does not match the
274
+ URL it was retrieved from (OIDC Discovery 1.0 §4.3 issuer mix-up defense).
275
+ - The RP router refuses to establish a session when the token response has no
276
+ ID token, and enforces the UserInfo `sub` match as a hard gate (a mismatch
277
+ fails the login instead of being swallowed).
278
+ - Transient login-flow state (state/nonce/PKCE verifier) is kept under a
279
+ separate session key from the identity and is single-use (popped on callback),
280
+ so an in-flight login is never read as an authenticated identity.
281
+ - `TokenValidationMiddleware` rejects an ID token presented as an access token,
282
+ requires a non-empty `audience` (a `None` audience skips `aud` enforcement for
283
+ aud-less tokens), lets CORS preflight through, and matches excluded subpaths.
284
+ - `POST /auth/logout` (was `GET`) so a cross-site request cannot force logout.
285
+ - `TokenManager` refreshes under an `asyncio.Lock` (no concurrent-refresh
286
+ token-family invalidation) and treats `expires_in=0` as already expired.
@@ -0,0 +1,241 @@
1
+ Metadata-Version: 2.5
2
+ Name: fastapi-identity-model
3
+ Version: 0.4.0-a.1
4
+ Summary: FastAPI OIDC/OAuth2 middleware and relying-party router, built on py-identity-model
5
+ Project-URL: Homepage, https://github.com/jamescrowley321/identity-model
6
+ Project-URL: Repository, https://github.com/jamescrowley321/identity-model
7
+ Project-URL: Issues, https://github.com/jamescrowley321/identity-model/issues
8
+ Author-email: jamescrowley321 <jamescrowley151@gmail.com>
9
+ License-Expression: Apache-2.0
10
+ Keywords: authentication,fastapi,jwt,middleware,oauth2,oidc,openid-connect
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Framework :: FastAPI
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: Apache Software License
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Topic :: Security
20
+ Classifier: Topic :: Software Development :: Libraries :: Application Frameworks
21
+ Classifier: Typing :: Typed
22
+ Requires-Python: >=3.12
23
+ Requires-Dist: fastapi>=0.115.0
24
+ Requires-Dist: itsdangerous>=2.0
25
+ Requires-Dist: py-identity-model<6,>=5.0.0a1
26
+ Requires-Dist: starlette>=0.49.1
27
+ Provides-Extra: server
28
+ Requires-Dist: uvicorn[standard]>=0.23.0; extra == 'server'
29
+ Description-Content-Type: text/markdown
30
+
31
+ # fastapi-identity-model
32
+
33
+ OIDC/OAuth2 integration for [FastAPI](https://fastapi.tiangolo.com/), built on
34
+ [`py-identity-model`](https://pypi.org/project/py-identity-model/) — an OpenID
35
+ Foundation–certified relying-party library.
36
+
37
+ It gives you two composable pieces:
38
+
39
+ | Piece | Use case |
40
+ |-------|----------|
41
+ | **`TokenValidationMiddleware`** + `Depends` helpers | Protect an **API / resource server** that receives `Authorization: Bearer <token>` or `Authorization: DPoP <token>` |
42
+ | **`build_oidc_router`** | Add a browser **login flow** (authorization code + PKCE) to your app (relying party) |
43
+
44
+ ## Install
45
+
46
+ ```bash
47
+ pip install fastapi-identity-model
48
+ # with a server for the demo:
49
+ pip install "fastapi-identity-model[server]"
50
+ ```
51
+
52
+ ## Resource server — validate incoming access tokens
53
+
54
+ ```python
55
+ from fastapi import FastAPI, Depends
56
+ from fastapi_identity_model import (
57
+ TokenValidationMiddleware, OIDCSettings, get_current_user, require_scope,
58
+ )
59
+
60
+ settings = OIDCSettings(
61
+ issuer="https://op.example.com",
62
+ client_id="<client_id>",
63
+ )
64
+ app = FastAPI()
65
+ app.add_middleware(
66
+ TokenValidationMiddleware,
67
+ issuer=settings.issuer,
68
+ audience=settings.expected_audience,
69
+ excluded_paths=settings.excluded_paths,
70
+ )
71
+
72
+ @app.get("/api/me")
73
+ async def me(user = Depends(get_current_user)):
74
+ return {"sub": user.identity.name, "authenticated": user.identity.is_authenticated}
75
+
76
+ @app.get("/api/data", dependencies=[Depends(require_scope("api.read"))])
77
+ async def data():
78
+ return {"data": "protected"}
79
+ ```
80
+
81
+ `issuer` is the provider's issuer identifier, not its discovery URL. The
82
+ discovery document is fetched from `<issuer>/.well-known/openid-configuration`,
83
+ and its `issuer` and each token's `iss` must equal the configured value
84
+ exactly (`https://op.example.com` and `https://op.example.com/` are different
85
+ issuers). A value ending with `/.well-known/...` is a configuration error.
86
+
87
+ The middleware validates the token (signature, issuer, audience, expiry) via
88
+ `py-identity-model` and attaches a `ClaimsPrincipal` to `request.state.user`.
89
+ Invalid tokens → **401**; an unexpected server-side failure → **500** (never
90
+ masked as a 401).
91
+
92
+ Sender-constrained tokens are always checked: a DPoP-bound token (`cnf.jkt`)
93
+ needs the `DPoP` scheme and a valid proof, and a certificate-bound token needs
94
+ its client certificate. Binding options live on one `AuthOptions`, passed as
95
+ `options=` to both `TokenValidationMiddleware` and `build_ws_authenticator`;
96
+ pass `settings=` instead to read `OIDC_REQUIRED_BINDING` and friends from
97
+ `OIDCSettings`. `AuthOptions(required_binding=TokenBinding.DPOP)` also refuses
98
+ unbound tokens. See
99
+ [DPoP resource server verification](https://jamescrowley321.github.io/identity-model/api/dpop/#fastapi).
100
+
101
+ ## Relying party — browser login flow
102
+
103
+ ```python
104
+ import os
105
+
106
+ from fastapi import FastAPI, Request
107
+ from starlette.middleware.sessions import SessionMiddleware
108
+ from fastapi_identity_model import OIDCSettings, build_oidc_router
109
+
110
+ settings = OIDCSettings(
111
+ issuer="https://api.descope.com/v1/apps/<project_id>",
112
+ client_id="<client_id>",
113
+ redirect_uri="http://localhost:8000/auth/callback",
114
+ scope="openid profile email",
115
+ )
116
+
117
+ app = FastAPI()
118
+ # Use a strong secret from the environment — never a committed literal, or
119
+ # anyone can forge a session cookie. same_site="lax" is required so the
120
+ # provider's redirect back to /auth/callback carries the session cookie.
121
+ app.add_middleware(
122
+ SessionMiddleware,
123
+ secret_key=os.environ["SESSION_SECRET"],
124
+ same_site="lax",
125
+ https_only=True, # behind TLS
126
+ )
127
+ app.include_router(build_oidc_router(settings), prefix="/auth")
128
+
129
+ @app.get("/me")
130
+ async def me(request: Request):
131
+ return request.session.get("oidc", {}) # {"sub", "claims", "userinfo"} after login
132
+ ```
133
+
134
+ Routes added: `GET /auth/login` → provider, `GET /auth/callback` (code exchange,
135
+ ID-token validation, **nonce check**, UserInfo `sub` verification), `POST /auth/logout`.
136
+
137
+ The callback validates the ID Token with `validate_id_token` (OIDC Core
138
+ §3.1.3.7). An ID Token whose `aud` lists anything besides `client_id` fails
139
+ the login unless that audience is in `trusted_audiences`
140
+ (`OIDC_TRUSTED_AUDIENCES`). If your provider issues multi-audience ID Tokens,
141
+ list the extra audiences. Whenever you set `OIDC_TRUSTED_AUDIENCES`, also set
142
+ `OIDC_VALIDATE_AZP=true` (`validate_azp=True`), so the token must name your
143
+ client as its authorized party (`azp`). Without it, an ID Token issued to
144
+ another client that also lists yours in `aud` logs in. The `azp` check is off
145
+ by default because OIDC Core §3.1.3.7 makes it a SHOULD:
146
+
147
+ ```python
148
+ settings = OIDCSettings(
149
+ ...,
150
+ trusted_audiences=["https://api.example.com"],
151
+ validate_azp=True,
152
+ )
153
+ ```
154
+
155
+ ### Session & security
156
+
157
+ The router uses Starlette's `SessionMiddleware`, which **signs but does not
158
+ encrypt** the cookie. Stored identity claims are tamper-proof but readable by the
159
+ client. Raw tokens are stored **only** when you pass `build_oidc_router(settings,
160
+ store_tokens=True)` — enable that only with an encrypted or server-side session
161
+ store. For production, back the session with a server-side store.
162
+
163
+ ## Configuration
164
+
165
+ The package reads no environment variables. Construct `OIDCSettings` yourself,
166
+ or build it from the environment with the optional helper:
167
+
168
+ ```python
169
+ from fastapi_identity_model.config_helpers import oidc_settings_from_env
170
+
171
+ settings = oidc_settings_from_env() # OIDC_ISSUER, OIDC_CLIENT_ID, OIDC_REDIRECT_URI, ...
172
+ settings = oidc_settings_from_env("APP_") # APP_ISSUER, APP_CLIENT_ID, ...
173
+ ```
174
+
175
+ `ISSUER` and `CLIENT_ID` are required. `EXCLUDED_PATHS` and
176
+ `TRUSTED_AUDIENCES` are comma-separated lists; an empty `TRUSTED_AUDIENCES`
177
+ entry raises `ValueError`. `VALIDATE_AZP` is `true` or `false`. Every other variable (`REDIRECT_URI`, `CLIENT_SECRET`,
178
+ `SCOPE`, `AUDIENCE`, `POST_LOGIN_REDIRECT`, `POST_LOGOUT_REDIRECT`) falls back
179
+ to the `OIDCSettings` default when unset. `AUDIENCE` sets `audience_override`;
180
+ read the audience to check from `settings.expected_audience`.
181
+
182
+ HTTP settings belong to a `py-identity-model` `HTTPConfig`, and cache settings
183
+ to a `CacheConfig`. Build an `AsyncHTTPClient` from the first (timeouts,
184
+ retries, CA bundle) and pass it as
185
+ `http_client=` to `TokenValidationMiddleware`, `build_oidc_router`,
186
+ `build_ws_authenticator` and `TokenManager`. Without it, the library default
187
+ client is used.
188
+
189
+ The discovery document, the keys and the kid-miss cooldown are kept on an
190
+ `AsyncValidationCache`, not on the client. Pass one as `cache=` to
191
+ `TokenValidationMiddleware` and `build_ws_authenticator` to set the cache
192
+ TTLs, size or cooldown. Without it, and in `build_oidc_router`, the library
193
+ default cache is used.
194
+
195
+ ```python
196
+ from py_identity_model import CacheConfig, HTTPConfig
197
+ from py_identity_model.aio import AsyncHTTPClient, AsyncValidationCache
198
+
199
+ http_client = AsyncHTTPClient(config=HTTPConfig(http_timeout=10.0))
200
+ cache = AsyncValidationCache(config=CacheConfig(jwks_cache_ttl=900.0))
201
+ app.add_middleware(
202
+ TokenValidationMiddleware,
203
+ issuer=settings.issuer,
204
+ audience=settings.expected_audience,
205
+ http_client=http_client,
206
+ cache=cache,
207
+ )
208
+ app.include_router(build_oidc_router(settings, http_client=http_client), prefix="/auth")
209
+ ```
210
+
211
+ Close the client on shutdown (`await http_client.close()`, e.g. in the app's
212
+ lifespan). A cache holds no connections and needs no closing.
213
+
214
+ ## Token refresh
215
+
216
+ ```python
217
+ from fastapi_identity_model import TokenManager
218
+
219
+ tm = TokenManager(issuer=..., client_id=..., client_secret=...)
220
+ tm.set_tokens(
221
+ access_token=..., refresh_token=..., expires_in=3600, token_type="Bearer"
222
+ )
223
+ access = await tm.get_access_token() # auto-refreshes shortly before expiry
224
+ headers = {"Authorization": f"{tm.token_type.value} {access}"}
225
+ ```
226
+
227
+ `token_type` is the token response's `token_type`, matched case-insensitively.
228
+ Anything but `Bearer` or `DPoP` raises `TokenManagerError` with
229
+ `kind=TokenManagerErrorKind.UNSUPPORTED_TOKEN_TYPE`. Every failure is a
230
+ `TokenManagerError` whose `kind` says why: `NO_REFRESH_TOKEN`,
231
+ `DISCOVERY_FAILED`, `REFRESH_FAILED`, `MISSING_ACCESS_TOKEN` or
232
+ `UNSUPPORTED_TOKEN_TYPE`. For an unsuccessful refresh, `details["error"]`
233
+ carries the core library's message verbatim: the status code for an HTTP
234
+ failure, a fixed label for network and unexpected errors. The core never
235
+ embeds response bodies in these messages — a body may contain secrets even in
236
+ `error` or `error_description` — so this layer passes them through without
237
+ rewriting.
238
+
239
+ ## License
240
+
241
+ Apache-2.0 — see the repository `LICENSE`.