auth fixes
This commit is contained in:
+24
-19
@@ -1,31 +1,17 @@
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
import jwt
|
||||
|
||||
from app.config import settings
|
||||
|
||||
_jwks_cache: dict[str, Any] | None = None
|
||||
|
||||
def decode_token(token: str) -> dict[str, Any]:
|
||||
"""Decode a JWT token.
|
||||
|
||||
When authentik_issuer_url is configured, validates the token
|
||||
against the OIDC discovery document JWKS.
|
||||
Otherwise, decodes without verification (local development only).
|
||||
"""
|
||||
async def decode_token(token: str) -> dict[str, Any]:
|
||||
if settings.authentik_issuer_url:
|
||||
import httpx
|
||||
|
||||
issuer = settings.authentik_issuer_url.rstrip("/")
|
||||
discovery_url = f"{issuer}/.well-known/openid-configuration"
|
||||
with httpx.Client() as client:
|
||||
resp = client.get(discovery_url)
|
||||
resp.raise_for_status()
|
||||
discovery = resp.json()
|
||||
jwks_uri = discovery["jwks_uri"]
|
||||
|
||||
jwks_resp = client.get(jwks_uri)
|
||||
jwks_resp.raise_for_status()
|
||||
jwks = jwks_resp.json()
|
||||
jwks = await _get_jwks(issuer)
|
||||
|
||||
signing_key = jwt.algorithms.RSAAlgorithm.from_jwk(
|
||||
_find_matching_key(jwks, token)
|
||||
@@ -42,8 +28,27 @@ def decode_token(token: str) -> dict[str, Any]:
|
||||
return jwt.decode(token, options={"verify_signature": False})
|
||||
|
||||
|
||||
async def _get_jwks(issuer: str) -> dict[str, Any]:
|
||||
global _jwks_cache
|
||||
|
||||
if _jwks_cache is not None:
|
||||
return _jwks_cache
|
||||
|
||||
discovery_url = f"{issuer}/.well-known/openid-configuration"
|
||||
async with httpx.AsyncClient() as client:
|
||||
resp = await client.get(discovery_url)
|
||||
resp.raise_for_status()
|
||||
discovery = resp.json()
|
||||
jwks_uri = discovery["jwks_uri"]
|
||||
|
||||
jwks_resp = await client.get(jwks_uri)
|
||||
jwks_resp.raise_for_status()
|
||||
_jwks_cache = jwks_resp.json()
|
||||
|
||||
return _jwks_cache
|
||||
|
||||
|
||||
def _find_matching_key(jwks: dict[str, Any], token: str) -> dict[str, Any]:
|
||||
"""Find the key in JWKS that matches the token's kid header."""
|
||||
unverified_header = jwt.get_unverified_header(token)
|
||||
kid = unverified_header.get("kid")
|
||||
for key in jwks.get("keys", []):
|
||||
|
||||
Reference in New Issue
Block a user