Once a user has obtained an access token, you can use the token to retrieve information about the current user. This is often necessary for displaying user-specific content or enforcing access controls.
Creating a Dependency
To retrieve the current user based on the access token, create a dependency:
Python
from fastapi import Depends, HTTPException
from app.utils import decode_access_token
def get_current_user(request: Request) -> User:
token = request.headers.get("Authorization").split()[1]
data = decode_access_token(token)
user = get_user_by_id(data["sub"])
return user
Using the Dependency in Endpoints
Python
from fastapi import APIRouter, Depends
router = APIRouter()
@router.get("/me")
async def get_current_user(current_user: User = Depends(get_current_user)):
return current_user
Additional Factors
- Token Validation: Ensure that the token is valid and not expired before retrieving the user.
- User Data: Consider storing additional user information in the token payload, such as user roles or preferences.
- Security: Protect against token theft and unauthorized access.
- Performance: If performance is a concern, consider caching user information based on the token.
By following these steps, you can effectively retrieve the current user based on their access token in your FastAPI application. This enables you to implement features that require user-specific information, such as personalized content or restricted access to certain resources.