@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 2 3 4 5 |
from pydantic import BaseModel class AuthCredentials(BaseModel): username: str password: str |
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 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.