Skip to main content

Command Palette

Search for a command to run...

How to Integrate Auth0 SSO with FastAPI

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

Updated
•2 min read
How to Integrate Auth0 SSO with FastAPI

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}"}

Express Ideas

Part 2 of 5

Small & self-contained tips that can help in many larger context. This is my attempt to help you out & shed some light on express ideas that helped me because it's just an idea that all you need 💡.

Up next

Working with Avro file format in Python the right way

Here are some quick helpful tips for using Avro file format correctly in python. Note: I am asumming you familair with Apache Avro file format, its advantages, its shortcomings, etc. Tip no 1: Use the correct package Instead of using the official p...