Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
3 changes: 2 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@ concurrency:
jobs:

unittest:
runs-on: ubuntu-latest
# Pinned: ubuntu-latest is now 26.04, which has no Python 3.9 build
runs-on: ubuntu-24.04

strategy:
matrix:
Expand Down
36 changes: 36 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,43 @@ 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.

### Changed
- **Auth**: The tokens from an authorization callback now replace the session's access, ID and
refresh tokens. Previously a refresh or ID token from an earlier sign-in was kept when the new
response had none.
- **Auth**: The authorization callback now checks the ID token before storing the tokens: its
audience must include the client ID, its issuer must be the configured Kinde host, it must
not be expired, and its nonce must be the one sent with the login. Otherwise
`handle_redirect()` raises `KindeLoginException`. The nonce is consumed by the callback, so
a login can't be completed twice.
- **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
- **Auth**: `TokenManager.get_access_token()` no longer deadlocks when it refreshes an expired
access token.
- **Auth**: Flask and FastAPI sessions use the same storage key in every worker process. Each
process generated its own, so a session stored by one worker could not be read by another,
and no session survived a restart.
- **Auth**: 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, or a later sign-in), refreshed tokens are saved back to the
session, and an older copy of the session written back by an overlapping request is
ignored and repaired.
- **Flask**: The `/callback` route keeps the post-login redirect location when it rejects a
callback, instead of dropping it before the callback is validated.
- **CI**: Hardened `renovate.json` so Renovate can no longer re-propose bumping the Python
`<3.12` `django` pin in `requirements.txt` to Django 6.x (Django 6.0+ requires Python
3.12+). Django is a test-only dependency for this SDK (no runtime usage), and the
Expand Down
105 changes: 105 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -514,6 +514,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
82 changes: 81 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 ..middleware.framework_middleware import FrameworkMiddleware
import os
Expand Down Expand Up @@ -62,6 +67,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 @@ -113,6 +121,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 @@ -184,6 +241,29 @@ async def callback(request: Request, code: Optional[str] = None, state: Optional
except Exception as ex:
return HTMLResponse(f"Error parsing reauth state: {str(ex)}", 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 Exception as e:
return PlainTextResponse(f"Authentication failed: {str(e)}", status_code=400)
return PlainTextResponse("Authentication failed", status_code=400)

user_id = request.session.get('user_id') or str(uuid.uuid4())

try:
Expand Down
Loading