Skip to content
Open
Show file tree
Hide file tree
Changes from 13 commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
0f6bc09
fix(auth): prevent deadlock when refreshing an expired access token
Koosha-Owji Nov 13, 2026
dd92adb
feat(auth): add acr_values and max_age login options
Koosha-Owji Nov 13, 2026
0f88e75
feat(auth): replace the session's tokens on an authorization callback
Koosha-Owji Nov 13, 2026
317b17a
feat(auth): add step_up() and authentication context checks
Koosha-Owji Nov 13, 2026
8f55535
feat(flask,fastapi): hand step-up callback errors to the app
Koosha-Owji Nov 13, 2026
f80aec8
fix(auth): use the same session key in every worker process
Koosha-Owji Nov 13, 2026
a88346d
fix(auth): keep cached tokens in step with the stored session
Koosha-Owji Nov 13, 2026
87786d2
docs: document step-up authentication
Koosha-Owji Nov 13, 2026
5bd46b9
fix(auth): keep the refresh token across step-up and tighten context …
Koosha-Owji Nov 18, 2026
34f8334
fix(auth): validate the ID token on callback and keep the refresh tok…
Koosha-Owji Nov 18, 2026
0e2c782
Merge branch 'main' into feat/step-up-auth
Koosha-Owji Dec 1, 2026
f25ca1a
fix(auth): fix FastAPI callback order and address review comments
Koosha-Owji Dec 1, 2026
6175b86
fix(auth): address review comments on token storage and callbacks
Koosha-Owji Dec 2, 2026
f043f65
fix(auth): keep logout from being undone by a save in progress
Koosha-Owji Dec 2, 2026
f0701dc
fix(auth): don't hold the session lock while waiting for a user's tok…
Koosha-Owji Dec 2, 2026
5e2fbec
fix(auth): clear the unsaved flag on adopted tokens and keep cleanup …
Koosha-Owji Dec 2, 2026
b3d2bbb
fix(auth): keep expiry cleanup from deleting a later sign-in stored b…
Koosha-Owji Dec 2, 2026
e9ae003
revert(auth): drop the storage comparison from expiry cleanup
Koosha-Owji Dec 3, 2026
e005a0f
fix(auth): don't write one device session's tokens into another's sto…
Koosha-Owji Dec 3, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

### Added
- **Step-up authentication (RFC 9470)**: `LoginOptions.ACR_VALUES` and `LoginOptions.MAX_AGE` on
`login()` and `register()`; `step_up()`, `get_authentication_context()`,
`has_authentication_context()` and `is_step_up_supported()` on `OAuth`, `AsyncOAuth` and
`SmartOAuth`; `UnmetAuthenticationRequirementsError` and `LoginRequiredError`, raised by
`handle_redirect()` and by the Flask and FastAPI `/callback` routes after `state` is validated.
Opt-in: existing login URLs are unchanged. See "Step-up authentication" in the README.

### Security
- **Secrets in session storage**: `client_secret` is no longer written to session storage
(which may be a browser cookie); it is kept in process memory. Legacy sessions that still
Expand Down Expand Up @@ -37,6 +45,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Changed
- Callbacks without a `state` parameter, and token responses without an ID token (e.g. custom
scopes that omit `openid`), are now rejected.
- **Auth**: The tokens from an authorization callback now replace the session's access, ID and
refresh tokens. Previously a refresh token from an earlier sign-in was kept when the new
response had none.
- **Auth**: `acr_values` and `max_age` inside `auth_params` are no longer sent when unset
(`None` or empty). An invalid `max_age`, or an `acr_values` that is not a string or a list
of strings, raises `ValueError`.
- **Auth**: Top-level `acr_values` and `max_age` keys in the login options were silently
ignored and are now sent, after validation. `max_age` must be an `int`, so for example
`login({"max_age": "300"})` now raises `ValueError`.

### Fixed
- **Token refresh deadlock**: `TokenManager.get_access_token()` hung forever when the access
Expand Down Expand Up @@ -65,6 +82,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- **Refreshed tokens persisted**: tokens from a refresh were only kept in process memory, so with
server-side or cookie sessions, a restart or another worker kept using (and refreshing with) the
old ones. `UserSession` now writes them back to session storage after every refresh.
- **Session tokens across workers**: tokens are now saved in the session with a revision, and
each worker process follows the newest one. A worker that had cached a session picks up tokens
stored by another worker (a step-up, a refresh or a later sign-in), and an older copy of the
session written back by an overlapping request is ignored and repaired.
Comment thread
Koosha-Owji marked this conversation as resolved.
Resolved
- **Flask**: The `/callback` route keeps the post-login redirect location when it rejects a
callback, instead of dropping it before the callback is validated.
- **StorageManager.reset() deadlock**: `reset()` held the class lock while calling `initialize()`,
which takes the same non-reentrant lock; the lock is now reentrant.
- **KindeSessionManagement**: the standalone-only guard never fired, because constructing the
Expand Down
105 changes: 105 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -546,6 +546,111 @@ if __name__ == "__main__":
main()
```

## Step-up authentication

Ask Kinde for a stronger or more recent authentication before a sensitive action, for example "MFA in the last 5 minutes before changing payout details". Kinde collects only what is missing (the second factor, or a passkey), and the user keeps their session. This is [RFC 9470](https://www.rfc-editor.org/rfc/rfc9470) on the normal Kinde login flow. There is nothing to register in Kinde, and nothing changes for existing logins.

| What | How |
|---|---|
| Ask for a context at login | `LoginOptions.ACR_VALUES` (`"mfa"` or `"phr"`) and `LoginOptions.MAX_AGE` (seconds) on `login()` and `register()` |
| Start a step-up | `await oauth.step_up(acr="mfa", max_age=300)` returns the URL to redirect to |
| Read how the user signed in | `oauth.get_authentication_context()` returns `{"acr": ..., "amr": [...], "auth_time": ...}` |
| Check a requirement | `oauth.has_authentication_context(acr="mfa", max_age=300)` |
| Check the environment | `oauth.is_step_up_supported()` |
| Callback errors | `UnmetAuthenticationRequirementsError`, `LoginRequiredError` |

`mfa` means a second factor. `phr` means phishing-resistant (a passkey with user verification) and also meets an `mfa` requirement. Kinde leaves `acr` out for a single-factor sign-in, so `acr` is `None` then.

### Require MFA in the last 5 minutes

#### FastAPI

```python
from fastapi.responses import PlainTextResponse, RedirectResponse
from kinde_sdk.core.exceptions import UnmetAuthenticationRequirementsError

@app.get("/payouts")
async def payouts():
if not kinde_oauth.is_authenticated():
return RedirectResponse("/login")
if not kinde_oauth.has_authentication_context(acr="mfa", max_age=300):
# The built-in /callback route brings the user back to this page
return RedirectResponse(await kinde_oauth.step_up(acr="mfa", max_age=300))
return {"message": "Payout details"}

@app.exception_handler(UnmetAuthenticationRequirementsError)
async def step_up_not_possible(request, error):
# The user can't meet the requirement. This is final: don't send them back to Kinde.
return PlainTextResponse("Add an authenticator app to your account to continue.", status_code=403)
```

#### Flask

```python
import asyncio
from flask import redirect
from kinde_sdk.core.exceptions import UnmetAuthenticationRequirementsError

@app.route("/payouts")
def payouts():
if not kinde_oauth.is_authenticated():
return redirect("/login")
if not kinde_oauth.has_authentication_context(acr="mfa", max_age=300):
# The built-in /callback route brings the user back to this page
return redirect(asyncio.run(kinde_oauth.step_up(acr="mfa", max_age=300)))
return {"message": "Payout details"}

@app.errorhandler(UnmetAuthenticationRequirementsError)
def step_up_not_possible(error):
# The user can't meet the requirement. This is final: don't send them back to Kinde.
return "Add an authenticator app to your account to continue.", 403
```

`step_up()` is a coroutine, like `login()`. In an `async def` Flask view (which needs `flask[async]`), `await` it instead of using `asyncio.run()`.

### When the user can't step up

If the user has no enrolled MFA factor or no passkey, Kinde returns `error=unmet_authentication_requirements` to your callback instead of tokens. The SDK validates `state` and raises `UnmetAuthenticationRequirementsError`. The built-in `/callback` routes let it reach your app, so handle it with `@app.exception_handler(...)` (FastAPI) or `@app.errorhandler(...)` (Flask), as above. Without a handler of your own, the user sees a plain-text 403 page.

- It is a final answer. Retrying gives the same error, and sending the user to login would sign them in without the step-up. Tell them why instead, for example "add a passkey to continue".
- The error has `error_description`, `state`, and the `acr_values` and `max_age` that were asked for, so you can say what is missing.
- A user who was signed in stays signed in, with the tokens they already had.
- `LoginRequiredError` is the same kind of error for `login_required`, which Kinde returns when a `prompt=none` request needs a screen. Both extend `KindeCallbackError`.

If you handle the callback yourself, pass the error through and catch it:

```python
try:
await oauth.handle_redirect(code, user_id, state, error=error, error_description=error_description)
except UnmetAuthenticationRequirementsError as e:
show_error(e.error_description)
```

### Good to know

- **After a step-up, the callback replaces the access, ID and refresh tokens.** Refreshing never upgrades a session: a refreshed token keeps the `acr`, `amr` and `auth_time` it had. When `has_authentication_context()` is false, the only way forward is `step_up()`.
- **`step_up()` is interactive.** It raises `ValueError` for `prompt=none` (also inside `auth_params`), for an invalid `acr` or `max_age`, and when neither is given. `max_age` must be a non-negative `int`. `0` is valid and forces a fresh verification.
- **Don't check `max_age=0`.** `has_authentication_context(max_age=0)` is only true in the same second as the sign-in, so the user would be sent back to Kinde every time. Use a short window such as 60 seconds.
- **Call `step_up()` when you redirect, not to render a link.** Each call stores a new `state`, replacing any login in progress.
- **Scope and refresh tokens.** Like `login()`, `step_up()` asks for `openid profile email` unless `login_options` sets a scope, so pass the scope your login uses. The callback replaces every stored token and Kinde only returns a refresh token for the `offline` scope, so `step_up()` adds `offline` itself when the session has a refresh token. Otherwise the user would be signed out when the access token expires.
- **Where the user lands.** With FastAPI and Flask, the user comes back to the page that called `step_up()` when that request was a GET. For any other method nothing is remembered, so the user lands on `/`: pass `post_login_redirect_url="/somewhere"` to choose the page, which you should do for a form POST (the POST is not replayed). Without a framework integration, your own callback decides.
- **Environments without step-up.** If the discovery document has no `acr_values_supported`, Kinde ignores `acr_values` and `max_age`. `step_up()` then raises `KindeConfigurationException` and sends nothing, instead of pretending it worked. `get_authentication_context()` reports `auth_time` as `None` there, because the claim may be the token's issue time, so `has_authentication_context(max_age=...)` is always false. Check `is_step_up_supported()` first and deny the action, or force a fresh sign-in with `login({"prompt": "login"})`, which only proves the user signed in again.
- **If discovery can't be fetched.** While the discovery document is unavailable, `is_step_up_supported()` returns `False` and `step_up()` raises `KindeRetrieveException`. That one is temporary: `step_up()` retries the fetch, at most once every 5 seconds. The retry never blocks an event loop: `step_up()` awaits it on a worker thread, and a check made from async code starts it in the background without waiting. Until it has finished, `is_step_up_supported()` answers `False` and `auth_time` is not trusted, so `has_authentication_context(max_age=...)` is false. A check on `acr` alone is not affected.
- **More than one worker process.** Tokens are saved in the session with a revision, and every worker follows the newest one: a step-up handled by one worker is picked up by the others, and refreshed tokens are saved. This needs a session store that every worker shares (for Flask, the same `SECRET_KEY` and session backend).
- **Overlapping requests.** Session backends save a request's whole session when it ends, so a request that began before a step-up can write the old tokens back. A worker that has the newer tokens ignores that and repairs the session on its next request. The same goes for a token refresh that was started before a step-up, or before a later sign-in, and finished after it: its tokens rank below the newer authorization, so a worker that has the newer one keeps it and repairs the session in the same way. A worker that has never seen the session (another process, or after a restart) trusts what it reads, so in that window it can still see the old tokens and ask for the step-up again.
- **`auth_time` comes from the ID token.** `amr` is informational. `has_authentication_context()` decides on `acr` and `auth_time` only. An `auth_time` more than a minute in the future is invalid and meets no `max_age`. The ID token is only trusted when its `sub` matches the access token's.
- **The callback checks the ID token.** Before the tokens are stored, the ID token's audience, issuer, expiry and nonce are checked against this client and this login. A token that fails raises `KindeLoginException` and nothing is stored.
- **What `mfa` asserts.** `acr: "mfa"` means two factors were accepted under your MFA policy. It does not assert that they are independent: a social sign-in followed by a one-time code to the same mailbox proves one channel twice. `phr` is the stronger value, because a phishing site can't use a passkey. For payments and regulated workloads, assess factor independence, enrolment and recovery against your own configuration rather than relying on `acr` alone.
- **APIs.** `kinde_sdk.has_authentication_context(claims, acr="mfa", max_age=300)` is the same check as a pure function, for the claims of an access token you have verified yourself. A `require_authentication_context` dependency/decorator that answers with the RFC 9470 `401` challenge is planned as a follow-up.

### Differences from the cross-SDK recommendations

- **No `returnTo` in `state` for standalone use.** Returning the user is done through the FastAPI and Flask post-login redirect. Without a framework integration the SDK doesn't own the callback, so your callback chooses the destination.
- **Only a GET returns the user automatically.** `step_up()` from a POST (or any other method) doesn't send the user back to the page that made it. Pass `post_login_redirect_url=` for those.
- **No `prompt=login` fallback.** On an environment without step-up, `step_up(max_age=...)` raises like `step_up(acr=...)` does, and the app decides what to do. A fallback sign-in could never satisfy `has_authentication_context(max_age=...)` there, so a guarded page would redirect in a loop.
- **`auth_params` is a raw passthrough.** `LoginOptions.ACR_VALUES` accepts only `mfa` and `phr`, and `LoginOptions.MAX_AGE` only an `int`. Inside `auth_params`, `acr_values` is sent as given and `max_age` may also be a string of digits, as before. In both places an unset value is never sent and an invalid `max_age` raises `ValueError`.
- **No clock tolerance by default.** `oauth.has_authentication_context()` compares `auth_time` with the server clock exactly. The pure function takes `leeway=` if you need one.

## Advanced Usage: Direct Storage Management

This section covers direct interaction with the `StorageManager` for custom storage solutions.
Expand Down
89 changes: 88 additions & 1 deletion kinde_fastapi/framework/fastapi_framework.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
from typing import Optional
from fastapi import FastAPI, Request
from fastapi.responses import RedirectResponse, HTMLResponse
from fastapi.responses import RedirectResponse, HTMLResponse, PlainTextResponse
from kinde_sdk.core.framework.framework_interface import FrameworkInterface
from kinde_sdk.core.exceptions import (
CALLBACK_ERRORS,
KindeCallbackError,
UnmetAuthenticationRequirementsError,
)
from kinde_sdk.auth.oauth import OAuth
from kinde_sdk.core.exceptions import KindeLoginException, KindeTokenException
from ..middleware.framework_middleware import FrameworkMiddleware
Expand Down Expand Up @@ -63,6 +68,9 @@ def start(self) -> None:

# Register Kinde routes
self._register_kinde_routes()

# Default page for errors the callback hands to the app
self._register_error_handlers()

self._initialized = True

Expand Down Expand Up @@ -114,6 +122,55 @@ def set_oauth(self, oauth: OAuth) -> None:
"""
self._oauth = oauth

def set_post_login_redirect_url(self, url: Optional[str] = None) -> None:
"""
Remember where the callback route sends the user after the next
sign-in or step-up.

Args:
url: The URL to return to. If None, the current page is used when
the current request is a GET. For any other method nothing is
remembered (a POST is never replayed), and a location left by
an earlier, abandoned request is cleared.
"""
request = self.get_request()
if request is None:
return
if url is None:
if request.method != "GET":
request.session.pop('post_login_redirect_url', None)
return
url = str(request.url)
request.session['post_login_redirect_url'] = {'url': url}

def _register_error_handlers(self) -> None:
"""
Register the default page for callback errors.

The callback route raises UnmetAuthenticationRequirementsError and
LoginRequiredError. Handle them with ``@app.exception_handler(...)``.
This default only applies when the application has no handler of its own.
"""
if KindeCallbackError not in self.app.exception_handlers:
self.app.add_exception_handler(KindeCallbackError, self._default_callback_error_page)

@staticmethod
async def _default_callback_error_page(request: Request, error: KindeCallbackError):
"""Explain a callback error in plain words. The user stays signed in."""
if isinstance(error, UnmetAuthenticationRequirementsError):
message = (
"We couldn't complete the extra verification needed for this action. "
"Your account may not have a second sign-in method (such as an "
"authenticator app) or a passkey set up yet."
)
status_code = 403
else:
message = "You need to sign in again to continue."
status_code = 401
if error.error_description:
message = f"{message}\n\nDetails: {error.error_description}"
return PlainTextResponse(message, status_code=status_code)

def _register_kinde_routes(self) -> None:
"""
Register all Kinde-specific routes with the FastAPI application.
Expand Down Expand Up @@ -185,6 +242,36 @@ async def callback(request: Request, code: Optional[str] = None, state: Optional
self._logger.warning("Invalid reauth state: %s", type(ex).__name__)
return HTMLResponse("Error parsing reauth state", status_code=400)

# A step-up the user cannot meet (or login_required after prompt=none)
# is a final answer. Hand it to the app: the core validates the state
# and raises the error. Never redirect to login or retry from here.
if error in CALLBACK_ERRORS:
assert self._oauth is not None
try:
await self._oauth.handle_redirect(
code,
request.session.get('user_id'),
state,
error=error,
error_description=request.query_params.get('error_description'),
)
except KindeCallbackError:
# The state was valid, so this answers the pending request
# and its return location is finished with. A callback
# with a wrong state leaves it for the genuine one.
request.session.pop('post_login_redirect_url', None)
raise
except KindeLoginException:
self._logger.warning("OAuth error callback rejected")
return PlainTextResponse(
"Authentication failed: invalid or expired login request", status_code=400
)
except Exception as e:
# Logged by type only, and never returned to the browser
self._logger.error("OAuth error callback failed: %s", type(e).__name__)
return PlainTextResponse("Authentication failed", status_code=400)
return PlainTextResponse("Authentication failed", status_code=400)

# Reject before handle_redirect, which would consume the pending state
if not code:
return HTMLResponse("Authentication failed: Missing authorization code", status_code=400)
Expand Down
Loading