Securing routes with Firebase Auth access token
See original GitHub issueFirst Check
- I added a very descriptive title to this issue.
- I used the GitHub search to find a similar issue and didn’t find it.
- I searched the FastAPI documentation, with the integrated search.
- I already searched in Google “How to X in FastAPI” and didn’t find any information.
- I already read and followed all the tutorial in the docs and didn’t find an answer.
- I already checked if it is not related to FastAPI but to Pydantic.
- I already checked if it is not related to FastAPI but to Swagger UI.
- I already checked if it is not related to FastAPI but to ReDoc.
Commit to Help
- I commit to help with one of those options 👆
Example Code
from fastapi import FastAPI
app = FastAPI()
firebase_auth = ...?
@app.get("/")
async def root(token: str = Depends(firebase_auth)):
return {"message": "Hello World"}
Description
Prior work & resources
From what I read in the fastAPI docs and tutorials, security is implemented using dependency injections and there are some examples on how to do this where the fastAPI server is both the resource as well as the authentication server.
In Issue #12 I found a mention of the OAuthFlowImplicit
class, which seems about right for my use case. However I do not have enough background knowledge with the involved libraries to solve the issue on my own, so here is my question:
My task
I have a frontend that authenticates with firebase auth and receives an bearer token. This token is then sent to the backend in which for certain routes I want to check for both authentication and authorization.
So first I need to extract the token from the header and check if it belongs to a valid user, which can be done using the firebase_admin library:
firebase_auth.verify_id_token(access_token)
Then I need to get the custom claims and search compare them with a list of authorized claims:
firebase_admin.auth.UserRecord.custom_claims.any(...)
How do I create appropriate dependency injection functions in order to perform these checks?
Operating System
Linux
Operating System Details
No response
FastAPI Version
0.75.1
Python Version
3.7 - 3.10
Additional Context
No response
Issue Analytics
- State:
- Created a year ago
- Comments:13 (2 by maintainers)
Top GitHub Comments
I’m sorry, I was running another version that did not have the
HTTPBearer
, hence no button.Now it’s working great, thank you very much 👍
@adriangb I assume that’s the most straight forward way to do it.
Pass a placeholder token so that the HTTBearer does not throw an Exception, then add a parameter
auth_enabled
to the validate_firebase_token method, depending on which we either call the auth service or don’t do anything.Thx 👍