Welcome to fastapi-third-party-auth’s documentation!
Verify and decrypt 3rd party OpenID Connect tokens to protect your FastAPI endpoints.
Easily used with authenticators such as:
Keycloak (open source)
SuperTokens (open source)
FastAPI’s generated interactive documentation supports the grant types
authorization_code
, implicit
, password
and client_credentials
.
Indices and tables
Installation
poetry add fastapi-third-party-auth
Or, for the old-timers:
pip install fastapi-third-party-auth
Example
Basic configuration for verifying OIDC tokens.
from fastapi import Depends
from fastapi import FastAPI
from fastapi import Security
from fastapi import status
from fastapi_third_party_auth import Auth
from fastapi_third_party_auth import GrantType
from fastapi_third_party_auth import KeycloakIDToken
auth = Auth(
openid_connect_url="http://localhost:8080/auth/realms/my-realm/.well-known/openid-configuration",
issuer="http://localhost:8080/auth/realms/my-realm", # optional, verification only
client_id="my-client", # optional, verification only
scopes=["email"], # optional, verification only
grant_types=[GrantType.IMPLICIT], # optional, docs only
idtoken_model=KeycloakIDToken, # optional, verification only
)
app = FastAPI(
title="Example",
version="dev",
dependencies=[Depends(auth)],
)
@app.get("/protected")
def protected(id_token: KeycloakIDToken = Security(auth.required)):
return dict(message=f"You are {id_token.email}")
API Reference
Auth
Module for validating Open ID Connect tokens.
Usage
# This assumes you've already configured Auth in your_app/auth.py
from your_app.auth import auth
@app.get("/auth")
def test_auth(authenticated_user: IDToken = Security(auth.required)):
return f"Hello {authenticated_user.preferred_username}"
- class fastapi_third_party_auth.auth.Auth(openid_connect_url: str, issuer: ~typing.Optional[str] = None, client_id: ~typing.Optional[str] = None, scopes: ~typing.List[str] = [], grant_types: ~typing.List[~fastapi_third_party_auth.grant_types.GrantType] = [<GrantType.IMPLICIT: 'implicit'>], signature_cache_ttl: int = 3600, idtoken_model: ~typing.Type[~fastapi_third_party_auth.idtoken_types.IDToken] = <class 'fastapi_third_party_auth.idtoken_types.IDToken'>)
- __init__(openid_connect_url: str, issuer: ~typing.Optional[str] = None, client_id: ~typing.Optional[str] = None, scopes: ~typing.List[str] = [], grant_types: ~typing.List[~fastapi_third_party_auth.grant_types.GrantType] = [<GrantType.IMPLICIT: 'implicit'>], signature_cache_ttl: int = 3600, idtoken_model: ~typing.Type[~fastapi_third_party_auth.idtoken_types.IDToken] = <class 'fastapi_third_party_auth.idtoken_types.IDToken'>)
Configure authentication
auth = Auth(...)
and then:Show authentication in the interactive docs with
Depends(auth)
when setting up FastAPI.Use
Security(auth.required)
orSecurity(auth.optional)
in your endpoints to check user credentials.
- Parameters
openid_connect_url (URL) – URL to the “well known” openid connect config e.g. https://dev-123456.okta.com/.well-known/openid-configuration
issuer (URL) – (Optional) The issuer URL from your auth server.
client_id (str) – (Optional) The client_id configured by your auth server.
scopes (Dict[str, str]) – (Optional) A dictionary of scopes and their descriptions.
grant_types (List[GrantType]) – (Optional) Grant types shown in docs.
signature_cache_ttl (int) – (Optional) How many seconds your app should cache the authorization server’s public signatures.
idtoken_model (Type) – (Optional) The model to use for validating the ID Token.
- Raises
Nothing intentional –
- required(security_scopes: SecurityScopes, authorization_credentials: Optional[HTTPAuthorizationCredentials] = Depends(HTTPBearer)) IDToken
Validate and parse OIDC ID token against configuration. Note this function caches the signatures and algorithms of the issuing server for signature_cache_ttl seconds.
- Parameters
security_scopes (SecurityScopes) – Security scopes
auth_header (str) – Base64 encoded OIDC Token. This is invoked behind the scenes by Depends.
- Returns
User information
- Return type
IDToken (self.idtoken_model)
- Raises
HTTPException(status_code=401, detail=f"Unauthorized – {err}”)
IDToken validation errors –
- optional(security_scopes: SecurityScopes, authorization_credentials: Optional[HTTPAuthorizationCredentials] = Depends(HTTPBearer)) Optional[IDToken]
Optionally validate and parse OIDC ID token against configuration. Will not raise if the user is not authenticated. Note this function caches the signatures and algorithms of the issuing server for signature_cache_ttl seconds.
- Parameters
security_scopes (SecurityScopes) – Security scopes
auth_header (str) – Base64 encoded OIDC Token. This is invoked behind the scenes by Depends.
- Returns
User information
- Return type
IDToken (self.idtoken_model)
- Raises
IDToken validation errors –
- authenticate_user(security_scopes: SecurityScopes, authorization_credentials: Optional[HTTPAuthorizationCredentials], auto_error: bool) Optional[IDToken]
Validate and parse OIDC ID token against against configuration. Note this function caches the signatures and algorithms of the issuing server for signature_cache_ttl seconds.
- Parameters
security_scopes (SecurityScopes) – Security scopes
auth_header (str) – Base64 encoded OIDC Token
auto_error (bool) – If True, will raise an HTTPException if the user is not authenticated.
- Returns
User information
- Return type
IDToken (self.idtoken_model)
- Raises
HTTPException(status_code=401, detail=f"Unauthorized – {err}”)
- model: SecurityBase
- scheme_name: str
Grant Types
IDToken Types
- class fastapi_third_party_auth.idtoken_types.IDToken(*, iss: str, sub: str, aud: Union[str, List[str]], exp: int, iat: int, **extra_data: Any)
Pydantic model representing an OIDC ID Token.
ID Tokens are polymorphic and may have many attributes not defined in the spec thus this model accepts all addition fields. Only required fields are listed in the attributes section of this docstring or enforced by pydantic.
See the specifications here. https://openid.net/specs/openid-connect-core-1_0.html#IDToken
- Parameters
iss (str) – Issuer Identifier for the Issuer of the response.
sub (str) – Subject Identifier.
aud (Union[str, List[str]]) – Audience(s) that this ID Token is intended for.
exp (str) – Expiration time on or after which the ID Token MUST NOT be accepted for processing.
iat (iat) – Time at which the JWT was issued.
- iss: str
- sub: str
- aud: Union[str, List[str]]
- exp: int
- iat: int
- class fastapi_third_party_auth.idtoken_types.OktaIDToken(*, iss: str, sub: str, aud: Union[str, List[str]], exp: int, iat: int, auth_time: int, ver: int, jti: str, amr: List[str], idp: str, nonce: str, at_hash: str, name: str, email: str, preferred_username: str, **extra_data: Any)
Pydantic Model for the IDToken returned by Okta’s OIDC implementation.
- auth_time: int
- ver: int
- jti: str
- amr: List[str]
- idp: str
- nonce: str
- at_hash: str
- name: str
- email: str
- preferred_username: str
- class fastapi_third_party_auth.idtoken_types.KeycloakIDToken(*, iss: str, sub: str, aud: Union[str, List[str]], exp: int, iat: int, jti: str, name: str, email: str, email_verified: bool, preferred_username: str, **extra_data: Any)
Pydantic Model for the IDToken returned by Keycloak’s OIDC implementation.
- jti: str
- name: str
- email: str
- email_verified: bool
- preferred_username: str