Skip to content

Conversation

@loveyana
Copy link
Contributor

@loveyana loveyana commented Jan 27, 2026

πŸ“‹ Description

Add a comprehensive OAuth2 3-Legged OAuth (3LO) middleware for Starlette-based frameworks with first-class VeIdentity User Pool integration.

✨ Features

Core OAuth2 Functionality

  • OAuth2 Authorization Code Flow - Complete 3LO implementation with automatic token exchange
  • PKCE Support - Enhanced security for public clients via Proof Key for Code Exchange
  • Automatic Token Refresh - Seamlessly refresh tokens before expiration using refresh_token grant
  • Signed Cookie Sessions - HMAC-SHA256 signed cookies with optional encryption for session storage
  • State Parameter Protection - CSRF protection via secure random state with server-side validation

VeIdentity Integration

  • OAuth2Config.from_veidentity() - Simplified configuration requiring only 3 parameters:
    OAuth2Config.from_veidentity(
        user_pool_name="my-app",
        client_name="my-app-web", 
        redirect_uri="https://myapp.com/oauth2/callback",
    )
  • Auto Resource Management - Automatically creates user pool, client, and registers callbacks
  • OIDC Discovery - Supports /.well-known/openid-configuration for endpoint discovery

Framework Support

  • Starlette - Native support for the base ASGI framework
  • FastAPI - Full compatibility (FastAPI extends Starlette)
  • Any Starlette-based framework - Works with frameworks built on Starlette

Production-Ready Features

  • Pluggable State Storage - StateStore Protocol for custom backends (Redis, database)
  • Built-in InMemoryStateStore - Default implementation with TTL and probabilistic pruning
  • API vs Browser Detection - Returns 401 JSON for API requests, redirects for browser requests
  • HTTP Connection Pooling - Configurable httpx client with connection limits
  • Cookie Size Warnings - Alerts when session cookies approach browser limits

πŸš€ Quick Start

from fastapi import FastAPI
from veadk.auth.middleware.oauth2_auth import OAuth2Config, setup_oauth2

app = FastAPI()

handler = setup_oauth2(
    app,
    OAuth2Config.from_veidentity(
        user_pool_name="my-app",
        client_name="my-app-web",
        redirect_uri="https://myapp.com/oauth2/callback",
    ),
)

@app.get("/")
async def home(request: Request):
    session = handler.get_session(request)
    return {"user": session.user_id}

πŸ“ Files Changed

File Description
veadk/auth/middleware/oauth2_auth.py Main OAuth2 middleware implementation

πŸ”§ Configuration Options

Category Options
OAuth2 authorize_url, token_url, client_id, client_secret, scope, use_pkce
Session session_cookie_name, session_timeout_seconds, cookie_secure, cookie_samesite
Token Refresh token_refresh_threshold_seconds, auto_refresh_token
HTTP Client http_timeout_seconds, http_max_connections, http_max_keepalive_connections
API Behavior api_path_prefixes (paths that return 401 instead of redirect)

πŸ”’ Security Features

  • βœ… PKCE (Proof Key for Code Exchange)
  • βœ… State parameter CSRF protection
  • βœ… HMAC-SHA256 cookie signing
  • βœ… Constant-time signature comparison
  • βœ… Secure redirect validation (prevents open redirect)
  • βœ… Cookie security attributes (Secure, HttpOnly, SameSite)

πŸ“– Related Documentation

Introduced veadk.auth.middleware.oauth2_auth.py, providing OAuth2 3LO middleware for Starlette/FastAPI with VeIdentity integration, including session management, PKCE, and extensible state storage. Updated inbound authentication documentation to detail both API Gateway and middleware OAuth2 SSO integration, with code samples, configuration options, and deployment guidance.

Create __init__.py

Refactor exception handling and formatting in oauth2_auth.py

Simplified exception raising in _fetch_oidc_discovery by consolidating RuntimeError messages into single lines. Improved code readability by reformatting function calls to follow consistent indentation.
@loveyana loveyana force-pushed the feat/add-oauth-middleware branch from 054ec10 to 23246f4 Compare January 27, 2026 14:57
Explicitly disables self sign-up and enables self account recovery when creating a user pool in IdentityClient.
@yaozheng-fang yaozheng-fang merged commit c8f6923 into volcengine:main Jan 28, 2026
5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants