Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Here are the steps to integrate Google OAuth with FastAPI:

  1. Go to the Google Cloud Console and create a new project.

  2. On the left-hand menu, select "APIs & Services", then "Dashboard".

  3. Click on "Enable APIs and Services" and search for "Google OAuth API". Click on the result and enable the API.

  4. On the left-hand menu, select "Credentials", then "Create credentials" and select "OAuth client ID".

  5. Select "Web application" as the application type.

  6. Add "http://localhost:8000/callback" as the authorized redirect URI and save.

  7. Take note of the generated client ID and client secret.

  8. Install the google-auth and google-auth-oauthlib packages: pip install google-auth google-auth-oauthlib.

  9. In your FastAPI application, create a new endpoint for the login flow. This endpoint should redirect the user to the Google OAuth consent screen.

from fastapi import FastAPI, Request, Response
from fastapi.responses import RedirectResponse
from google.oauth2 import client

app = FastAPI()

@app.get("/login")
async def login(request: Request):
   flow = client.WebAppFlow.from_client_config(
       {"client_id": CLIENT_ID, "client_secret": CLIENT_SECRET, "redirect_uris": ["http://localhost:8000/callback"]},
       ["https://www.googleapis.com/auth/userinfo.profile", "https://www.googleapis.com/auth/userinfo.email"],
   )
   authorization_url, _ = flow.authorization_url(
       access_type="offline", prompt="consent"
   )
   return RedirectResponse(url=authorization_url)
  1. Create another endpoint for the callback URL that the user will be redirected to after granting access.
@app.get("/callback")
async def callback(request: Request, response: Response, code: str = None, error: str = None):
   if error:
       return {"error": error}
   flow = client.WebAppFlow.from_client_config(
       {"client_id": CLIENT_ID, "client_secret": CLIENT_SECRET, "redirect_uris": ["http://localhost:8000/callback"]},
       ["https://www.googleapis.com/auth/userinfo.profile", "https://www.googleapis.com/auth/userinfo.email"],
   )
   flow.fetch_token(code=code)
   credentials = flow.credentials
   id_info = credentials.id_token["sub"]
   return {"id": id_info}
  1. Test the login flow by navigating to http://localhost:8000/login in your web browser. If everything worked correctly, you should be redirected to the Google OAuth consent screen. After granting access, you should be redirected back to the callback URL and see your Google user ID in the response.