This article explains how to enforce user authentication in FastAPI to protect routes for creating, deleting, and updating posts.
In this article, we complete the authentication setup for our FastAPI application by enforcing that users must be authenticated before creating, deleting, or updating posts. Without this protection, any client could call our endpoints and perform operations without logging in.For example, the following JSON payload demonstrates how a post can be created without any authentication:
Without user authentication, anyone can create, delete, or modify posts. Depending on your application’s design—for instance, a Twitter-like platform where everyone can view tweets but only the owner can modify them—you might want to restrict certain operations to authenticated users only.Below, we explain how to enforce user authentication before allowing a post to be created.
Enforcing Authentication on the Create Post Endpoint
We start by modifying our POST API endpoint for creating posts. In our router file (post.py), we import the necessary modules including the OAuth2 functionality:
The dependency user_id: int = Depends(oauth2.get_current_user) ensures that the endpoint only proceeds if the user is authenticated. If the token is missing or invalid, an error is raised and the post is not created.
The function get_current_user extracts the token provided by the user and calls the helper function verify_access_token to decode and validate it. The implementation is as follows:
The verify_access_token function decodes the token using our secret key and algorithm, extracts the user ID from the payload, and validates that the ID is present:
Copy
Ask AI
def verify_access_token(token: str, credentials_exception): try: payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) id: str = payload.get("user_id") if id is None: raise credentials_exception token_data = schemas.TokenData(id=id) except JWTError: raise credentials_exception return token_data
If the token does not include a valid user ID or if an error occurs during decoding, the request fails with an HTTP 401 error.
When you send a POST request to create a post without a valid token, you will receive an error similar to:
Copy
Ask AI
{ "detail": "Not authenticated"}
To create a post successfully, first obtain a token via the login route then include it in your request header. For example, after obtaining a token from the login endpoint, you might receive a response like:
In Postman, you can also select the Bearer Token option under the Authorization tab and paste your token. This ensures that the token is correctly sent in the request header.
You can enforce authentication on other endpoints by adding the current user dependency. Below are examples for fetching an individual post and deleting a post.
@router.get("/{id}", response_model=schemas.Post)def get_post( id: int, db: Session = Depends(get_db), user_id: int = Depends(oauth2.get_current_user)): post = db.query(models.Post).filter(models.Post.id == id).first() if not post: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail=f"Post with id: {id} does not exist" ) return post
In the authentication router (auth.py), a token schema is used as the response model. This ensures that when a user logs in, the returned response contains exactly the fields defined in our token schema. Make sure the attribute names and capitalization match the schema definitions.
After securing your endpoints, consider testing these common scenarios:
Scenario
Expected Outcome
GET /posts
Unauthorized request returns a 401 error with “Not authenticated”.
GET /posts/
Requires a valid token to fetch a specific post.
DELETE /posts/
Deleting without proper authentication returns a not found or unauthorized error.
PUT /posts/
Updating a post without the Bearer token returns “Not authenticated”.
Always include a valid token in your requests for protected endpoints to ensure proper access control.
This concludes our guide on protecting routes using authentication in FastAPI. By enforcing these measures, your API will only allow authenticated users to perform sensitive actions such as creating, updating, and deleting posts.