FastAPI and Frontend Integration: User Authentication Best Practices

Hey folks! I’m new to frontend development and could use some help. I’ve got a FastAPI backend with JWT authentication set up for my API endpoints. It’s working great!

Now I’m adding a frontend and I’m not sure how to handle user auth for web pages. Here’s what I’ve got so far:

@app.get('/users')
async def users_page(request: Request, max_users: int = 10):
    user_data = await db.users.find().limit(max_users).to_list()
    cleaned_users = [clean_user_info(u) for u in user_data]
    return templates.TemplateResponse('users.html', {'request': request, 'users': cleaned_users})

How do I make sure only logged-in users with valid tokens can access this page? Should I be handling this differently for web pages vs API endpoints? Any tips or best practices would be super helpful! Thanks in advance!

ooh, interesting challenge! have u considered using oauth2 with a provider like google or github? it cud simplify auth for both api and web pages. plus, users dont hav to remember another password. whaddya think bout that approach? any specific features ur looking for in the auth system?

For integrating user authentication, adopting a centralized middleware approach can be very effective. You can create a dependency function that checks the validity of JWT tokens from request headers, and then consistently apply this check across your API and page routes. This way, you ensure that all requests are authenticated without duplicating the logic. Additionally, by including the JWT token with every client request and implementing a token refresh mechanism, you can handle token expiration smoothly and maintain a secure, uniform authentication process.

hey zoestring42! for web pages, you could use session-based auth instead of jwt. implement a login route that sets a session cookie. then use middleware to check the session before rendering pages:

@app.middleware("http")
async def auth_middleware(request: Request, call_next):
    if not request.session.get("user_id"):
        return RedirectResponse("/login")
    return await call_next(request)

this way you don’t need to handle tokens in the frontend. hope this helps!