### Installing FastAPI SSO with Poetry Source: https://github.com/tomasvotava/fastapi-sso/blob/master/docs/how-to-guides/00-installation.md This snippet demonstrates how to install the `fastapi-sso` library using the `poetry` package manager. It adds the library as a dependency to your project's `pyproject.toml` file and installs it. ```console poetry add fastapi-sso ``` -------------------------------- ### Installing FastAPI SSO with Pip Source: https://github.com/tomasvotava/fastapi-sso/blob/master/docs/how-to-guides/00-installation.md This snippet demonstrates how to install the `fastapi-sso` library using the `pip` package installer. It downloads and installs the package into your current Python environment. ```console pip install fastapi-sso ``` -------------------------------- ### Running Google SSO Example via Console Source: https://github.com/tomasvotava/fastapi-sso/blob/master/examples/README.md This console command demonstrates how to run the Google SSO example. It requires `CLIENT_ID` and `CLIENT_SECRET` environment variables to be set before execution, which are crucial for authentication with Google. The command then executes the `google.py` script located in the `examples` directory. ```console CLIENT_ID="client-id" CLIENT_SECRET="client-secret" python examples/google.py ``` -------------------------------- ### Installing Pre-commit Hooks (Console) Source: https://github.com/tomasvotava/fastapi-sso/blob/master/docs/contributing.md This command installs `pre-commit` hooks into the local Git repository. These hooks automatically run code quality checks (formatting, linting, typechecking) before each commit, ensuring code standards are met. ```console $ poe pre-commit install ``` -------------------------------- ### Installing Pre-commit Hooks (Console) Source: https://github.com/tomasvotava/fastapi-sso/blob/master/CONTRIBUTING.md This command installs `pre-commit` hooks into the local Git repository. These hooks automatically run code quality checks (formatting, linting, type-checking) before each commit, ensuring adherence to project standards. ```console $ poe pre-commit install pre-commit installed at .git/hooks/pre-commit ``` -------------------------------- ### Installing FastAPI SSO with pip Source: https://github.com/tomasvotava/fastapi-sso/blob/master/README.md This command installs the `fastapi-sso` library using pip, the standard package installer for Python. It fetches the latest version of the library from PyPI and makes it available in your Python environment. ```console pip install fastapi-sso ``` -------------------------------- ### Implementing Google SSO with FastAPI (Minimal Example) Source: https://github.com/tomasvotava/fastapi-sso/blob/master/docs/tutorials.md This snippet demonstrates a basic integration of Google OAuth2 with FastAPI using `fastapi-sso`. It initializes `GoogleSSO` with client credentials and a redirect URI, then defines two endpoints: `/google/login` for initiating the OAuth flow and `/google/callback` for processing the user's data after successful authentication. It requires a pre-configured Google OAuth2 client. ```Python from fastapi import FastAPI from starlette.requests import Request from fastapi_sso.sso.google import GoogleSSO app = FastAPI() CLIENT_ID = "your-google-client-id" # <-- paste your client id here CLIENT_SECRET = "your-google-client-secret" # <-- paste your client secret here google_sso = GoogleSSO(CLIENT_ID, CLIENT_SECRET, "http://localhost:3000/google/callback") @app.get("/google/login") async def google_login(): async with google_sso: return await google_sso.get_login_redirect() @app.get("/google/callback") async def google_callback(request: Request): async with google_sso: user = await google_sso.verify_and_process(request) return user ``` -------------------------------- ### Installing FastAPI SSO with Poetry Source: https://github.com/tomasvotava/fastapi-sso/blob/master/README.md This command adds the `fastapi-sso` library as a dependency to your project using Poetry, a dependency management and packaging tool for Python. Poetry automatically manages virtual environments and updates your `pyproject.toml` file. ```console poetry add fastapi-sso ``` -------------------------------- ### Using Google SSO as a FastAPI Dependency Source: https://github.com/tomasvotava/fastapi-sso/blob/master/docs/tutorials.md This example shows how to manage the `GoogleSSO` instance as a FastAPI dependency. By defining a `get_google_sso` function, the SSO instance can be injected into multiple route handlers, ensuring proper state management and resource cleanup. This approach is beneficial for reusability and maintaining a clean application structure. ```Python from fastapi import Depends, FastAPI, Request from fastapi_sso.sso.google import GoogleSSO app = FastAPI() CLIENT_ID = "your-google-client-id" # <-- paste your client id here CLIENT_SECRET = "your-google-client-secret" # <-- paste your client secret here def get_google_sso() -> GoogleSSO: return GoogleSSO(CLIENT_ID, CLIENT_SECRET, redirect_uri="http://localhost:3000/google/callback") @app.get("/google/login") async def google_login(google_sso: GoogleSSO = Depends(get_google_sso)): return await google_sso.get_login_redirect() @app.get("/google/callback") async def google_callback(request: Request, google_sso: GoogleSSO = Depends(get_google_sso)): user = await google_sso.verify_and_process(request) return user ``` -------------------------------- ### Dynamically Generating Google SSO Login URL in FastAPI Source: https://github.com/tomasvotava/fastapi-sso/blob/master/docs/how-to-guides/redirect-uri-request-time.md This snippet demonstrates how to initialize `GoogleSSO` without a `redirect_uri` and then dynamically generate the login URL using `request.url_for` within a FastAPI endpoint. It shows the setup for both the login redirect and the callback endpoint, highlighting how the `redirect_uri` is passed at the time of the `get_login_redirect` call. ```Python # ... other imports and code ... google_sso = GoogleSSO("my-client-id", "my-client-secret") @app.get("/google/login") async def google_login(request: Request): """Dynamically generate login url and return redirect""" async with google_sso: return await google_sso.get_login_redirect(redirect_uri=request.url_for("google_callback")) @app.get("/google/callback") async def google_callback(request: Request): # ... handle callback ... ``` -------------------------------- ### FastAPI Application with Google SSO and JWT Authentication Source: https://github.com/tomasvotava/fastapi-sso/blob/master/docs/how-to-guides/use-with-fastapi-security.md This comprehensive example demonstrates a FastAPI application integrating Google SSO for user authentication. It uses JWTs stored in cookies for session management, protecting endpoints with `fastapi.security.APIKeyCookie` to enable Swagger UI's lock icon. It includes routes for login, logout, OAuth callback processing, and a protected endpoint. ```python import datetime # to calculate expiration of the JWT from fastapi import FastAPI, Depends, HTTPException, Security, Request from fastapi.responses import RedirectResponse from fastapi.security import APIKeyCookie # this is the part that puts the lock icon to the docs from fastapi_sso.sso.google import GoogleSSO # pip install fastapi-sso from fastapi_sso.sso.base import OpenID from jose import jwt # pip install python-jose[cryptography] SECRET_KEY = "this-is-very-secret" # used to sign JWTs, make sure it is really secret CLIENT_ID = "your-client-id" # your Google OAuth2 client ID CLIENT_SECRET = "your-client-secret" # your Google OAuth2 client secret sso = GoogleSSO(client_id=CLIENT_ID, client_secret=CLIENT_SECRET, redirect_uri="http://127.0.0.1:5000/auth/callback") app = FastAPI() async def get_logged_user(cookie: str = Security(APIKeyCookie(name="token"))) -> OpenID: """Get user's JWT stored in cookie 'token', parse it and return the user's OpenID.""" try: claims = jwt.decode(cookie, key=SECRET_KEY, algorithms=["HS256"]) return OpenID(**claims["pld"]) except Exception as error: raise HTTPException(status_code=401, detail="Invalid authentication credentials") from error @app.get("/protected") async def protected_endpoint(user: OpenID = Depends(get_logged_user)): """This endpoint will say hello to the logged user. If the user is not logged, it will return a 401 error from `get_logged_user`.""" return { "message": f"You are very welcome, {user.email}!", } @app.get("/auth/login") async def login(): """Redirect the user to the Google login page.""" async with sso: return await sso.get_login_redirect() @app.get("/auth/logout") async def logout(): """Forget the user's session.""" response = RedirectResponse(url="/protected") response.delete_cookie(key="token") return response @app.get("/auth/callback") async def login_callback(request: Request): """Process login and redirect the user to the protected endpoint.""" async with sso: openid = await sso.verify_and_process(request) if not openid: raise HTTPException(status_code=401, detail="Authentication failed") # Create a JWT with the user's OpenID expiration = datetime.datetime.now(tz=datetime.timezone.utc) + datetime.timedelta(days=1) token = jwt.encode({"pld": openid.dict(), "exp": expiration, "sub": openid.id}, key=SECRET_KEY, algorithm="HS256") response = RedirectResponse(url="/protected") response.set_cookie( key="token", value=token, expires=expiration ) # This cookie will make sure /protected knows the user return response if __name__ == "__main__": import uvicorn uvicorn.run(app, host="127.0.0.1", port=5000) ``` -------------------------------- ### Running Pytest Tests (Console) Source: https://github.com/tomasvotava/fastapi-sso/blob/master/docs/contributing.md This command executes the project's test suite using `pytest` via `poe`. It runs all defined tests to verify the functionality and correctness of the codebase. ```console poe test ``` -------------------------------- ### Linting Code with Ruff (Console) Source: https://github.com/tomasvotava/fastapi-sso/blob/master/docs/contributing.md This command runs the `ruff` linter via `poe` to check the `fastapi_sso` codebase for potential issues and style violations. It helps maintain code quality and adherence to configured linting rules. ```console $ poe ruff ``` -------------------------------- ### Formatting Code with Black (Console) Source: https://github.com/tomasvotava/fastapi-sso/blob/master/docs/contributing.md This command executes the `black` formatter using `poe` to reformat Python code according to the project's specified `line_length` of 120 characters. It ensures consistent code style across the repository. ```console $ poe black ``` -------------------------------- ### Initializing GoogleSSO with Insecure HTTP (Python) Source: https://github.com/tomasvotava/fastapi-sso/blob/master/docs/how-to-guides/http-development.md This Python snippet demonstrates how to initialize the GoogleSSO class from fastapi_sso while explicitly allowing insecure HTTP connections. It sets the OAUTHLIB_INSECURE_TRANSPORT environment variable and passes 'allow_insecure_http=True' to the constructor, enabling testing on 'localhost' without HTTPS. ```python import os from fastapi_sso.sso.google import GoogleSSO os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1" google_sso = GoogleSSO("client-id", "client-secret", allow_insecure_http=True) ``` -------------------------------- ### Running Tests with Pytest (Console) Source: https://github.com/tomasvotava/fastapi-sso/blob/master/CONTRIBUTING.md This command executes the project's test suite using `pytest` via `poe`. Contributors are encouraged to provide tests for new code to ensure functionality and prevent regressions. ```console poe test ``` -------------------------------- ### Configuring Google SSO Login with Additional Parameters (Python) Source: https://github.com/tomasvotava/fastapi-sso/blob/master/docs/how-to-guides/additional-query-params.md This Python snippet demonstrates how to initiate a Google OAuth login flow using 'fastapi-sso', passing extra query parameters like 'prompt=consent' and 'access_type=offline' to ensure a refresh token is returned. It also includes the corresponding callback endpoint for processing the authenticated user. ```Python # ... other imports and code ... @app.get("/google/login") async def google_login(request: Request): async with google_sso: return await google_sso.get_login_redirect( redirect_uri=request.url_for("google_callback"), params={"prompt": "consent", "access_type": "offline"} ) @app.get("/google/callback") async def google_callback(request: Request): async with google_sso: user = await google_sso.verify_and_process(request) # you may now use google_sso.refresh_token to refresh the access token ``` -------------------------------- ### Using Asynchronous SSO Context Manager (Recommended) in Python Source: https://github.com/tomasvotava/fastapi-sso/blob/master/README.md This snippet illustrates the recommended asynchronous `async with` context manager for the FastAPI SSO instance. It is crucial for preventing race conditions during concurrent login requests and ensures proper handling of asynchronous operations. Users must update their code to use this pattern with version `0.16.0` or later. ```Python # After (recommended) async with sso: openid = await sso.verify_and_process(request) ``` -------------------------------- ### Typechecking Code with MyPy (Console) Source: https://github.com/tomasvotava/fastapi-sso/blob/master/docs/contributing.md This command executes `mypy` through `poe` to perform static type checking on the project's source files. It verifies type annotations and helps catch type-related errors before runtime. ```console $ poe mypy ``` -------------------------------- ### Formatting Code with Black (Console) Source: https://github.com/tomasvotava/fastapi-sso/blob/master/CONTRIBUTING.md This command uses `poe` to run the `black` formatter across the project. It ensures code adheres to the defined formatting standards, specifically a line length of 120 characters, as configured in `pyproject.toml`. ```console $ poe black All done! ✨ 🍰 ✨ 13 files left unchanged. ``` -------------------------------- ### Requesting Additional Google Scopes with FastAPI-SSO Source: https://github.com/tomasvotava/fastapi-sso/blob/master/docs/how-to-guides/additional-scopes.md This snippet illustrates how to initialize `GoogleSSO` by specifying an array of desired scopes, including standard ones like 'openid' and 'email', along with specific Google API scopes like 'https://www.googleapis.com/auth/calendar'. It then shows how to use the `sso.access_token` obtained after successful verification to make authenticated requests to Google APIs, such as fetching the user's calendar list. ```python sso = GoogleSSO(client_id="client-id", client_secret="client-secret", scope=["openid", "email", "https://www.googleapis.com/auth/calendar"]) @app.get("/google/login") async def google_login(): async with sso: return await sso.get_login_redirect(redirect_uri=request.url_for("google_callback")) @app.get("/google/callback") async def google_callback(request: Request): async with sso: await sso.verify_and_process(request) # you may now use sso.access_token to access user's Google calendar async with httpx.AsyncClient() as client: response = await client.get( "https://www.googleapis.com/calendar/v3/users/me/calendarList", headers={"Authorization": f"Bearer {sso.access_token}"} ) return response.json() ``` -------------------------------- ### Linting Code with Ruff (Console) Source: https://github.com/tomasvotava/fastapi-sso/blob/master/CONTRIBUTING.md This command executes `ruff` via `poe` to perform linting checks on the `fastapi_sso` codebase. It verifies code quality against the rules defined in `pyproject.toml`, helping to identify and fix potential issues. ```console $ poe ruff Poe => ruff check fastapi_sso All checks passed! ``` -------------------------------- ### Implementing Google SSO Login and Callback with State in FastAPI Source: https://github.com/tomasvotava/fastapi-sso/blob/master/docs/how-to-guides/state-return-url.md This snippet demonstrates how to integrate Google SSO into a FastAPI application, using the 'state' parameter to handle post-authentication redirects. It shows how to pass a 'return_url' during the login redirect and then utilize it in the callback function to redirect the user to their intended destination after successful verification. ```python from fastapi import Request from fastapi.responses import RedirectResponse google_sso = GoogleSSO("client-id", "client-secret") # E.g. https://example.com/auth/login?return_url=https://example.com/welcome async def google_login(return_url: str): async with google_sso: # Send return_url to Google as a state so that Google knows to return it back to us return await google_sso.get_login_redirect(redirect_uri=request.url_for("google_callback"), state=return_url) async def google_callback(request: Request, state: str | None = None): async with google_sso: user = await google_sso.verify_and_process(request) if state is not None: return RedirectResponse(state) else: return user ``` -------------------------------- ### Typechecking Code with MyPy (Console) Source: https://github.com/tomasvotava/fastapi-sso/blob/master/CONTRIBUTING.md This command runs `mypy` through `poe` to perform static type checks on the project's source files. It ensures type consistency and helps catch type-related errors before runtime. ```console $ poe mypy Success: no issues found in 13 source files ``` -------------------------------- ### Using Synchronous SSO Context Manager (Deprecated) in Python Source: https://github.com/tomasvotava/fastapi-sso/blob/master/README.md This snippet demonstrates the deprecated synchronous `with` context manager for the FastAPI SSO instance. It shows how `sso.verify_and_process(request)` was previously called within this context. This method is no longer recommended due to a race condition bug and will be removed in future versions. ```Python # Before (deprecated) with sso: openid = await sso.verify_and_process(request) ``` -------------------------------- ### Successful Protected Endpoint Access Response (JSON) Source: https://github.com/tomasvotava/fastapi-sso/blob/master/docs/how-to-guides/use-with-fastapi-security.md This JSON snippet represents the expected response from the `/protected` endpoint after a user has successfully authenticated via Google SSO. It confirms the user's access with a personalized welcome message. ```json { "message": "You are very welcome, ijustfarted@example.com" } ``` -------------------------------- ### Setting OAUTHLIB_INSECURE_TRANSPORT Environment Variable (Bash) Source: https://github.com/tomasvotava/fastapi-sso/blob/master/docs/how-to-guides/http-development.md This snippet shows how to set the OAUTHLIB_INSECURE_TRANSPORT environment variable to '1' in a Bash shell. This is necessary for allowing insecure HTTP connections, typically for local development and testing, when 'allow_insecure_http' is not automatically handled by FastAPI-SSO versions prior to 0.9.0 or when explicitly needed. ```bash OAUTHLIB_INSECURE_TRANSPORT=1 ``` -------------------------------- ### FastAPI Authentication Error Response Source: https://github.com/tomasvotava/fastapi-sso/blob/master/docs/how-to-guides/use-with-fastapi-security.md This JSON snippet shows the expected error response from a FastAPI endpoint when a user attempts to access a protected resource without valid authentication credentials, typically a 401 Unauthorized error. ```json { "detail": "Not authenticated" } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.