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

fastapi_keycloak_middleware.setup_keycloak_middleware(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, add_exception_response: bool = True, add_swagger_auth: bool = False, swagger_auth_scopes: List[str] | None = None, swagger_auth_pkce: bool = True, swagger_scheme_name: str = 'keycloak-openid')

This function can be used to initialize the middleware on an existing FastAPI application. Note that the middleware can also be added directly.

This function adds the benefit of automatically adding correct response types as well as the OpenAPI configuration.

Parameters:
  • app – The FastAPI app instance, required

  • keycloak_configuration (KeycloakConfiguration) – KeyCloak configuration object. For potential options, see the KeycloakConfiguration schema.

  • exclude_patterns (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

  • add_exception_response (bool, optional) – Whether to add exception responses for 401 and 403. Defaults to True.

  • add_swagger_auth (bool, optional) – Whether to add OpenID Connect authentication to the OpenAPI schema. Defaults to False.

  • swagger_auth_scopes (List[str], optional) – Scopes to use for the Swagger UI authentication. Defaults to [‘openid’, ‘profile’].

  • swagger_auth_pkce (bool, optional) – Whether to use PKCE with the Swagger UI authentication. Defaults to True.

  • swagger_scheme_name (str, optional) – Name of the OpenAPI security scheme. Defaults to ‘keycloak-openid’.

class fastapi_keycloak_middleware.KeycloakMiddleware(app: Callable[[MutableMapping[str, Any], Callable[[], Awaitable[MutableMapping[str, Any]]], Callable[[MutableMapping[str, Any]], Awaitable[None]]], Awaitable[None]], 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_patterns (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, swagger_client_id: str | None, client_secret: str | None = None, 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', verify: bool | str = True, decode_options: Dict[str, bool | int] = {'verify_aud': True, 'verify_exp': True, 'verify_signature': True})

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) – Client ID of the client used to validate the token.

  • swagger_client_id (str, optional) – Client ID for swagger UI authentication. Defaults to None.

  • 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 if enable_device_authentication is set to True. The value is extracted from the claim and checked if its a truthy value. To be specific, bool(value) must evaluate to True.

  • verify (Union[bool,str], optional) – Whether to verify SSL connection. Defaults to True

  • decode_options (Dict[str, Union[bool,int]], optional) – Defines options to be passed to python-jose’s decode` function. Defaults to {"verify_signature": True, "verify_aud": True, "verify_exp": True}. See the following project for an overview of acceptable options: https://github.com/mpdavis/python-jose/blob/4b0701b46a8d00988afcc5168c2b3a1fd60d15d8/jose/jwt.py#L81

model_computed_fields: ClassVar[dict[str, ComputedFieldInfo]] = {}

A dictionary of computed field names and their corresponding ComputedFieldInfo objects.

model_config: ClassVar[ConfigDict] = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

model_fields: ClassVar[dict[str, FieldInfo]] = {'authentication_scheme': FieldInfo(annotation=str, required=False, default='Bearer', title='Authentication Scheme', description='The authentication scheme to use.'), 'authorization_claim': FieldInfo(annotation=str, required=False, default='roles', title='Authorization Claim', description='The claim to use for authorization.'), 'authorization_method': FieldInfo(annotation=AuthorizationMethod, required=False, default=<AuthorizationMethod.NONE: 0>, title='Authorization Method', description='The authorization method to use.'), 'claims': FieldInfo(annotation=list[str], required=False, default=['sub', 'name', 'family_name', 'given_name', 'preferred_username', 'email'], title='Claims', description='The claims to add to the user object.'), 'client_id': FieldInfo(annotation=str, required=True, title='Client ID', description='The client ID.'), 'client_secret': FieldInfo(annotation=Union[str, NoneType], required=False, title='Client Secret', description='The client secret.'), 'decode_options': FieldInfo(annotation=Dict[str, Union[bool, int]], required=False, default={'verify_signature': True, 'verify_aud': True, 'verify_exp': True}, title='JWT Decode Options', description='Decode options that are passed to python-jose decode function.'), 'device_authentication_claim': FieldInfo(annotation=str, required=False, default='is_device', title='Device Authentication Claim', description='The claim that will be checked. If present and if it evaluates to true, the device authentication will be applied for the request.'), 'enable_device_authentication': FieldInfo(annotation=bool, required=False, default=False, title='Enable Device Authentication', description='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.'), 'realm': FieldInfo(annotation=str, required=True, title='Realm', description='The realm to use.'), 'reject_on_missing_claim': FieldInfo(annotation=bool, required=False, default=True, title='Reject on Missing Claim', description='Whether to reject the request if a claim is missing.'), 'swagger_client_id': FieldInfo(annotation=Union[str, NoneType], required=True, title='Swagger Client ID', description='The client ID for the swagger UI.'), 'url': FieldInfo(annotation=str, required=True, title='URL', description='The URL of the Keycloak server.'), 'use_introspection_endpoint': FieldInfo(annotation=bool, required=False, default=False, title='Use Introspection Endpoint', description='Whether to use the introspection endpoint.'), 'verify': FieldInfo(annotation=Union[bool, str], required=False, default=True, title='Verify', description='Whether to verify the SSL connection')}

Metadata about the fields defined on the model, mapping of field names to [FieldInfo][pydantic.fields.FieldInfo].

This replaces Model.__fields__ from Pydantic V1.

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

model_computed_fields: ClassVar[dict[str, ComputedFieldInfo]] = {}

A dictionary of computed field names and their corresponding ComputedFieldInfo objects.

model_config: ClassVar[ConfigDict] = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

model_fields: ClassVar[dict[str, FieldInfo]] = {'authorized': FieldInfo(annotation=bool, required=False, default=False, title='Authorized', description='Whether the user is authorized or not.'), 'matched_scopes': FieldInfo(annotation=List[str], required=False, default=[], title='Matched Scopes', description="The scopes that matched the user's scopes."), 'method': FieldInfo(annotation=Union[NoneType, AuthorizationMethod], required=False, title='Method', description='The method used to authorize the user.')}

Metadata about the fields defined on the model, mapping of field names to [FieldInfo][pydantic.fields.FieldInfo].

This replaces Model.__fields__ from Pydantic V1.

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_permission decorator. Please use the Enum values instead of the values behind the Enums.

Supported options are:

  • MatchStrategy.OR: One of the provided scopes must match

  • MatchStrategy.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