FastAPI SSO Integration
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
- breaking Python 3.9 support was removed in version 0.21.0. Python 3.8 support was removed in version 0.18.0.
- breaking A critical OAuth login CSRF vulnerability due to missing `state` validation was fixed in version 0.19.0. This is a security-critical update.
- gotcha The `redirect_uri` configured in your FastAPI-SSO instance MUST exactly match the authorized redirect URI set in your OAuth provider's developer console (e.g., Google Cloud Console). Mismatches will cause authentication failures.
- gotcha When developing locally, ensure `allow_insecure_http=True` is set for providers if you are using `http://localhost`. Remember to set this to `False` in production environments for security.
Install
-
pip install fastapi-sso -
pip install 'fastapi-sso[google]' # for Google provider
Imports
- GoogleSSO
from fastapi_sso.sso.google import GoogleSSO
- FacebookSSO
from fastapi_sso.sso.facebook import FacebookSSO
- OpenID
from fastapi_sso.sso import OpenID
Quickstart
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