code-specialist / fastapi-keycloak

Keycloak integration for Python FastAPI
https://fastapi-keycloak.code-specialist.com/
Apache License 2.0
193 stars 50 forks source link

Missing token introspection #48

Open hall-b opened 2 years ago

hall-b commented 2 years ago

The library is missing the token introspection as defined in the standard: https://datatracker.ietf.org/doc/html/rfc7662 A consequence of this is that even if a user has been disabled on the keycloak side, if a user still has a valid JWT that was generated before, the library will still consider it to be valid. We'll have to wait until the JWT expiration time (that could last for long..) before a user can be considered as completely blocked.

A very simple piece of code that can handle this:

    from authlib.integrations.requests_client import OAuth2Session
    from fastapi import HTTPException

    oauth = OAuth2Session(client_id=client_id, client_secret=client_secret)
    result = oauth.introspect_token(
        url=f"{keycloak_server}/auth/realms/{realm_name}/protocol/openid-connect/token/introspect",
        token=token,
    )
    content = json.loads(result.content.decode())
    if not content["active"]:
        raise HTTPException(status_code=401, detail="Token expired or invalid")
    else:
        .....