fix: enhance JWT validation by adding audience verification options and logging

This commit is contained in:
Mabe
2026-06-21 17:31:55 +02:00
parent d23aee37e8
commit d866664064
+9 -4
View File
@@ -127,16 +127,21 @@ async def validate_token(credentials: HTTPAuthorizationCredentials = Security(se
logger.debug("Validating token with JWKS; issuer=%s, audience=%s", discovery.get("issuer"), settings.oidc_audience)
# Only pass `audience` to the decoder if configured. Some providers
# (or local development setups) may not include the aud claim in a
# way that matches your API identifier; in that case leave
# `OIDC_AUDIENCE` unset and the audience check will be skipped.
# way that matches your API identifier; in that case disable audience
# verification in python-jose instead of passing audience=None.
jwt_kwargs = {
"algorithms": [key.get("alg", "RS256")],
"issuer": discovery.get("issuer") if settings.oidc_verify_iss else None,
}
options = {"verify_signature": True}
if settings.oidc_verify_iss:
jwt_kwargs["issuer"] = discovery.get("issuer")
if settings.oidc_audience:
jwt_kwargs["audience"] = settings.oidc_audience
else:
options["verify_aud"] = False
verified = jwt.decode(token, public_key, **jwt_kwargs)
logger.debug("JWT decode args: options=%s, jwt_kwargs=%s", options, jwt_kwargs)
verified = jwt.decode(token, public_key, options=options, **jwt_kwargs)
logger.debug("JWT validation succeeded; claims=%s", verified)
except JWTError:
logger.exception("JWT validation failed, attempting introspection")