First, let’s clarify some terms involved in this process:
- Audience: Typically a URI or a unique identifier for the API or resource server the client aims to access. It’s utilized to ensure that an access token is presented to the correct resource server, which verifies the audience value matches its identifier.
- Client ID and Client Secret: Credentials provided by the authorization server (e.g., Auth0) to the client. These are used by the client to authenticate itself to the authorization server when requesting a token.
- Access Token: The token presented by the client to the resource server (API) as proof of authorization to access resources on behalf of the user or itself, in machine-to-machine communication.
How to Set Up Auth0 to Secure a FastAPI Application
On the Auth0 Provider Site
To protect our resource (the API), the following steps are necessary:
- Resource Setup:
- Set up a resource with a unique name, which could be your API name or project name. This distinct name allows the Auth0 provider to differentiate among the various resources that need protection. In Auth0 context, this resource is also referred to as the audience.
- Client Configuration:
- For every potential user that will call your API (referred to as a client), create a client in Auth0 that will have access to the resource you’ve set up. This includes obtaining a Client ID and a Client Secret.
Using the Client ID and Secret in Your App
With these credentials (Client ID and secrets):
- When clients wish to call your API, they first request a JWT token (bearer token) from the Auth0 domain by providing the Client ID, Client Secret, and the audience (resource name).
Here’s an example in Python:
import requests |
- With this token, which typically has a limited lifetime of a few hours, the client can then authenticate and make calls to your API.
Validating the Access Token on the FastAPI Side
To validate incoming tokens, follow these steps:
- Fetch the public key from the Auth0 provider page and use the RSA256 algorithm to verify if the token from the user is valid.
Here’s how to validate tokens in Python:
pip install pyjwt[crypto] requests |
That concludes the setup to secure a FastAPI application with Auth0.
```
This guidance provides a structured approach for integrating Auth0 authentication into a FastAPI app, highlighting the necessary steps and providing code snippets for practical implementation.