Created
June 6, 2020 16:36
-
-
Save nakanoasaservice/a698fd679fb545cb2cfe792f0114938c to your computer and use it in GitHub Desktop.
FastAPIでFirebaseのトークンを検証する
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials | |
| from fastapi import FastAPI, Depends, HTTPException, status | |
| import firebase_admin | |
| from firebase_admin import auth, credentials | |
| app = FastAPI() | |
| cert = credentials.Certificate('path/to/cert.json') | |
| firebase_admin.initialize_app(cert) | |
| def get_current_user(cred: HTTPAuthorizationCredentials = Depends(HTTPBearer())): | |
| try: | |
| decoded_token = auth.verify_id_token(cred.credentials) | |
| except: | |
| raise HTTPException( | |
| status_code=status.HTTP_401_UNAUTHORIZED, | |
| detail='Invalid authentication credentials', | |
| headers={'WWW-Authenticate': 'Bearer'}, | |
| ) | |
| user = decoded_token['firebase']['identities'] | |
| return user | |
| @app.get('/') | |
| async def homepage(current_user=Depends(get_current_user)): | |
| return {'msg': 'ok', 'user': current_user} | |
| if __name__ == '__main__': | |
| import uvicorn | |
| uvicorn.run(app, host='localhost', port=5000) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment