Bigger Applications
Because fastapi-jwt-auth configure your setting via class state that applies across all instances of the class. You need to make sure to call load_config(callback) above from your endpoint. Thanks to FastAPI
when you make endpoint from APIRouter
it will actually work as if everything was the same single app.
So you only need to define load_config(callback) where Fastapi
instance created or you can import it where you included all the router.
An example file structure¶
Let's say you have a file structure like this:
.
├── multiple_files
│ ├── __init__.py
│ ├── app.py
│ └── routers
│ ├── __init__.py
│ ├── items.py
│ └── users.py
Here an example of app.py
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from pydantic import BaseModel
from routers import items, users
from async_fastapi_jwt_auth import AuthJWT
from async_fastapi_jwt_auth.exceptions import AuthJWTException
app = FastAPI()
class Settings(BaseModel):
authjwt_secret_key: str = "secret"
@AuthJWT.load_config
def get_config():
return Settings()
@app.exception_handler(AuthJWTException)
def authjwt_exception_handler(request: Request, exc: AuthJWTException):
return JSONResponse(status_code=exc.status_code, content={"detail": exc.message})
app.include_router(users.router, tags=["users"])
app.include_router(items.router, tags=["items"])
Here an example of users.py
from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel
from async_fastapi_jwt_auth import AuthJWT
from async_fastapi_jwt_auth.auth_jwt import AuthJWTBearer
class User(BaseModel):
username: str
password: str
router = APIRouter()
auth_dep = AuthJWTBearer()
@router.post("/login")
async def login(user: User, authorize: AuthJWT = Depends(auth_dep)):
if user.username != "test" or user.password != "test":
raise HTTPException(status_code=401, detail="Bad username or password")
access_token = await authorize.create_access_token(subject=user.username)
return {"access_token": access_token}
Here an example of items.py
from fastapi import APIRouter, Depends
from async_fastapi_jwt_auth import AuthJWT
from async_fastapi_jwt_auth.auth_jwt import AuthJWTBearer
router = APIRouter()
auth_dep = AuthJWTBearer()
@router.get("/items")
async def items(authorize: AuthJWT = Depends(auth_dep)):
await authorize.jwt_required()
items = ["item1", "item2", "item3"]
return {"items": items}