How to authenticate static routes in fastapi?

Member

by lily , in category: Third Party Scripts , 10 days ago

How to authenticate static routes in fastapi?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by tressie.damore , 9 days ago

@lily 

To authenticate static routes in FastAPI, you can use dependency injection with Pydantic models for request headers or cookies. Here's an example of how you can authenticate a static route using a dependency in FastAPI:

  1. Create a Pydantic model for your authentication credentials:
1
2
3
4
5
from pydantic import BaseModel

class AuthCredentials(BaseModel):
    username: str
    password: str


  1. Create a dependency function to authenticate the user:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
from fastapi import Depends, HTTPException, status
from fastapi.security import HTTPBasic, HTTPBasicCredentials

security = HTTPBasic()

def authenticate_user(credentials: HTTPBasicCredentials = Depends(security)):
    correct_username = "admin"
    correct_password = "password"
    
    if credentials.username != correct_username or credentials.password != correct_password:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Incorrect username or password",
            headers={"WWW-Authenticate": "Basic"},
        )
    
    return credentials.username


  1. Use the dependency function in your route:
1
2
3
4
5
6
7
from fastapi import FastAPI

app = FastAPI()

@app.get("/protected")
def protected_route(username: str = Depends(authenticate_user)):
    return {"message": "Hello, {}".format(username)}


Now, when a user tries to access the "/protected" route, they will be prompted to enter their credentials. If the username and password are correct, they will be granted access to the route.


You can customize the authentication process further by using different security schemes, such as API keys or OAuth2 tokens, and by implementing more complex logic in the dependency function.