Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save nakanoasaservice/a698fd679fb545cb2cfe792f0114938c to your computer and use it in GitHub Desktop.

Select an option

Save nakanoasaservice/a698fd679fb545cb2cfe792f0114938c to your computer and use it in GitHub Desktop.
FastAPIでFirebaseのトークンを検証する
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