1 | initial version |
Here are the steps to integrate Google OAuth with FastAPI:
Go to the Google Cloud Console and create a new project.
On the left-hand menu, select "APIs & Services", then "Dashboard".
Click on "Enable APIs and Services" and search for "Google OAuth API". Click on the result and enable the API.
On the left-hand menu, select "Credentials", then "Create credentials" and select "OAuth client ID".
Select "Web application" as the application type.
Add "http://localhost:8000/callback" as the authorized redirect URI and save.
Take note of the generated client ID and client secret.
Install the google-auth
and google-auth-oauthlib
packages: pip install google-auth google-auth-oauthlib
.
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)
@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}