How to Integrate Auth0 SSO with FastAPI

How to Integrate Auth0 SSO with FastAPI

Quick & Easy way to integrate Auth0 platform SSO service with FastAPI to secure the endpoints

If you want to integrate Auth0 SSO (or any social login) for all your authentication and authorization needs, you're in the right place! Let's get started together!

Here are the steps

  1. Step 1: Use FastAPI-Auth0 python library.

  2. Step 2: Create Auth0 FastAPI Security dependency

from typing import Any, Iterator

from fastapi import Depends, FastAPI, Security
from fastapi_auth0.auth import Auth0
from pydantic import RootModel


class RootUser(RootModel):
    root: dict[str, Any]

    def __iter__(self) -> Iterator[str]:
        return iter(self.root)

    def __getitem__(self, item) -> Any:
        return self.root[item]

auth = Auth0(
    domain="<Your auth0 domain>",
    api_audience="<Your auth0 api audience>",
    auth0user_model=RootUser
) # Note - You can use customized pydantic user model too
  1. Step 3: Secured the Endpoint using FastAPI dependency
app = FastAPI()

# NOTE - I am using `auth.implicit_scheme` to implement Auth0 SSO
@app.get("/protected", dependencies=[Depends(auth.implicit_scheme)])
# NOTE -`auth.get_user` performs the login & returns user identity 
def get_secure(user: RootUser = Security(auth.get_user)):
    return {"message": f"{user}"}

  1. Step 4: (Optional) If you want the client id to be auto-filled then modify it accordingly
from typing import Any, Iterator

from fastapi import Depends, FastAPI, Security
from fastapi_auth0.auth import Auth0
from pydantic import RootModel


class RootUser(RootModel):
    root: dict[str, Any]

    def __iter__(self) -> Iterator[str]:
        return iter(self.root)

    def __getitem__(self, item) -> Any:
        return self.root[item]


auth = Auth0(
    domain="<Your auth0 domain>",
    api_audience="<Your auth0 api audience>",
    auth0user_model=RootUser
) # Note - You can use a customized pydantic user model too
app = FastAPI(swagger_ui_init_oauth={"clientId": "<your client id>"})

@app.get("/protected", dependencies=[Depends(auth.implicit_scheme)])
def get_secure(user: RootUser = Security(auth.get_user)):
    return {"message": f"{user}"}

Did you find this article valuable?

Support import idea by becoming a sponsor. Any amount is appreciated!