Concept Flow - Protected routes
Client sends request
Check for auth token
Reject request
Validate token
Allow access
Return protected data
The server checks if the client request has a valid token before allowing access to protected data.
Jump into concepts and practice - no test required
from fastapi import FastAPI, Depends, HTTPException, status from fastapi.security import OAuth2PasswordBearer app = FastAPI() oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") async def get_current_user(token: str = Depends(oauth2_scheme)): if token != "validtoken": raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token") return {"user": "alice"} @app.get("/protected") async def protected_route(current_user: dict = Depends(get_current_user)): return {"message": f"Hello {current_user['user']}"}
| Step | Action | Token Present? | Token Valid? | Result | Response |
|---|---|---|---|---|---|
| 1 | Client requests /protected without token | No | N/A | Reject request | 401 Unauthorized |
| 2 | Client requests /protected with token='invalidtoken' | Yes | No | Reject request | 401 Unauthorized |
| 3 | Client requests /protected with token='validtoken' | Yes | Yes | Allow access | {"message": "Hello alice"} |
| Variable | Start | Request 1 | Request 2 | Request 3 |
|---|---|---|---|---|
| token | None | None | invalidtoken | validtoken |
| current_user | None | None | None | {"user": "alice"} |
Protected routes require a valid token to access. Use OAuth2PasswordBearer to extract token. Validate token in a dependency function. Raise HTTPException(401) if invalid. Pass user info to route via Depends. Return protected data only if authorized.
Depends to declare dependencies like authentication checks.Depends with a function that verifies tokens enforces protection on routes./users/me without a token?
from fastapi import FastAPI, Depends, HTTPException
from fastapi.security import OAuth2PasswordBearer
app = FastAPI()
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
def get_current_user(token: str = Depends(oauth2_scheme)):
if token != "validtoken":
raise HTTPException(status_code=401, detail="Invalid token")
return {"username": "user1"}
@app.get("/users/me")
async def read_users_me(current_user: dict = Depends(get_current_user)):
return current_userget_current_user checks if the token equals "validtoken"; otherwise, it raises HTTP 401.oauth2_scheme will not provide a valid token, so the check fails and raises HTTP 401.from fastapi import FastAPI, Depends, HTTPException
from fastapi.security import OAuth2PasswordBearer
app = FastAPI()
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
def get_current_user(token: str):
if token != "secret":
raise HTTPException(status_code=401, detail="Unauthorized")
return {"user": "admin"}
@app.get("/dashboard")
async def dashboard(user: dict = Depends(get_current_user)):
return usertoken: str but does not use Depends(oauth2_scheme) to get the token automatically.Depends(oauth2_scheme), FastAPI won't provide the token, causing an error.