How do you implement JWT authentication in FastAPI?
Answer
FastAPI JWT authentication uses the dependency injection system. 1. Login endpoint: verify credentials, generate token: access_token = jwt.encode({"sub": user.id, "exp": datetime.utcnow() + timedelta(hours=1)}, SECRET_KEY, algorithm="HS256"). 2. Security scheme: oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/auth/token"). 3. Get current user dependency: async def get_current_user(token: str = Depends(oauth2_scheme)): payload = jwt.decode(token, SECRET_KEY, algorithms=["HS256"]); return await get_user(payload["sub"]). 4. Protected route: @app.get("/me") async def me(user: User = Depends(get_current_user)): return user. FastAPI integrates with the OAuth2PasswordBearer scheme to automatically display the Authorize button in Swagger UI, making API testing easy. Use the python-jose or PyJWT library for token encoding/decoding.
Previous
What is Uvicorn and how is it used with FastAPI?
Next
How does SQLAlchemy async work with FastAPI?