Simple library for using a third party authentication service like Keycloak or Auth0 with FastAPI
Project description
FastAPI Third Party Auth
Documentation: https://fastapi-third-party-auth.readthedocs.io/
Source Code: https://github.com/aiwizo/fastapi-third-party-auth
Simple library for using a third party authentication service with FastAPI. Verifies and decrypts 3rd party OpenID Connect tokens to protect your endpoints.
Easily used with authentication services such as:
- Keycloak (open source)
- SuperTokens (open source)
- Auth0
- Okta
FastAPI's generated interactive documentation supports the grant flows:
GrantType.AUTHORIZATION_CODE
GrantType.IMPLICIT
GrantType.PASSWORD
GrantType.CLIENT_CREDENTIALS
Installation
poetry add fastapi-third-party-auth
Or, for the old-timers:
pip install fastapi-third-party-auth
Usage
See this example for how to use
docker-compose
to set up authentication with fastapi-third-party-auth
+
Keycloak.
Standard usage
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}")
Optional: Custom token validation
The IDToken class will accept any number of extra fields but you can also validate fields in the token like this:
class MyAuthenticatedUser(IDToken):
custom_field: str
custom_default: float = 3.14
auth = Auth(
...,
idtoken_model=MyAuthenticatedUser,
)
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Hashes for fastapi-third-party-auth-0.1.0.tar.gz
Algorithm | Hash digest | |
---|---|---|
SHA256 | 4dd52acbe53baa7fd2726752d8a8b72168230c09cffe9b7f3ef046d045808798 |
|
MD5 | d3e5c801b28535aac9a8c11b298c8240 |
|
BLAKE2b-256 | cbda8a2ef779a5a88f9776584990d83810d0f6028163e2e1398594e078d6cb05 |
Hashes for fastapi_third_party_auth-0.1.0-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 7f0a3e981813ab66f6ff036ef54536325074d690f21d3e18e303eef327ebdc76 |
|
MD5 | 93c2b5b0bad4554ef235f9eb35b422a5 |
|
BLAKE2b-256 | ed6e4f20de374c836fb0f326667c5eb3a8441c0163655cf5d2ef4c3184bc2a7d |