fix: enhance JWT validation by adding audience verification options and logging
This commit is contained in:
+9
-4
@@ -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)
|
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
|
# Only pass `audience` to the decoder if configured. Some providers
|
||||||
# (or local development setups) may not include the aud claim in a
|
# (or local development setups) may not include the aud claim in a
|
||||||
# way that matches your API identifier; in that case leave
|
# way that matches your API identifier; in that case disable audience
|
||||||
# `OIDC_AUDIENCE` unset and the audience check will be skipped.
|
# verification in python-jose instead of passing audience=None.
|
||||||
jwt_kwargs = {
|
jwt_kwargs = {
|
||||||
"algorithms": [key.get("alg", "RS256")],
|
"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:
|
if settings.oidc_audience:
|
||||||
jwt_kwargs["audience"] = 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)
|
logger.debug("JWT validation succeeded; claims=%s", verified)
|
||||||
except JWTError:
|
except JWTError:
|
||||||
logger.exception("JWT validation failed, attempting introspection")
|
logger.exception("JWT validation failed, attempting introspection")
|
||||||
|
|||||||
Reference in New Issue
Block a user