Create a login endpoint to issue JWTs and a protected endpoint that requires a valid token.
Implementing JWT authentication in a web framework like FastAPI involves a few key steps. First, you need an endpoint, typically `/login` or `/token`, where a user can authenticate with their credentials (e.g., username and password). Upon successful verification of credentials, this endpoint generates a JWT containing claims about the user (like their ID and roles) and an expiration time. This token is then returned to the client. Second, the client must store this token securely (e.g., in memory or `localStorage` in a browser) and send it with every subsequent request to protected endpoints. The standard way to send the token is in the `Authorization` header, using the `Bearer` schema: `Authorization: Bearer <your-jwt-here>`. Third, you need to create protected endpoints that require this token. In FastAPI, this is typically done using dependencies. You create a dependency function that extracts the token from the `Authorization` header, decodes it, and verifies its signature and claims (like expiration). If the token is invalid or missing, the dependency raises an `HTTPException`, immediately stopping the request and returning a `401 Unauthorized` error. If the token is valid, the dependency can return the payload (e.g., the user ID), which the protected endpoint can then use to perform its logic. This pattern provides a clean and reusable way to secure multiple routes, ensuring that only authenticated users can access sensitive data or perform privileged actions. This stateless approach is highly scalable, as the server doesn't need to maintain a session store; it just needs to verify the token on each request.