Registry / auth-security / fastapi-sso

fastapi-sso

JSON →
library0.21.1pypypi✓ verified 29d ago

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.

pip install fastapi-sso
INSTALL
IMPORT
SIG · FASTAPI-SSO
F
fastapi-sso
auth-securitypythonv0.21.1
Install
4.8s avg
Import
1390ms
Disk
37MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.9–3.13
musl
3.9–3.13
Install & Compatibility
Where this runs
tested against v0.21.1 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.10–3.910 runs
installs and imports cleanly · install 0.0s · import 1.420s · 38.6MB
glibc
py 3.10–3.910 runs
installs and imports cleanly · install 4.8s · import 1.360s · 38MB
37MB installed
● package 37MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

GoogleSSO
✓ from fastapi_sso.sso.google import GoogleSSO
FacebookSSO
✓ from fastapi_sso.sso.facebook import FacebookSSO
OpenID
✓ from fastapi_sso.sso import OpenID
✗ from fastapi_sso.openid import OpenID
The OpenID class is directly under `fastapi_sso.sso` for generic OpenID Connect.

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
Debug
Known issues
breakingPython 3.9 support was removed in version 0.21.0. Python 3.8 support was removed in version 0.18.0.
fix
Ensure your project uses Python 3.10 or higher. For version 0.21.0+, Python 3.10+ is required.
affects: >=0.18.0, >=0.21.0
breakingA critical OAuth login CSRF vulnerability due to missing `state` validation was fixed in version 0.19.0. This is a security-critical update.
fix
Upgrade to `fastapi-sso==0.19.0` or higher immediately. Note that future `1.0.0` versions plan to use a server-side state store.
affects: <0.19.0
gotchaThe `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.
fix
Double-check that the `REDIRECT_URI` passed to the SSO provider object (e.g., `GoogleSSO`) precisely matches the URI registered with the third-party OAuth provider, including scheme (http/https), host, port, and path.
affects: all
gotchaWhen 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.
fix
Toggle `allow_insecure_http` based on your environment. Use HTTPS for all production deployments.
affects: all
Errors
Common errors & fixes
KeyError: 'id_token'
This error often occurs when the `id_token` is missing or not structured as expected in the OAuth provider's response, particularly when trying to parse user information after successful authentication. This can be due to incorrect `scope` settings or changes in the provider's response format.
fix
Ensure the required scopes (e.g., 'openid', 'email', 'profile') are requested during SSO initialization. Check the raw `token` object received from the `authorize_access_token` call to understand its structure and adapt the code to correctly extract user information. For `Authlib` users (which `fastapi-sso` builds upon), consider using `userinfo` from the token if `parse_id_token` is problematic. For example: `user_info = token.get('userinfo')` or `user_info = await oauth.provider.userinfo(token=token)` if `id_token` itself is not directly in the top level of the token.
{"error":"invalid_grant", "error_description":"The provided access grant is invalid, expired, or revoked..."}
This error, returned by the OAuth provider, indicates an issue with the authorization code during the token exchange step. Common causes include an expired authorization code (they are usually short-lived), a mismatch between the `redirect_uri` used in the initial authorization request and the token exchange, or incorrect `client_id`/`client_secret` configuration.
fix
Verify that the `redirect_uri` passed to `fastapi-sso` (both in initialization and `get_login_redirect` if provided) exactly matches the one registered with the OAuth provider. Ensure the `client_id` and `client_secret` are correct. Process the authorization code immediately after receiving it to avoid expiration. Also, verify that your server's clock is synchronized.
SessionMiddleware must be installed to access request.session
`fastapi-sso` relies on `Authlib`, which often uses FastAPI's `request.session` to store temporary state (like the OAuth state parameter). This error means that `starlette.middleware.sessions.SessionMiddleware` has not been added to your FastAPI application, or it's misconfigured.
fix
Add `SessionMiddleware` to your FastAPI application with a secure `secret_key`. Example: `app.add_middleware(SessionMiddleware, secret_key='your-super-secret-key-at-least-32-bytes')`. The secret key should be a long, random string.
Error with Redirect URI When Defined in get_login_redirect Using HTTPS with Nginx / The response was received at https://containerip/ instead of https:myserverurl
This problem arises when FastAPI (or `Authlib`/`fastapi-sso`) perceives a different `redirect_uri` than what the OAuth provider sends or what the application is configured for, especially when deployed behind a reverse proxy like Nginx or Docker. The proxy might be rewriting headers or the application isn't correctly configured to trust `X-Forwarded-For` headers, leading to a URL mismatch.
fix
Ensure that your `redirect_uri` in `fastapi-sso` initialization and the OAuth provider's settings explicitly match the *external* URL your users access. When behind a proxy, configure FastAPI to trust proxy headers (e.g., `app = FastAPI(root_path="/subpath")`). You might need to adjust Nginx configurations (e.g., `proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme;`) and potentially use `allow_insecure_http=True` during local development if not using HTTPS.
Upgrade
Version history
0.21.1latest on PyPI · released Jun 22, 2026
Audit
Dependencies
python-multipartoptionalRequired for FastAPI form data handling, often used in callback routes.
httpxrequiredUnderlying HTTP client used by SSO providers.
python-joseoptionalUsed for JWT handling, especially in OpenID Connect flows.
Agent activity
19 hits · last 30 days
node
16
OpenAI (training)
1
Resources
fastapi-sso — pip install fastapi-sso · libregistry