Class OpenOAuth2

java.lang.Object
cloud.opencode.base.oauth2.OpenOAuth2

public final class OpenOAuth2 extends Object
OAuth2 Facade Class OAuth2 门面类

Main entry point for OAuth2 operations. Provides convenient factory methods for creating OAuth2 clients with pre-configured providers.

OAuth2 操作的主入口点。提供便捷的工厂方法来创建带有预配置提供者的 OAuth2 客户端。

Features | 主要功能:

  • Pre-configured providers (Google, Microsoft, GitHub) - 预配置提供者
  • PKCE challenge generation - PKCE 挑战生成
  • JWT parsing - JWT 解析
  • Token store factories - Token 存储工厂
  • State parameter generation (CSRF protection) - State 参数生成(CSRF 防护)
  • OIDC Discovery - OIDC 自动发现
  • Token Introspection (RFC 7662) - Token 内省
  • Pushed Authorization Requests (RFC 9126) - 推送授权请求
  • Token lifecycle management - Token 生命周期管理

Usage Examples | 使用示例:

// Quick start with Google
OAuth2Client client = OpenOAuth2.google("client-id", "client-secret")
    .redirectUri("https://yourapp.com/callback")
    .scopes("https://mail.google.com/")
    .build();

// Generate PKCE challenge
PkceChallenge pkce = OpenOAuth2.generatePkce();

// Get authorization URL
String authUrl = client.getAuthorizationUrl("state", pkce);

// Exchange code for token
OAuth2Token token = client.exchangeCode(code, pkce.verifier());

// Parse JWT
JwtClaims claims = OpenOAuth2.parseJwt(token.idToken());

Thread Safety | 线程安全:

This class is stateless and thread-safe.

此类是无状态的,线程安全。

Since:
JDK 25, opencode-base-oauth2 V1.0.0
Author:
Leon Soo www.LeonSoo.com
See Also:
  • Method Details

    • google

      public static OAuth2Client.Builder google(String clientId, String clientSecret)
      Create a Google OAuth2 client builder 创建 Google OAuth2 客户端构建器

      Example | 示例:

      OAuth2Client client = OpenOAuth2.google("client-id", "client-secret")
          .redirectUri("https://yourapp.com/callback")
          .scopes("https://mail.google.com/")
          .build();
      
      Parameters:
      clientId - the client ID | 客户端 ID
      clientSecret - the client secret | 客户端密钥
      Returns:
      the client builder | 客户端构建器
    • microsoft

      public static OAuth2Client.Builder microsoft(String clientId, String clientSecret)
      Create a Microsoft OAuth2 client builder 创建 Microsoft OAuth2 客户端构建器

      Example | 示例:

      OAuth2Client client = OpenOAuth2.microsoft("client-id", "client-secret")
          .redirectUri("https://yourapp.com/callback")
          .build();
      
      Parameters:
      clientId - the client ID | 客户端 ID
      clientSecret - the client secret | 客户端密钥
      Returns:
      the client builder | 客户端构建器
    • microsoft

      public static OAuth2Client.Builder microsoft(String tenantId, String clientId, String clientSecret)
      Create a Microsoft OAuth2 client builder for a specific tenant 为特定租户创建 Microsoft OAuth2 客户端构建器
      Parameters:
      tenantId - the Azure AD tenant ID | Azure AD 租户 ID
      clientId - the client ID | 客户端 ID
      clientSecret - the client secret | 客户端密钥
      Returns:
      the client builder | 客户端构建器
    • github

      public static OAuth2Client.Builder github(String clientId, String clientSecret)
      Create a GitHub OAuth2 client builder 创建 GitHub OAuth2 客户端构建器

      Example | 示例:

      OAuth2Client client = OpenOAuth2.github("client-id", "client-secret")
          .redirectUri("https://yourapp.com/callback")
          .build();
      
      Parameters:
      clientId - the client ID | 客户端 ID
      clientSecret - the client secret | 客户端密钥
      Returns:
      the client builder | 客户端构建器
    • apple

      public static OAuth2Client.Builder apple(String clientId, String clientSecret)
      Create an Apple OAuth2 client builder 创建 Apple OAuth2 客户端构建器
      Parameters:
      clientId - the client ID (Services ID) | 客户端 ID(服务 ID)
      clientSecret - the client secret (JWT) | 客户端密钥(JWT)
      Returns:
      the client builder | 客户端构建器
    • facebook

      public static OAuth2Client.Builder facebook(String clientId, String clientSecret)
      Create a Facebook OAuth2 client builder 创建 Facebook OAuth2 客户端构建器
      Parameters:
      clientId - the client ID (App ID) | 客户端 ID(应用 ID)
      clientSecret - the client secret (App Secret) | 客户端密钥(应用密钥)
      Returns:
      the client builder | 客户端构建器
    • client

      public static OAuth2Client.Builder client()
      Create a custom OAuth2 client builder 创建自定义 OAuth2 客户端构建器

      Example | 示例:

      OAuth2Client client = OpenOAuth2.client()
          .clientId("client-id")
          .clientSecret("client-secret")
          .authorizationEndpoint("https://auth.example.com/authorize")
          .tokenEndpoint("https://auth.example.com/token")
          .redirectUri("https://yourapp.com/callback")
          .build();
      
      Returns:
      the client builder | 客户端构建器
    • client

      public static OAuth2Client.Builder client(OAuth2Provider provider)
      Create an OAuth2 client builder with a custom provider 使用自定义提供者创建 OAuth2 客户端构建器
      Parameters:
      provider - the OAuth2 provider | OAuth2 提供者
      Returns:
      the client builder | 客户端构建器
    • fromConfig

      public static OAuth2Client fromConfig(OAuth2Config config)
      Create an OAuth2 client from configuration 从配置创建 OAuth2 客户端
      Parameters:
      config - the OAuth2 configuration | OAuth2 配置
      Returns:
      the client | 客户端
    • generatePkce

      public static PkceChallenge generatePkce()
      Generate a PKCE challenge 生成 PKCE 挑战

      Example | 示例:

      PkceChallenge pkce = OpenOAuth2.generatePkce();
      
      // Use in authorization request
      String authUrl = client.getAuthorizationUrl("state", pkce);
      
      // Use verifier in token exchange
      OAuth2Token token = client.exchangeCode(code, pkce.verifier());
      
      Returns:
      the PKCE challenge | PKCE 挑战
    • parseJwt

      public static JwtClaims parseJwt(String token)
      Parse a JWT token without signature verification 解析 JWT 令牌(不验证签名)

      Warning | 警告:

      This method does NOT verify the JWT signature. For security-critical applications, use a proper JWT library with signature verification.

      此方法不验证 JWT 签名。对于安全关键的应用程序,请使用具有签名验证的正式 JWT 库。

      Example | 示例:

      JwtClaims claims = OpenOAuth2.parseJwt(idToken);
      
      String subject = claims.sub();
      String issuer = claims.iss();
      
      if (claims.isExpired()) {
          // Token is expired
      }
      
      Parameters:
      token - the JWT token | JWT 令牌
      Returns:
      the JWT claims | JWT 声明
    • isExpired

      public static boolean isExpired(OAuth2Token token)
      Check if a token is expired 检查令牌是否已过期
      Parameters:
      token - the OAuth2 token | OAuth2 令牌
      Returns:
      true if expired | 已过期返回 true
    • isExpiringSoon

      public static boolean isExpiringSoon(OAuth2Token token, Duration threshold)
      Check if a token is expiring soon 检查令牌是否即将过期
      Parameters:
      token - the OAuth2 token | OAuth2 令牌
      threshold - the time threshold | 时间阈值
      Returns:
      true if expiring within threshold | 在阈值内即将过期返回 true
    • inMemoryTokenStore

      public static TokenStore inMemoryTokenStore()
      Create an in-memory token store 创建内存令牌存储
      Returns:
      the token store | 令牌存储
    • fileTokenStore

      public static TokenStore fileTokenStore(Path directory)
      Create a file-based token store 创建文件令牌存储
      Parameters:
      directory - the storage directory | 存储目录
      Returns:
      the token store | 令牌存储
    • fileTokenStore

      public static TokenStore fileTokenStore(String appName)
      Create a file-based token store in the user's home directory 在用户主目录中创建文件令牌存储
      Parameters:
      appName - the application name (used as subdirectory) | 应用程序名称(用作子目录)
      Returns:
      the token store | 令牌存储
    • generateState

      public static String generateState()
      Generate a cryptographically secure state parameter for CSRF protection 生成用于 CSRF 防护的加密安全 state 参数
      Returns:
      the state parameter string | state 参数字符串
    • validateState

      public static boolean validateState(String expected, String actual)
      Validate a state parameter using constant-time comparison 使用常量时间比较验证 state 参数
      Parameters:
      expected - the expected state | 期望的 state
      actual - the actual state from callback | 回调中的实际 state
      Returns:
      true if valid | 有效返回 true
    • discover

      public static DiscoveryDocument discover(String issuerUrl)
      Discover OIDC endpoints from an issuer URL 从 issuer URL 发现 OIDC 端点

      Example | 示例:

      DiscoveryDocument doc = OpenOAuth2.discover("https://accounts.google.com");
      String tokenEndpoint = doc.tokenEndpoint();
      
      Parameters:
      issuerUrl - the OIDC issuer URL | OIDC 颁发者 URL
      Returns:
      the discovery document | 发现文档
    • discover

      public static DiscoveryDocument discover(String issuerUrl, OAuth2HttpClient httpClient)
      Discover OIDC endpoints using a custom HTTP client 使用自定义 HTTP 客户端发现 OIDC 端点
      Parameters:
      issuerUrl - the OIDC issuer URL | OIDC 颁发者 URL
      httpClient - the HTTP client | HTTP 客户端
      Returns:
      the discovery document | 发现文档
    • tokenIntrospection

      public static TokenIntrospection tokenIntrospection(String introspectionEndpoint, String clientId, String clientSecret)
      Create a token introspection client 创建 Token 内省客户端
      Parameters:
      introspectionEndpoint - the introspection endpoint URL | 内省端点 URL
      clientId - the client ID | 客户端 ID
      clientSecret - the client secret | 客户端密钥
      Returns:
      the token introspection client | Token 内省客户端
    • par

      public static PushedAuthorizationRequest par(String parEndpoint, String clientId, String clientSecret)
      Create a pushed authorization request client 创建推送授权请求客户端
      Parameters:
      parEndpoint - the PAR endpoint URL | PAR 端点 URL
      clientId - the client ID | 客户端 ID
      clientSecret - the client secret | 客户端密钥
      Returns:
      the PAR client | PAR 客户端
    • tokenManager

      public static DefaultTokenManager.Builder tokenManager()
      Create a default token manager builder 创建默认 Token 管理器构建器

      Example | 示例:

      TokenManager manager = OpenOAuth2.tokenManager()
          .tokenStore(OpenOAuth2.inMemoryTokenStore())
          .build();
      
      Returns:
      the token manager builder | Token 管理器构建器
    • configBuilder

      public static OAuth2Config.Builder configBuilder()
      Create a new OAuth2 configuration builder 创建新的 OAuth2 配置构建器
      Returns:
      the configuration builder | 配置构建器