Skip to main content

FastAPI Auth OpenID Connect

Project description

FastAPI OIDC Security

This library allows your server-side application to check credentials with ease using OpenID Connect token flows. Use it with Firebase, Keycloak, Authentik or other OIDC providers.

Simple usage

You can just add auth_user dependency to take token data into your FastAPI routes.

from fastapi import FastAPI
from fastapi_auth_oidc import OIDCProvider, IDToken
from fastapi_auth_oidc.exceptions import AuthenticationException


app = FastAPI()
auth_user = OIDCProvider(
    configuration_uri="https://example.domain/issuer/.well-known/openid-configuration",
    client_id="my-client",
)


@app.exception_handler(AuthenticationException)
def invalid_credentials(request: Request, exc: InvalidCredentialsException):
    return JSONResponse(
        status_code=403,
        content={"detail": "Invalid token"},
    )


@app.get("/me")
def get_me(
    user: Annotated[IDToken | None, Depends(auth_user)],
):
    return user.model_dump() if user else {}

Advanced authorization

For authorization with this package you shoud create security guards. Example below provides NamedTuple with 2 authorization methods: authenticated and is_admin. They uses FastAPI dependency injection to ensure user and validate token. Now you shoud alse use them as dependencies.

from typing import Annotated, NamedTuple

from fastapi import Depends
from fastapi_auth_oidc import IDToken, OIDCProvider
from fastapi_auth_oidc import IDToken, OIDCProvider
from fastapi_auth_oidc.exceptions import UnauthenticatedException


# Taking a new property mapping from JWT
class MyIDToken(IDToken):
    my_app_permissions: str | None = None

# Setting up provider
auth_user = OIDCProvider(
    configuration_uri=str(settings.oidc_configuration_uri),
    client_id=settings.oidc_client_id,
    token_type=MyIDToken,
)
TokenData = Annotated[MyIDToken | None, Depends(auth_user)]


# Check if user token set and valid
def get_authenticated(user: TokenData):
    if not user:
        raise UnauthenticatedException()
    return user


# Check if user has `my_app_permissions` field in JWT token and it equals to `admin`.
def get_is_admin(user: Annotated[MyIDToken, Depends(get_authenticated)]):
    if not user.my_app_permissions == "admin":
        raise Exception()
    return user


# This utilities in pretty form
class User(NamedTuple):
    authenticated = Annotated[IDToken, Depends(get_authenticated)]
    is_admin = Annotated[IDToken, Depends(get_is_admin)]

# Usage
app = FastAPI()

@app.get("/everybody")
def get_me(user: TokenData):
    """Everybody can open `"/everybody` =)"""
    return user.model_dump() if user else {}


@app.get("/authenticated")
def get_me(user: User.authenticated):
    """Only users with valid JWT token will get their data"""
    return user.model_dump()


@app.get("/admin")
def get_me(user: User.is_admin):
    """Only users with `my_app_permissions == "admin"` can get their data"""
    return user.model_dump()

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

fastapi_auth_oidc-0.1.5.tar.gz (45.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

fastapi_auth_oidc-0.1.5-py3-none-any.whl (7.2 kB view details)

Uploaded Python 3

File details

Details for the file fastapi_auth_oidc-0.1.5.tar.gz.

File metadata

  • Download URL: fastapi_auth_oidc-0.1.5.tar.gz
  • Upload date:
  • Size: 45.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.11.11

File hashes

Hashes for fastapi_auth_oidc-0.1.5.tar.gz
Algorithm Hash digest
SHA256 f5e665ade5787408afba4b615d4fa572475ea8691b70585b79ea46830a8b0e76
MD5 b51d17190a794bbcbde2962084fb79d0
BLAKE2b-256 8b0d568e12c35b65615c9fe47ebae0b36f8f8319d756a6ff679bd0dd007a09dd

See more details on using hashes here.

File details

Details for the file fastapi_auth_oidc-0.1.5-py3-none-any.whl.

File metadata

File hashes

Hashes for fastapi_auth_oidc-0.1.5-py3-none-any.whl
Algorithm Hash digest
SHA256 c3bd91460fc8e2dbd31794f881eb7329069ff30a3d9084d942246a81e73acd3c
MD5 f72d4bef2d9d2275d23105711286c4e1
BLAKE2b-256 83fbe688b785d973408405d2ec92c1589c6b3a1ec45985b857253b4d6f5ae189

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page