# 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](https://github.com/dorinclisu/fastapi-auth0) python library.
    
2. **Step 2:** Create Auth0 FastAPI Security dependency

```python
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
```
    
3. **Step 3:** Secured the Endpoint using FastAPI dependency

```python
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}"}
```
    
    ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1732690017380/631ff9d4-730d-4b59-8ac1-f5ff2d8a7855.png align="center")
    
    ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1732690094712/42841d13-f09b-4f67-9cfc-f59a32de1d5b.png align="center")
    
4. **Step 4:** (Optional) If you want the client id to be auto-filled then modify it accordingly

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

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1732690590226/5bdbe27f-3d45-45a8-b65d-4c38ab7dc79a.png align="center")
