API Documentation
This part of the documentation covers all the interfaces of Requests. For parts where Requests depends on external libraries, we document the most important right here and provide links to the canonical documentation.
Middleware
- class fastapi_keycloak_middleware.KeycloakMiddleware(app: FastAPI, keycloak_configuration: KeycloakConfiguration, exclude_patterns: List[str] | None = None, user_mapper: Callable[[Dict[str, Any]], Awaitable[Any]] | None = None, scope_mapper: Callable[[List[str]], List[str]] | None = None)
This class represents the middleware for FastAPI. It will authenticate a user based on a token. It currently only supports one backend (Keycloak backend).
The middleware will add the user object to the request object. It optionally can also compile a list of scopes and add it to the request object as well, which can later be used for authorization.
- Parameters:
app (FastAPI) – The FastAPI app instance, is automatically passed by FastAPI
keycloak_configuration (KeycloakConfiguration) – KeyCloak configuration object. For potential options, see the KeycloakConfiguration schema.
exclude_paths (List[str], optional) – List of paths that should be excluded from authentication. Defaults to an empty list. The strings will be compiled to regular expressions and used to match the path. If the path matches, the middleware will skip authentication.
user_mapper (Callable[ [Dict[str, Any]], Awaitable[Any] ] optional) – Custom async function that gets the userinfo extracted from AT and should return a representation of the user that is meaningful to you, the user of this library, defaults to None
scope_mapper (Callable[[List[str]], List[str]], optional) – Custom async function that transforms the claim values extracted from the token to permissions meaningful for your application, defaults to None
Support Classes
- class fastapi_keycloak_middleware.KeycloakConfiguration(*, realm: str, url: str, client_id: str, client_secret: str, claims: list[str] = ['sub', 'name', 'family_name', 'given_name', 'preferred_username', 'email'], reject_on_missing_claim: bool = True, authentication_scheme: str = 'Bearer', authorization_method: AuthorizationMethod = AuthorizationMethod.NONE, authorization_claim: str = 'roles', use_introspection_endpoint: bool = False, enable_device_authentication: bool = False, device_authentication_claim: str = 'is_device')
This is a Pydantic schema used to pass backend konfiguration for the Keycloak Backend to the middleware.
- Parameters:
realm (str) – Keycloak realm that should be used for token authentication.
url (str) – URL of the Keycloak server. If you use legacy Keycloak versions or still have the auth context, you need to add the auth context to the URL.
client_id (str, optional) – Client ID of the client used to validate the token. The client id is only needed if you use the introspection endpoint.
client_secret (str, optional) – Client secret of the client used to validate the token. The client secret is only needed if you use the introspection endpoint.
claims (list[str], optional) – List of claims that should be extracted from the access token. Defaults to
["sub", "name", "family_name", "given_name", "preferred_username", "email"].reject_on_missing_claim (bool, optional) – Whether to reject the request if a claim is missing. Defaults to
True.authentication_scheme (str, optional) – Authentication scheme to use. Defaults to
Bearer.authorization_method (AuthorizationMethod, optional) – Authorization method to use. Defaults to
NONE.authorization_claim (str, optional) – Claim to use for extracting authorization scopes. Defaults to
roles.use_introspection_endpoint (bool, optional) – Whether to use the introspection endpoint for token validation. Should not be needed for Keycloak in general as Keycloak doesn’t support opaque tokens. Defaults to
False.enable_device_authentication (bool, optional) – Whether to enable device authentication. If device authentication is enabled, the middleware will ignore required user claims and not attempt to map the user. The token will be validated and then the request forwarded unmodified. Defaults to
False.device_authentication_claim – This claim will be used to check if the token is a device token. Defaults to
is_device. This is only used ifenable_device_authenticationis set toTrue. The value is extracted from the claim and checked if its a truthy value. To be specific,bool(value)must evaluate toTrue.
- class fastapi_keycloak_middleware.AuthorizationResult(*, method: None | AuthorizationMethod = None, authorized: bool = False, matched_scopes: List[str] = [])
This class contains the schema representing an authorization result.
The following attributes will be set when returning the class in your path function:
- authorized: bool
Whether the user is authorized or not
- matched_scopes: List[str]
The scopes that matched the user’s scopes
- method: None | AuthorizationMethod
The method that was used to authorize the user
- class fastapi_keycloak_middleware.AuthorizationMethod(value)
This Enum can be used to set authorization methods. Please use the Enum values instead of the values behind the Enums.
Supported options are:
AuthorizationMethod.NONE: No authorization is performed.AuthorizationMethod.CLAIM: Authorization is performed by extracting the authorization scopes from a claim.
- class fastapi_keycloak_middleware.MatchStrategy(value)
This Enum can be used to set the authorization match strategy if multiple scopes are bassed to the
require_permissiondecorator. Please use the Enum values instead of the values behind the Enums.Supported options are:
MatchStrategy.OR: One of the provided scopes must matchMatchStrategy.AND: All of the provided scopes must match
Decorators
These decorators can be used to wrap certain paths in your FastAPI application.
- fastapi_keycloak_middleware.require_permission(permissions: str | List[str], match_strategy: MatchStrategy = MatchStrategy.AND) Callable
This decorator can be used to enfore certain permissions for the path function it is applied to.
- Parameters:
permissions (Union[str, List[str]], optional) – The permissions that are required to access the path function. Can be a single string or a list of strings.
match_strategy (MatchStrategy, optional) – The strategy that is used to match the permissions. Defaults to
MatchStrategy.AND.
- Returns:
The decorated function
- fastapi_keycloak_middleware.strip_request(func)
Wrapper that strips the request argument from kwargs
FastAPI Depdencies
These are the dependencies that you can use in your FastAPI application.
- async fastapi_keycloak_middleware.get_user(request: Request) Any
This function can be used as FastAPI dependency to easily retrieve the user object
- async fastapi_keycloak_middleware.get_authorization_result(authorization_result: AuthorizationResult | None = None) AuthorizationResult
This function can be used as FastAPI dependency and returns the authorization result