FastAPI SSO Integration

0.21.0 · active · verified Sat Apr 11

fastapi-sso is a FastAPI plugin designed to simplify integration of Single Sign-On (SSO) with common providers like Google, Facebook, Microsoft, and many others. It streamlines the OAuth2/OpenID Connect flow for authentication. The library is actively maintained with frequent minor and patch releases, currently at version 0.21.0.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates setting up Google SSO. Ensure you register your application with Google Cloud Console to obtain a client ID and secret, and configure the authorized redirect URI to match `http://localhost:8000/auth/google/callback`. For production, ensure `allow_insecure_http` is `False` and `REDIRECT_URI` uses HTTPS. Environment variables are the recommended way to manage credentials.

import os
from fastapi import FastAPI
from fastapi_sso.sso.google import GoogleSSO

app = FastAPI()

GOOGLE_CLIENT_ID = os.environ.get('GOOGLE_CLIENT_ID', 'YOUR_GOOGLE_CLIENT_ID')
GOOGLE_CLIENT_SECRET = os.environ.get('GOOGLE_CLIENT_SECRET', 'YOUR_GOOGLE_CLIENT_SECRET')
REDIRECT_URI = os.environ.get('GOOGLE_REDIRECT_URI', 'http://localhost:8000/auth/google/callback')

google_sso = GoogleSSO(
    GOOGLE_CLIENT_ID,
    GOOGLE_CLIENT_SECRET,
    REDIRECT_URI,
    allow_insecure_http=True # For localhost development
)

@app.get("/auth/google/login")
async def google_login():
    return await google_sso.get_login_redirect()

@app.get("/auth/google/callback")
async def google_callback():
    try:
        user = await google_sso.verify_and_process_token(request=app.request)
        return {"email": user.email, "display_name": user.display_name, "provider": user.provider}
    except Exception as e:
        return {"error": str(e)}

# To run:
# 1. Set GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET, GOOGLE_REDIRECT_URI in your environment
# 2. Configure Google OAuth credentials with Redirect URI: http://localhost:8000/auth/google/callback
# 3. uvicorn your_module:app --reload
# 4. Access http://localhost:8000/auth/google/login in your browser

view raw JSON →