I’m building my first web application with FastAPI. I already have JWT authentication working for my API endpoints, but now I’m confused about how to protect my frontend pages.
For my API routes, I use this security setup:
active_user: User = Security(get_current_user, scopes=["read_access"])
But for my web page routes, I’m not sure how to add the same protection:
@products_router.get("/products", tags=["pages"])
async def show_products(request: Request, count: int = 20):
products_data = DB.products.find()
product_list = await products_data.to_list(length=count)
product_list = list(map(format_product_data, product_list))
return templates.TemplateResponse("products.html", {"request": request, "products": product_list})
How do I make sure only users with valid JWT tokens can access my web pages? Should I check the token in the same way as API endpoints or is there a different approach for frontend routes?
yeah, just add active_user: User = Security(get_current_user, scopes=["read_access"])
to your show_products function. fastapi will throw a 401 if the token’s bad instead of rendering the template. works perfectly for protecting pages.
I’ve dealt with this exact issue in my FastAPI projects. The main difference between API and web routes is how you handle auth failures - web pages need redirects to login, not JSON errors. I built a custom dependency that looks for JWT tokens in cookies and automatically redirects unauthenticated users to the login page. Just modify your existing get_current_user
function to detect if the request wants HTML or JSON, then either redirect or raise HTTPException. This keeps your auth logic consistent while giving users the right experience whether they’re hitting web pages or API endpoints.
interesting question! where are you storing the jwt token - cookies or localStorage? that’ll change how you handle auth in your template routes. also, what happens when users aren’t authenticated - do they get redirected to login or just see an error? need to know more about your frontend setup to help out.