Skip to main content

Overview

The oauth2 middleware provides OAuth 2.0 authentication flows for integrating with providers like Google, GitHub, Facebook, and custom OAuth servers. Use it when you need:
  • Social login (Google, GitHub, etc.)
  • Third-party authentication
  • OAuth 2.0 authorization code flow

Installation

Quick Start

Configuration

Config

Examples

Google OAuth

GitHub OAuth

Custom Provider

State Parameter

API Reference

Functions

Types

Technical Details

Architecture

The OAuth2 middleware is designed as a resource server implementation that validates OAuth 2.0 access tokens. It follows a flexible architecture that supports multiple validation strategies:
  1. Token Extraction: Supports multiple token sources (header, query, form) via configurable TokenLookup parameter
  2. Token Validation: Two validation strategies:
    • Custom validator function for flexibility
    • Token introspection endpoint (RFC 7662) for standard OAuth servers
  3. Scope Verification: Automatic scope checking against required scopes
  4. Context Storage: Validated token information is stored in request context for downstream handlers

Token Validation Flow

  1. Extract token from request based on TokenLookup configuration
  2. Validate token using:
    • Custom Validator function if provided, or
    • OAuth 2.0 token introspection endpoint
  3. Check token expiration if ExpiresAt is set
  4. Verify required scopes match token scopes
  5. Store validated token in context
  6. Pass request to next handler

Token Introspection

When using the introspection endpoint, the middleware:
  • Sends POST request to IntrospectionURL with token
  • Uses Basic authentication with ClientID and ClientSecret if provided
  • Parses introspection response according to RFC 7662
  • Validates the active field and extracts token metadata (subject, scopes, expiry)

Error Handling

The middleware returns appropriate HTTP status codes:
  • 401 Unauthorized: Missing, invalid, or expired tokens
  • 403 Forbidden: Insufficient scopes
  • Sets WWW-Authenticate: Bearer header on errors
Custom error handling can be implemented via the ErrorHandler option.

Context Access

Helper functions provide convenient access to token information:
  • Get(c): Retrieves full token object
  • Subject(c): Gets token subject
  • Scopes(c): Returns token scopes
  • HasScope(c, scope): Checks for specific scope

Scope Middleware

The RequireScopes middleware can be chained after the main OAuth2 middleware to enforce scope requirements at specific routes or route groups.

Security Considerations

  1. Store secrets securely - Use environment variables
  2. Validate state parameter - Prevents CSRF attacks
  3. Use HTTPS - Required for production OAuth
  4. Verify tokens - Check expiration and validity
  5. Limit scopes - Request only needed permissions

Best Practices

  • Store tokens securely (encrypted if stored)
  • Implement token refresh for long sessions
  • Handle callback errors gracefully
  • Log OAuth events for security monitoring

Testing

The OAuth2 middleware includes comprehensive test coverage for all functionality:
  • oidc - OpenID Connect
  • jwt - JWT authentication
  • session - Session management