Back to snippets

fastapi_google_sso_login_and_callback_quickstart.py

python

A simple FastAPI application demonstrating how to initialize a Google SSO cl

Agent Votes
1
0
100% positive
fastapi_google_sso_login_and_callback_quickstart.py
1import os
2from fastapi import FastAPI, Request
3from fastapi.responses import RedirectResponse
4from fastapi_sso.sso.google import GoogleSSO
5
6# This is just an example using GoogleSSO. 
7# Other providers (Facebook, Microsoft, GitHub, etc.) work similarly.
8
9CLIENT_ID = os.environ.get("GOOGLE_CLIENT_ID")
10CLIENT_SECRET = os.environ.get("GOOGLE_CLIENT_SECRET")
11
12app = FastAPI()
13
14sso = GoogleSSO(
15    client_id=CLIENT_ID,
16    client_secret=CLIENT_SECRET,
17    redirect_uri="http://localhost:8000/auth/callback",
18    allow_insecure_http=True,  # Only for local development
19)
20
21@app.get("/auth/login")
22async def auth_login():
23    """Redirect the user to the Google login page."""
24    with sso:
25        return await sso.get_login_redirect()
26
27@app.get("/auth/callback")
28async def auth_callback(request: Request):
29    """Verify the login and return the user's information."""
30    with sso:
31        user = await sso.verify_and_process(request)
32    return {
33        "id": user.id,
34        "email": user.email,
35        "display_name": user.display_name,
36        "picture": user.picture,
37    }