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:
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.
Verifying the Token
The functionget_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:
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:
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.
Testing the Protected Endpoint
When you send a POST request to create a post without a valid token, you will receive an error similar to:Protecting Other Routes
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.Getting an Individual Post
Deleting a Post
Setting Up the Login Endpoint
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.
Testing All Routes
After securing your endpoints, consider testing these common scenarios: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.