|
| 1 | +from fastapi import Depends, FastAPI, HTTPException, Request, WebSocket |
| 2 | +from fastapi.responses import JSONResponse |
| 3 | +from pydantic import BaseModel |
| 4 | + |
| 5 | +from fastapi_paseto import AuthPASETO |
| 6 | +from fastapi_paseto.exceptions import AuthPASETOException |
| 7 | + |
| 8 | +app = FastAPI() |
| 9 | + |
| 10 | + |
| 11 | +class User(BaseModel): |
| 12 | + username: str |
| 13 | + password: str |
| 14 | + |
| 15 | + |
| 16 | +@AuthPASETO.load_config |
| 17 | +def get_config(): |
| 18 | + """Return the application auth configuration.""" |
| 19 | + |
| 20 | + return {"authpaseto_secret_key": "secret"} |
| 21 | + |
| 22 | + |
| 23 | +@app.exception_handler(AuthPASETOException) |
| 24 | +def authpaseto_exception_handler(request: Request, exc: AuthPASETOException): |
| 25 | + """Return auth exceptions as JSON for HTTP endpoints.""" |
| 26 | + |
| 27 | + return JSONResponse(status_code=exc.status_code, content={"detail": exc.message}) |
| 28 | + |
| 29 | + |
| 30 | +@app.post("/login") |
| 31 | +def login(user: User, Authorize: AuthPASETO = Depends()): |
| 32 | + """Issue an access token for the demo user.""" |
| 33 | + |
| 34 | + if user.username != "test" or user.password != "test": |
| 35 | + raise HTTPException(status_code=401, detail="Bad username or password") |
| 36 | + |
| 37 | + access_token = Authorize.create_access_token(subject=user.username) |
| 38 | + return {"access_token": access_token} |
| 39 | + |
| 40 | + |
| 41 | +@app.websocket("/ws/header") |
| 42 | +async def websocket_header( |
| 43 | + websocket: WebSocket, |
| 44 | + Authorize: AuthPASETO = Depends(), |
| 45 | +) -> None: |
| 46 | + """Authorize the websocket using the configured auth header.""" |
| 47 | + |
| 48 | + Authorize.paseto_required() |
| 49 | + await websocket.accept() |
| 50 | + await websocket.send_json({"user": Authorize.get_subject()}) |
| 51 | + await websocket.close() |
| 52 | + |
| 53 | + |
| 54 | +@app.websocket("/ws/query") |
| 55 | +async def websocket_query( |
| 56 | + websocket: WebSocket, |
| 57 | + Authorize: AuthPASETO = Depends(), |
| 58 | +) -> None: |
| 59 | + """Authorize the websocket using a query parameter fallback.""" |
| 60 | + |
| 61 | + Authorize.paseto_required(location="query") |
| 62 | + await websocket.accept() |
| 63 | + await websocket.send_json({"user": Authorize.get_subject()}) |
| 64 | + await websocket.close() |
0 commit comments