This Python code sample demonstrates how to implement authorization in a FastAPI server using Auth0.
Hi, developers.
I’m was following the developers documentation on Auth0 for FastAPI but I wasn’t able to clone it. because it was asking for username and password. And I searched this repo on GitHub of Auth0 but this repo wasn’t there.
So, I guess the repo is private for now. But if you can make it public just let us know.
Hello, Sachin! Welcome to the Auth0 Community.
I apologize about that. The repo was left private but it’s not public Please let us know if you have any questions on the code. Thanks for the heads up!
Hi developers, thanks to you I was able to integrate my FastAPI with Auth0.
But now I have come up with a different issue.
I have used the sample template provided by Auth0 for my FastAPI and Angular Integration to test it. But when I used it in my FastAPI and Angular code it is throwing
Access to XMLHttpRequest at ‘http://localhost:6060/robots/’ from origin ‘http://localhost:4040’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource
GET http://localhost:6060/robots/ net::ERR_FAILED 500 (Internal Server Error)
I tried to log it then I found this
- {
data: null
error: {message: ‘Http failure response for http://localhost:6060/robots/: 0
Unknown Error’}
}*
Here is a Sample code of my FastAPI and Angular.
app.module.ts
imports: [
....
AuthModule.forRoot({
...environment.auth0,
httpInterceptor: {
allowedList: [`${environment.api.serverUrl}/robots/`]
},
}),
.....
],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: AuthHttpInterceptor,
multi: true,
},
],
environment.ts
export const environment = {
production: false,
auth0: {
domain: 'xxx',
clientId: 'xxx',
authorizationParams: {
audience: 'https://hello-world.example.com',
redirect_uri: 'http://localhost:4040',
},
errorPath: '',
},
api: {
serverUrl: 'http://localhost:6060',
},
};
robot.service.ts
getAllRobotsRestricted = (): Observable<ApiResponseModel> => {
const config: RequestConfigModel = {
url: `${env.api.serverUrl}/robots/`,
method: 'GET',
headers: {
'content-type': 'application/json',
},
};
return this.externalAuth0Service.callExternalApi(config).pipe(
mergeMap((response) => {
const { data, error } = response;
return of({
data: data ? (data as RobotsModel) : null,
error,
});
})
);
}
external api
callExternalApi = (config: RequestConfigModel): Observable<ApiResponseModel> => {
return this.http
.request<unknown>(config.method, config.url, config.headers)
.pipe(
mergeMap((data) => {
return of({
data: data,
error: null,
});
}),
catchError((err) => {
if (err.error && err.status) {
return of({
data: null,
error: err.error,
});
}
return of({
data: null,
error: {
message: err.message,
},
});
})
);
};
So, can you help me with this?
Hi, @imsachinsingh10 I’m happy to hear that this code sample has helped you to integrate your FastAPI application with Auth0.
This error is related to how you set up CORS in your FastAPI application. FastAPI is restrictive by default, so you’ll need to explicitly enable particular origins, methods, or headers so browsers can be permitted to use them in a Cross-Domain context.
For example, in our case, the client applications, such as the Angular application, are running on http://localhost:4040, so we’ve explicitly enabled the FastAPI server to allow requests from the http://localhost:4040 origin by doing the following in the main.py
file:
from fastapi.middleware.cors import CORSMiddleware
...
app = FastAPI(openapi_url=None)
...
app.add_middleware(
CORSMiddleware,
allow_origins=[settings.client_origin_url],
allow_methods=["GET"],
allow_headers=["Authorization", "Content-Type"],
max_age=86400,
)
Notice that our FastAPI code sample reads the settings.client_origin_url
value from an environment variable. You can leverage this example, pass the allowed origin directly, and adjust it to your needs. For more information on how you can configure CORS in FastAPI, you can check the official documentation:
To understand how CORS works here is an excellent blog post from Auth0 that you can also read What is CORS? Complete Tutorial on Cross-Origin Resource Sharing.
Thank you so much for your response but I figured out the problem. Now it is working perfectly fine .
It was a minor issue from my side that I forgot to install one of the libraries Cryptography which is required along with other dependencies like PyJWT , secure.
So, if anyone faces the similar issue then they can keep a check of requirement.txt files as well.
Thanks!
Thanks for sharing it with the rest of community!