oauth2

package module
v0.5.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 22, 2025 License: MIT Imports: 17 Imported by: 5

README

oauth2

OAuth 2.0 授权框架的 Go 语言实现,支持 SaaS 多租户场景。

Go implementation of OAuth 2.0 Authorization Framework with SaaS multi-tenant support.

Features / 特性

  • ✅ 授权码模式 (Authorization Code)
  • ✅ 简化模式 (Implicit)
  • ✅ 密码模式 (Resource Owner Password Credentials)
  • ✅ 客户端凭证模式 (Client Credentials)
  • ✅ 设备授权模式 (Device Code) - RFC 8628
  • ✅ 令牌内省 (Token Introspection) - RFC 7662
  • ✅ 令牌撤销 (Token Revocation) - RFC 7009
  • PKCE 支持 - RFC 7636 增强公开客户端安全性
  • SaaS 多租户动态 Issuer - 根据请求域名动态生成 JWT issuer
  • SaaS 多租户动态 JWT 密钥 - 每个租户使用独立的签名密钥
  • 反向代理支持 - 支持 X-Forwarded-* 头部

Installation / 安装

go get -u github.com/nilorg/oauth2

Import / 导入

import "github.com/nilorg/oauth2"

Quick Start / 快速开始

基础用法 / Basic Usage
srv := oauth2.NewServer()
// 配置回调函数...
srv.InitWithError()
SaaS 多租户场景 / SaaS Multi-tenant Scenario
srv := oauth2.NewServer(
    // 动态 Issuer:根据请求 Host 自动生成 JWT 的 iss 字段
    oauth2.ServerIssuerFunc(func(ctx context.Context, req oauth2.IssuerRequest) string {
        // req.Host   = "tenant1.example.com"
        // req.Scheme = "https"
        return fmt.Sprintf("%s://%s", req.Scheme, req.Host)
    }),
)
反向代理场景 / Reverse Proxy Scenario
srv := oauth2.NewServer(
    // 使用内置的反向代理支持,从 X-Forwarded-* 头部获取信息
    oauth2.ServerIssuerRequestFunc(oauth2.ProxyIssuerRequestFunc),
    oauth2.ServerIssuerFunc(func(ctx context.Context, req oauth2.IssuerRequest) string {
        return fmt.Sprintf("%s://%s", req.Scheme, req.Host)
    }),
)
自定义 IssuerRequest 提取 / Custom IssuerRequest Extraction
srv := oauth2.NewServer(
    oauth2.ServerIssuerRequestFunc(func(r *http.Request) oauth2.IssuerRequest {
        return oauth2.IssuerRequest{
            Host:   r.Header.Get("X-Tenant-Domain"),
            Scheme: r.Header.Get("X-Forwarded-Proto"),
        }
    }),
    oauth2.ServerIssuerFunc(func(ctx context.Context, req oauth2.IssuerRequest) string {
        return fmt.Sprintf("%s://%s", req.Scheme, req.Host)
    }),
)
静态 Issuer(单租户)/ Static Issuer (Single Tenant)
srv := oauth2.NewServer(
    oauth2.ServerIssuer("https://auth.example.com"),
)
多租户 JWT 密钥 / Multi-tenant JWT Key
// 每个租户使用独立的 JWT 签名密钥
srv.AccessToken = oauth2.NewMultiTenantAccessToken(func(ctx context.Context, issuer string) []byte {
    // issuer = "https://tenant1.example.com"
    // 根据 issuer 从数据库/配置中获取对应租户的密钥
    return getTenantJwtKey(issuer)
})

PKCE Support / PKCE 支持

PKCE (Proof Key for Code Exchange) 是 RFC 7636 定义的扩展,用于增强公开客户端(如移动应用、单页应用)的安全性。

客户端实现 / Client Implementation
// 1. 生成 code_verifier 和 code_challenge
codeVerifier := oauth2.RandomCodeVerifier()
codeChallenge := oauth2.GenerateCodeChallenge(codeVerifier, oauth2.CodeChallengeMethodS256)

// 2. 授权请求中包含 code_challenge
// GET /authorize?response_type=code&client_id=xxx&redirect_uri=xxx
//     &code_challenge=xxx&code_challenge_method=S256

// 3. Token 请求中包含 code_verifier
// POST /token
//     grant_type=authorization_code&code=xxx&code_verifier=xxx
服务端实现 / Server Implementation
// GenerateCode 需要存储 PKCE 参数
srv.GenerateCode = func(ctx context.Context, clientID, openID, redirectURI string, 
    scope []string, codeChallenge, codeChallengeMethod string) (string, error) {
    code := oauth2.RandomCode()
    // 存储: code -> {clientID, openID, redirectURI, scope, codeChallenge, codeChallengeMethod}
    return code, nil
}

// VerifyCode 需要返回 PKCE 参数
srv.VerifyCode = func(ctx context.Context, code, clientID, redirectURI string) (*oauth2.CodeValue, error) {
    // 从存储中获取
    return &oauth2.CodeValue{
        ClientID:            clientID,
        RedirectURI:         redirectURI,
        Scope:               []string{"read", "write"},
        CodeChallenge:       savedCodeChallenge,       // PKCE
        CodeChallengeMethod: savedCodeChallengeMethod, // PKCE
    }, nil
}

Examples / 示例

oauth2-server

server/client examples

Documentation / 文档参考

  1. 《理解OAuth 2.0》阮一峰
  2. RFC 6749 - The OAuth 2.0 Authorization Framework
  3. RFC 7636 - Proof Key for Code Exchange (PKCE)
  4. RFC 8628 - OAuth 2.0 Device Authorization Grant
  5. RFC 7662 - OAuth 2.0 Token Introspection
  6. RFC 7009 - OAuth 2.0 Token Revocation

Grant Types / 授权模式

Authorization Code / 授权码模式

授权码模式是功能最完整、流程最严密的授权模式。它的特点就是通过客户端的后台服务器,与"服务提供商"的认证服务器进行互动。

Implicit / 简化模式

简化模式不通过第三方应用程序的服务器,直接在浏览器中向认证服务器申请令牌,跳过了"授权码"这个步骤。

Resource Owner Password Credentials / 密码模式

用户向客户端提供自己的用户名和密码,客户端使用这些信息向"服务商提供商"索要授权。

Client Credentials / 客户端凭证模式

客户端以自己的名义,而不是以用户的名义,向"服务提供商"进行认证。

Device Code / 设备模式

设备授权模式用于无法输入的设备(如智能电视、IoT设备等)。

Server Configuration / 服务器配置

Server Options / 服务器选项
Option Description
ServerLogger(log) 设置日志记录器
ServerIssuer(issuer) 设置静态 JWT issuer
ServerIssuerFunc(fn) 设置动态 JWT issuer 函数(SaaS多租户)
ServerIssuerRequestFunc(fn) 设置从HTTP请求提取信息的函数
ServerDeviceAuthorizationEndpointEnabled(bool) 启用设备授权端点
ServerIntrospectEndpointEnabled(bool) 启用令牌内省端点
ServerTokenRevocationEnabled(bool) 启用令牌撤销端点
AccessToken 配置 / AccessToken Configuration
Function Description
NewDefaultAccessToken(key) 创建静态密钥的 AccessToken 处理器(单租户)
NewMultiTenantAccessToken(fn) 创建动态密钥的 AccessToken 处理器(多租户)
PKCE 工具函数 / PKCE Utility Functions
Function Description
RandomCodeVerifier() 生成随机的 code_verifier (43字符)
GenerateCodeChallenge(verifier, method) 根据 verifier 生成 code_challenge
VerifyCodeChallenge(challenge, method, verifier) 验证 code_verifier 是否匹配
PKCE 常量 / PKCE Constants
Constant Description
CodeChallengeMethodPlain PKCE plain 方法
CodeChallengeMethodS256 PKCE S256 方法 (推荐)

Complete Server Example / 完整服务器示例

package main

import (
    "context"
    "fmt"
    "net/http"

    "github.com/gin-gonic/gin"
    "github.com/nilorg/oauth2"
)

var clients = map[string]string{
    "oauth2_client": "password",
}

func main() {
    srv := oauth2.NewServer(
        // SaaS多租户:动态Issuer
        oauth2.ServerIssuerFunc(func(ctx context.Context, req oauth2.IssuerRequest) string {
            return fmt.Sprintf("%s://%s", req.Scheme, req.Host)
        }),
        oauth2.ServerDeviceAuthorizationEndpointEnabled(true),
    )

    srv.VerifyClient = func(ctx context.Context, basic *oauth2.ClientBasic) (err error) {
        pwd, ok := clients[basic.ID]
        if !ok || basic.Secret != pwd {
            return oauth2.ErrInvalidClient
        }
        return nil
    }

    srv.VerifyClientID = func(ctx context.Context, clientID string) (err error) {
        if _, ok := clients[clientID]; !ok {
            return oauth2.ErrInvalidClient
        }
        return nil
    }

    srv.VerifyCode = func(ctx context.Context, code, clientID, redirectURI string) (*oauth2.CodeValue, error) {
        return &oauth2.CodeValue{
            ClientID:    clientID,
            RedirectURI: redirectURI,
            Scope:       []string{"read", "write"},
            // PKCE: 如果启用 PKCE,需要从存储中返回 CodeChallenge 和 CodeChallengeMethod
        }, nil
    }

    srv.GenerateCode = func(ctx context.Context, clientID, openID, redirectURI string, 
        scope []string, codeChallenge, codeChallengeMethod string) (string, error) {
        code := oauth2.RandomCode()
        // 存储 code 信息,包括 PKCE 参数
        return code, nil
    }

    srv.VerifyRedirectURI = func(ctx context.Context, clientID, redirectURI string) error {
        return nil
    }

    srv.VerifyPassword = func(ctx context.Context, clientID, username, password string) (string, error) {
        if username == "admin" && password == "123456" {
            return "user_001", nil
        }
        return "", oauth2.ErrUnauthorizedClient
    }

    srv.VerifyScope = func(ctx context.Context, scopes []string, clientID string) error {
        return nil
    }

    srv.VerifyGrantType = func(ctx context.Context, clientID, grantType string) error {
        return nil
    }

    srv.AccessToken = oauth2.NewDefaultAccessToken([]byte("your-jwt-secret"))

    srv.GenerateDeviceAuthorization = func(ctx context.Context, issuer, verificationURI, clientID string, scope []string) (*oauth2.DeviceAuthorizationResponse, error) {
        return &oauth2.DeviceAuthorizationResponse{
            DeviceCode:      oauth2.RandomCode(),
            UserCode:        oauth2.RandomUserCode(),
            VerificationURI: issuer + verificationURI,
            ExpiresIn:       1800,
            Interval:        5,
        }, nil
    }

    srv.VerifyDeviceCode = func(ctx context.Context, deviceCode, clientID string) (*oauth2.DeviceCodeValue, error) {
        return nil, nil
    }

    if err := srv.InitWithError(); err != nil {
        panic(err)
    }

    r := gin.Default()
    oauth2Group := r.Group("/oauth2")
    {
        oauth2Group.GET("/authorize", func(c *gin.Context) {
            srv.HandleAuthorize(c.Writer, c.Request)
        })
        oauth2Group.POST("/token", func(c *gin.Context) {
            srv.HandleToken(c.Writer, c.Request)
        })
        oauth2Group.POST("/device_authorization", func(c *gin.Context) {
            srv.HandleDeviceAuthorization(c.Writer, c.Request)
        })
    }

    http.ListenAndServe(":8003", r)
}

Test / 测试

# Password Grant
curl -X POST http://localhost:8003/oauth2/token \
  -u oauth2_client:password \
  -d 'grant_type=password&username=admin&password=123456&scope=read'

# Client Credentials Grant  
curl -X POST http://localhost:8003/oauth2/token \
  -u oauth2_client:password \
  -d 'grant_type=client_credentials&scope=read'

# Refresh Token (所有 grant_type 都支持刷新)
curl -X POST http://localhost:8003/oauth2/token \
  -u oauth2_client:password \
  -d 'grant_type=refresh_token&refresh_token=YOUR_REFRESH_TOKEN'
PKCE 测试 / PKCE Test
# 1. 生成 code_verifier 和 code_challenge (S256)
# code_verifier: dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk
# code_challenge: E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM

# 2. 授权请求 (包含 code_challenge)
# GET /oauth2/authorize?response_type=code&client_id=oauth2_client
#     &redirect_uri=http://localhost:8080/callback
#     &code_challenge=E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM
#     &code_challenge_method=S256

# 3. Token 请求 (包含 code_verifier)
curl -X POST http://localhost:8003/oauth2/token \
  -u oauth2_client:password \
  -d 'grant_type=authorization_code&code=YOUR_CODE&redirect_uri=http://localhost:8080/callback&code_verifier=dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk'

JWT Payload / JWT 载荷

标准声明 (Registered Claims):

Claim Description
iss 令牌颁发者 (Issuer) - 在SaaS场景下会动态生成
sub 令牌主体 (Subject) - 通常是用户标识
aud 令牌受众 (Audience)
exp 过期时间 (Expiration Time)
nbf 生效时间 (Not Before)
iat 颁发时间 (Issued At)
jti 令牌唯一标识 (JWT ID)

License

MIT

Documentation

Index

Constants

View Source
const (

	// AccessTokenExpire 访问令牌过期时间(1小时) / Access token expiration time (1 hour)
	AccessTokenExpire = time.Second * 3600
	// RefreshTokenExpire 刷新令牌过期时间(30分钟) / Refresh token expiration time (30 minutes)
	RefreshTokenExpire = AccessTokenExpire / 2
	// TokenTypeBearer Bearer令牌类型 / Bearer token type
	TokenTypeBearer = "Bearer"
	// ScopeRefreshToken 刷新令牌的scope / Scope for refresh token
	ScopeRefreshToken = "refresh_token"
	// DefaultJwtIssuer 默认JWT颁发者 / Default JWT issuer
	DefaultJwtIssuer = "github.com/nilorg/oauth2"

	// PKCE 相关常量 / PKCE related constants (RFC 7636)
	// CodeChallengeMethodPlain 明文方法 / Plain method
	CodeChallengeMethodPlain = "plain"
	// CodeChallengeMethodS256 SHA256方法 / SHA256 method
	CodeChallengeMethodS256 = "S256"
)
View Source
const (
	// ResponseTypeKey 响应类型 / Response type parameter key
	ResponseTypeKey = "response_type"
	// ClientIDKey 客户端ID / Client identifier parameter key
	ClientIDKey = "client_id"
	// ClientSecretKey 客户端密钥 / Client secret parameter key
	ClientSecretKey = "client_secret"
	// RedirectURIKey 重定向URI / Redirect URI parameter key
	RedirectURIKey = "redirect_uri"
	// ScopeKey 授权范围 / Scope parameter key
	ScopeKey = "scope"
	// StateKey 状态码,用于防止CSRF攻击 / State parameter key for CSRF protection
	StateKey = "state"
	// GrantTypeKey 授权类型 / Grant type parameter key
	GrantTypeKey = "grant_type"
	// CodeKey 授权码 / Authorization code parameter key
	CodeKey = "code"
	// TokenKey 令牌 / Token parameter key
	TokenKey = "token"
	// ErrorKey 错误信息 / Error parameter key
	ErrorKey = "error"
	// AccessTokenKey 访问令牌 / Access token parameter key
	AccessTokenKey = "access_token"
	// TokenTypeKey 令牌类型 / Token type parameter key
	TokenTypeKey = "token_type"
	// ClientCredentialsKey 客户端凭证模式 / Client credentials grant type
	ClientCredentialsKey = "client_credentials"
	// PasswordKey 密码模式 / Resource owner password credentials grant type
	PasswordKey = "password"
	// UsernameKey 用户名 / Username parameter key
	UsernameKey = "username"
	// RefreshTokenKey 刷新令牌 / Refresh token parameter key
	RefreshTokenKey = "refresh_token"
	// AuthorizationCodeKey 授权码模式 / Authorization code grant type
	AuthorizationCodeKey = "authorization_code"
	// DeviceCodeKey 设备码模式 / Device code grant type
	DeviceCodeKey = "device_code"
	// UrnIetfParamsOAuthGrantTypeDeviceCodeKey 设备码模式URN格式 / Device code grant type in URN format (RFC 8628)
	UrnIetfParamsOAuthGrantTypeDeviceCodeKey = "urn:ietf:params:oauth:grant-type:device_code"
	// TokenTypeHintKey 令牌类型提示 / Token type hint parameter key
	TokenTypeHintKey = "token_type_hint"
	// ImplicitKey 隐式授权模式 / Implicit grant type
	ImplicitKey = "implicit"

	// PKCE 相关参数键 / PKCE related parameter keys (RFC 7636)
	// CodeChallengeKey PKCE code_challenge 参数 / PKCE code_challenge parameter
	CodeChallengeKey = "code_challenge"
	// CodeChallengeMethodKey PKCE code_challenge_method 参数 / PKCE code_challenge_method parameter
	CodeChallengeMethodKey = "code_challenge_method"
	// CodeVerifierKey PKCE code_verifier 参数 / PKCE code_verifier parameter
	CodeVerifierKey = "code_verifier"
)

Variables

View Source
var (
	// ErrContextNotFoundOpenID 上下文不存在OpenID / OpenID not found in context
	ErrContextNotFoundOpenID = errors.New("openid not found in context")
	// ErrContextNotFoundIssuerRequest 上下文不存在IssuerRequest / IssuerRequest not found in context
	ErrContextNotFoundIssuerRequest = errors.New("issuer request not found in context")
)
View Source
var (
	// ErrInvalidRequest 无效的请求
	ErrInvalidRequest = errors.New("invalid_request")
	// ErrUnauthorizedClient 未经授权的客户端
	ErrUnauthorizedClient = errors.New("unauthorized_client")
	// ErrAccessDenied 拒绝访问
	ErrAccessDenied = errors.New("access_denied")
	// ErrUnsupportedResponseType 不支持的response类型
	ErrUnsupportedResponseType = errors.New("unsupported_response_type")
	// ErrUnsupportedGrantType 不支持的grant类型
	ErrUnsupportedGrantType = errors.New("unsupported_grant_type")
	// ErrInvalidGrant 无效的grant
	ErrInvalidGrant = errors.New("invalid_grant")
	// ErrInvalidScope 无效scope
	ErrInvalidScope = errors.New("invalid_scope")
	// ErrTemporarilyUnavailable 暂时不可用
	ErrTemporarilyUnavailable = errors.New("temporarily_unavailable")
	// ErrServerError 服务器错误
	ErrServerError = errors.New("server_error")
	// ErrInvalidClient 无效的客户
	ErrInvalidClient = errors.New("invalid_client")
	// ErrExpiredToken 过期的令牌
	ErrExpiredToken = errors.New("expired_token")
	// ErrAuthorizationPending 授权待定
	// https://tools.ietf.org/html/rfc8628#section-3.5
	ErrAuthorizationPending = errors.New("authorization_pending")
	// ErrSlowDown 轮询太频繁
	// https://tools.ietf.org/html/rfc8628#section-3.5
	ErrSlowDown = errors.New("slow_down")
	// ErrUnsupportedTokenType 不支持的令牌类型
	// https://tools.ietf.org/html/rfc7009#section-4.1.1
	ErrUnsupportedTokenType = errors.New("unsupported_token_type")
)
View Source
var (
	// ErrVerifyClientFuncNil VerifyClient函数未设置 / VerifyClient function is not set
	ErrVerifyClientFuncNil = errors.New("OAuth2 Server VerifyClient Is Nil")
	// ErrVerifyClientIDFuncNil VerifyClientID函数未设置 / VerifyClientID function is not set
	ErrVerifyClientIDFuncNil = errors.New("OAuth2 Server VerifyClientID Is Nil")
	// ErrVerifyPasswordFuncNil VerifyPassword函数未设置 / VerifyPassword function is not set
	ErrVerifyPasswordFuncNil = errors.New("OAuth2 Server VerifyPassword Is Nil")
	// ErrVerifyRedirectURIFuncNil VerifyRedirectURI函数未设置 / VerifyRedirectURI function is not set
	ErrVerifyRedirectURIFuncNil = errors.New("OAuth2 Server VerifyRedirectURI Is Nil")
	// ErrGenerateCodeFuncNil GenerateCode函数未设置 / GenerateCode function is not set
	ErrGenerateCodeFuncNil = errors.New("OAuth2 Server GenerateCode Is Nil")
	// ErrVerifyCodeFuncNil VerifyCode函数未设置 / VerifyCode function is not set
	ErrVerifyCodeFuncNil = errors.New("OAuth2 Server VerifyCode Is Nil")
	// ErrVerifyScopeFuncNil VerifyScope函数未设置 / VerifyScope function is not set
	ErrVerifyScopeFuncNil = errors.New("OAuth2 Server VerifyScope Is Nil")
	// ErrGenerateAccessTokenFuncNil GenerateAccessToken函数未设置 / GenerateAccessToken function is not set
	ErrGenerateAccessTokenFuncNil = errors.New("OAuth2 Server GenerateAccessTokenFunc Is Nil")
	// ErrGenerateDeviceAuthorizationFuncNil GenerateDeviceAuthorization函数未设置 / GenerateDeviceAuthorization function is not set
	ErrGenerateDeviceAuthorizationFuncNil = errors.New("OAuth2 Server GenerateDeviceAuthorizationFunc Is Nil")
	// ErrVerifyDeviceCodeFuncNil VerifyDeviceCode函数未设置 / VerifyDeviceCode function is not set
	ErrVerifyDeviceCodeFuncNil = errors.New("OAuth2 Server ErrVerifyDeviceCodeFunc Is Nil")
	// ErrRefreshAccessTokenFuncNil RefreshAccessToken函数未设置 / RefreshAccessToken function is not set
	ErrRefreshAccessTokenFuncNil = errors.New("OAuth2 Server ErrRefreshAccessTokenFuncNil Is Nil")
	// ErrParseAccessTokenFuncNil ParseAccessToken函数未设置 / ParseAccessToken function is not set
	ErrParseAccessTokenFuncNil = errors.New("OAuth2 Server ParseAccessTokenFunc Is Nil")
	// ErrVerifyIntrospectionTokenFuncNil VerifyIntrospectionToken函数未设置 / VerifyIntrospectionToken function is not set
	ErrVerifyIntrospectionTokenFuncNil = errors.New("OAuth2 Server VerifyIntrospectionToken Is Nil")
	// ErrTokenRevocationFuncNil TokenRevocation函数未设置 / TokenRevocation function is not set
	ErrTokenRevocationFuncNil = errors.New("OAuth2 Server TokenRevocation Is Nil")
	// ErrVerifyGrantTypeFuncNil VerifyGrantType函数未设置 / VerifyGrantType function is not set
	ErrVerifyGrantTypeFuncNil = errors.New("OAuth2 Server VerifyGrantType Is Nil")
	// ErrInvalidAccessToken 无效的访问令牌
	ErrInvalidAccessToken = errors.New("invalid_access_token")
	// ErrInvalidRedirectURI 无效的RedirectURI
	ErrInvalidRedirectURI = errors.New("invalid_redirect_uri")
	// ErrStateValueDidNotMatch state值不匹配 / State value did not match
	ErrStateValueDidNotMatch = errors.New("state value did not match")
	// ErrMissingAccessToken 缺少访问令牌 / Missing access token in request
	ErrMissingAccessToken = errors.New("missing access token")
	// ErrAccessToken AccessToken接口未设置 / AccessToken interface is not set
	ErrAccessToken = errors.New("OAuth2 Server AccessToken Is Nil")
)
View Source
var (
	// Errors 错误映射表,用于从错误字符串查找错误对象 / Error map for looking up error objects from error strings
	Errors = map[string]error{
		ErrVerifyClientFuncNil.Error():   ErrVerifyClientFuncNil,
		ErrInvalidAccessToken.Error():    ErrInvalidAccessToken,
		ErrStateValueDidNotMatch.Error(): ErrStateValueDidNotMatch,
		ErrMissingAccessToken.Error():    ErrMissingAccessToken,

		ErrInvalidRequest.Error():          ErrInvalidRequest,
		ErrUnauthorizedClient.Error():      ErrUnauthorizedClient,
		ErrAccessDenied.Error():            ErrAccessDenied,
		ErrUnsupportedResponseType.Error(): ErrUnsupportedResponseType,
		ErrUnsupportedGrantType.Error():    ErrUnsupportedGrantType,
		ErrInvalidGrant.Error():            ErrInvalidGrant,
		ErrInvalidScope.Error():            ErrInvalidScope,
		ErrTemporarilyUnavailable.Error():  ErrTemporarilyUnavailable,
		ErrServerError.Error():             ErrServerError,
		ErrInvalidClient.Error():           ErrInvalidClient,
		ErrExpiredToken.Error():            ErrExpiredToken,
		ErrAuthorizationPending.Error():    ErrAuthorizationPending,
		ErrSlowDown.Error():                ErrSlowDown,
		ErrUnsupportedTokenType.Error():    ErrUnsupportedTokenType,
	}
	// ErrStatusCodes 错误对应的HTTP状态码映射表 / HTTP status codes mapping for errors
	// 根据 RFC 6749 Section 5.2,Token 端点错误应返回 400 Bad Request
	// 仅 invalid_client 在客户端认证失败时返回 401
	// According to RFC 6749 Section 5.2, token endpoint errors should return 400 Bad Request
	// Only invalid_client returns 401 when client authentication fails
	ErrStatusCodes = map[error]int{
		ErrInvalidRequest:          http.StatusBadRequest,
		ErrUnauthorizedClient:      http.StatusBadRequest,
		ErrAccessDenied:            http.StatusForbidden,
		ErrUnsupportedResponseType: http.StatusBadRequest,
		ErrInvalidScope:            http.StatusBadRequest,
		ErrServerError:             http.StatusInternalServerError,
		ErrTemporarilyUnavailable:  http.StatusServiceUnavailable,
		ErrInvalidClient:           http.StatusUnauthorized,
		ErrInvalidGrant:            http.StatusBadRequest,
		ErrUnsupportedGrantType:    http.StatusBadRequest,
		ErrExpiredToken:            http.StatusUnauthorized,
		ErrAuthorizationPending:    http.StatusBadRequest,
		ErrSlowDown:                http.StatusBadRequest,
		ErrUnsupportedTokenType:    http.StatusServiceUnavailable,
	}
)

Functions

func GenerateCodeChallenge added in v0.5.0

func GenerateCodeChallenge(codeVerifier, method string) string

GenerateCodeChallenge 生成 PKCE code_challenge (RFC 7636) Generate PKCE code_challenge from code_verifier

func NewHS256JwtClaimsToken added in v0.2.1

func NewHS256JwtClaimsToken(claims *JwtClaims, jwtVerifyKey []byte) (string, error)

NewHS256JwtClaimsToken ...

func NewIssuerRequestContext added in v0.5.0

func NewIssuerRequestContext(ctx context.Context, req IssuerRequest) context.Context

NewIssuerRequestContext 创建包含IssuerRequest的上下文 / Create context with IssuerRequest

func NewJwtClaimsToken added in v0.2.1

func NewJwtClaimsToken(claims *JwtClaims, algorithm string, key interface{}) (string, error)

NewJwtClaimsToken ...

func NewJwtStandardClaimsToken added in v0.2.1

func NewJwtStandardClaimsToken(claims *JwtStandardClaims, algorithm string, key interface{}) (string, error)

NewJwtStandardClaimsToken ...

func NewJwtToken added in v0.2.0

func NewJwtToken(v interface{}, algorithm string, key interface{}) (string, error)

NewJwtToken ...

func NewOpenIDContext added in v0.0.3

func NewOpenIDContext(ctx context.Context, openID string) context.Context

NewOpenIDContext 创建包含OpenID的上下文 / Create context with OpenID

func OpenIDFromContext added in v0.0.3

func OpenIDFromContext(ctx context.Context) (string, error)

OpenIDFromContext 从上下文中获取OpenID / Get OpenID from context

func RandomCode

func RandomCode() string

RandomCode 随机Code

func RandomCodeVerifier added in v0.5.0

func RandomCodeVerifier() string

RandomCodeVerifier 生成随机 PKCE code_verifier (RFC 7636 Section 4.1) Generate random PKCE code_verifier (43-128 characters)

func RandomDeviceCode added in v0.2.0

func RandomDeviceCode() string

RandomDeviceCode 随机DeviceCode

func RandomState

func RandomState() string

RandomState 随机State

func RandomUserCode added in v0.2.0

func RandomUserCode() string

RandomUserCode 随机用户code

func RedirectError

func RedirectError(w http.ResponseWriter, r *http.Request, redirectURI *url.URL, err error)

RedirectError 重定向错误

func RedirectSuccess

func RedirectSuccess(w http.ResponseWriter, r *http.Request, redirectURI *url.URL, code string)

RedirectSuccess 重定向成功

func StringSplit added in v0.0.4

func StringSplit(s, sep string) (results []string)

StringSplit strings.Split

func VerifyCodeChallenge added in v0.5.0

func VerifyCodeChallenge(codeChallenge, codeChallengeMethod, codeVerifier string) bool

VerifyCodeChallenge 验证 PKCE code_verifier (RFC 7636 Section 4.6) Verify PKCE code_verifier against code_challenge

func WriterError

func WriterError(w http.ResponseWriter, err error)

WriterError 写入Error

func WriterJSON

func WriterJSON(w http.ResponseWriter, value interface{})

WriterJSON 写入Json

Types

type AccessTokener added in v0.4.2

type AccessTokener interface {
	Generate(ctx context.Context, issuer, clientID, scope, openID string, code *CodeValue) (token *TokenResponse, err error)
	Refresh(ctx context.Context, clientID, refreshToken string) (token *TokenResponse, err error)
	Parse(ctx context.Context, accessToken string) (claims *JwtClaims, err error)
}

AccessTokener AccessToken接口

type Client

type Client struct {
	Log Logger // 日志记录器 / Logger instance

	ServerBaseURL               string // 服务器基础URL / OAuth2 server base URL
	AuthorizationEndpoint       string // 授权端点 / Authorization endpoint path
	TokenEndpoint               string // 令牌端点 / Token endpoint path
	IntrospectEndpoint          string // 内省端点 / Introspection endpoint path
	DeviceAuthorizationEndpoint string // 设备授权端点 / Device authorization endpoint path
	TokenRevocationEndpoint     string // 令牌撤销端点 / Token revocation endpoint path
	ID                          string // 客户端ID / Client identifier
	Secret                      string // 客户端密钥 / Client secret
	// contains filtered or unexported fields
}

Client OAuth2客户端 / OAuth2 client for making authorization requests

func NewClient

func NewClient(serverBaseURL, id, secret string) *Client

NewClient 创建OAuth2客户端 / Create a new OAuth2 client serverBaseURL: 服务器基础URL / OAuth2 server base URL id: 客户端ID / Client identifier secret: 客户端密钥 / Client secret

func (*Client) AuthorizeAuthorizationCode

func (c *Client) AuthorizeAuthorizationCode(ctx context.Context, w http.ResponseWriter, redirectURI, scope, state string) (err error)

AuthorizeAuthorizationCode 授权码模式授权请求 / Authorization code grant authorization request redirectURI: 重定向URI / Redirect URI after authorization scope: 授权范围 / Requested scope state: 状态码,用于防止CSRF攻击 / State parameter for CSRF protection

func (*Client) AuthorizeImplicit

func (c *Client) AuthorizeImplicit(ctx context.Context, w http.ResponseWriter, redirectURI, scope, state string) (err error)

AuthorizeImplicit 隐式授权模式授权请求 / Implicit grant authorization request redirectURI: 重定向URI / Redirect URI after authorization scope: 授权范围 / Requested scope state: 状态码,用于防止CSRF攻击 / State parameter for CSRF protection

func (*Client) DeviceAuthorization added in v0.2.0

func (c *Client) DeviceAuthorization(ctx context.Context, w http.ResponseWriter, scope string) (err error)

DeviceAuthorization 设备授权请求 / Device authorization request (RFC 8628) scope: 授权范围 / Requested scope

func (*Client) RefreshToken

func (c *Client) RefreshToken(ctx context.Context, refreshToken string) (model *TokenResponse, err error)

RefreshToken 刷新访问令牌 / Refresh access token using refresh token refreshToken: 刷新令牌 / Refresh token

func (*Client) Token added in v0.3.3

func (c *Client) Token(ctx context.Context, grantType string, values url.Values) (token *TokenResponse, err error)

func (*Client) TokenAuthorizationCode

func (c *Client) TokenAuthorizationCode(ctx context.Context, code, redirectURI, clientID string) (token *TokenResponse, err error)

TokenAuthorizationCode 授权码模式获取令牌 / Exchange authorization code for access token code: 授权码 / Authorization code received from authorization server redirectURI: 重定向URI / Redirect URI used in authorization request clientID: 客户端ID / Client identifier

func (*Client) TokenClientCredentials

func (c *Client) TokenClientCredentials(ctx context.Context, scope ...string) (model *TokenResponse, err error)

TokenClientCredentials 客户端凭证模式获取令牌 / Client credentials grant scope: 授权范围(可选) / Requested scope (optional)

func (*Client) TokenDeviceCode added in v0.2.0

func (c *Client) TokenDeviceCode(ctx context.Context, deviceCode string) (model *TokenResponse, err error)

TokenDeviceCode 设备码模式获取令牌 / Exchange device code for access token (RFC 8628) deviceCode: 设备码 / Device code received from device authorization

func (*Client) TokenIntrospect added in v0.2.0

func (c *Client) TokenIntrospect(ctx context.Context, token string, tokenTypeHint ...string) (introspection *IntrospectionResponse, err error)

TokenIntrospect 令牌内省 / Token introspection (RFC 7662) token: 要检查的令牌 / Token to introspect tokenTypeHint: 令牌类型提示(可选) / Token type hint (optional): access_token or refresh_token

func (*Client) TokenResourceOwnerPasswordCredentials

func (c *Client) TokenResourceOwnerPasswordCredentials(ctx context.Context, username, password string) (model *TokenResponse, err error)

TokenResourceOwnerPasswordCredentials 密码模式获取令牌 / Resource owner password credentials grant username: 用户名 / Resource owner username password: 密码 / Resource owner password

func (*Client) TokenRevocation added in v0.2.0

func (c *Client) TokenRevocation(ctx context.Context, token string, tokenTypeHint ...string) (introspection *IntrospectionResponse, err error)

TokenRevocation 令牌撤销 / Token revocation (RFC 7009) token: 要撤销的令牌 / Token to revoke tokenTypeHint: 令牌类型提示(可选) / Token type hint (optional): access_token or refresh_token

type ClientBasic

type ClientBasic struct {
	ID     string `json:"client_id"`     // 客户端ID / Client identifier
	Secret string `json:"client_secret"` // 客户端密钥 / Client secret
}

ClientBasic 客户端基础信息 / Client basic credentials

func RequestClientBasic

func RequestClientBasic(r *http.Request) (basic *ClientBasic, err error)

RequestClientBasic 获取请求中的客户端信息

type CodeValue

type CodeValue struct {
	ClientID            string   `json:"client_id"`                       // 客户端ID / Client identifier
	OpenID              string   `json:"open_id"`                         // 用户唯一标识 / User unique identifier
	RedirectURI         string   `json:"redirect_uri"`                    // 重定向URI / Redirect URI
	Scope               []string `json:"scope"`                           // 授权范围 / Authorized scopes
	CodeChallenge       string   `json:"code_challenge,omitempty"`        // PKCE code_challenge (RFC 7636)
	CodeChallengeMethod string   `json:"code_challenge_method,omitempty"` // PKCE method: plain or S256 (RFC 7636)
}

CodeValue 授权码存储值 / Authorization code storage value

func (*CodeValue) MarshalBinary added in v0.0.4

func (code *CodeValue) MarshalBinary() ([]byte, error)

MarshalBinary 序列化为JSON二进制 / Serialize to JSON binary

func (*CodeValue) UnmarshalBinary added in v0.0.4

func (code *CodeValue) UnmarshalBinary(data []byte) error

UnmarshalBinary 从JSON二进制反序列化 / Deserialize from JSON binary

type CustomGrantTypeAuthenticationFunc added in v0.3.3

type CustomGrantTypeAuthenticationFunc func(ctx context.Context, client *ClientBasic, req *http.Request) (openID string, err error)

CustomGrantTypeAuthenticationFunc 自定义GrantType身份验证委托

type DefaultAccessToken added in v0.4.2

type DefaultAccessToken struct {
	AccessTokener
	JwtVerifyKey []byte     // 静态密钥 / Static key
	JwtKeyFunc   JwtKeyFunc // 动态密钥函数,优先级高于静态密钥 / Dynamic key function, takes precedence over static key
}

func NewDefaultAccessToken added in v0.4.2

func NewDefaultAccessToken(jwtVerifyKey []byte) *DefaultAccessToken

NewDefaultAccessToken 创建默认AccessToken处理器(静态密钥) Create default AccessToken handler with static key

func NewMultiTenantAccessToken added in v0.5.0

func NewMultiTenantAccessToken(jwtKeyFunc JwtKeyFunc) *DefaultAccessToken

NewMultiTenantAccessToken 创建多租户AccessToken处理器(动态密钥) Create multi-tenant AccessToken handler with dynamic key 示例 / Example:

NewMultiTenantAccessToken(func(ctx context.Context, issuer string) []byte {
    // 根据 issuer 从数据库/配置中获取对应租户的密钥
    // Get tenant's key from database/config based on issuer
    return getTenantJwtKey(issuer)
})

func (*DefaultAccessToken) Generate added in v0.4.2

func (d *DefaultAccessToken) Generate(ctx context.Context, issuer, clientID, scope, openID string, code *CodeValue) (token *TokenResponse, err error)

Generate 生成AccessToken

func (*DefaultAccessToken) Parse added in v0.4.2

func (d *DefaultAccessToken) Parse(ctx context.Context, accessToken string) (claims *JwtClaims, err error)

Parse 解析AccessToken

func (*DefaultAccessToken) Refresh added in v0.4.2

func (d *DefaultAccessToken) Refresh(ctx context.Context, clientID, refreshToken string) (token *TokenResponse, err error)

Refresh 刷新AccessToken

type DefaultLogger

type DefaultLogger struct{}

DefaultLogger ...

func (*DefaultLogger) Debugf

func (*DefaultLogger) Debugf(_ context.Context, format string, args ...interface{})

Debugf ...

func (*DefaultLogger) Debugln

func (*DefaultLogger) Debugln(_ context.Context, args ...interface{})

Debugln ...

func (*DefaultLogger) Errorf

func (*DefaultLogger) Errorf(_ context.Context, format string, args ...interface{})

Errorf ...

func (*DefaultLogger) Errorln

func (*DefaultLogger) Errorln(_ context.Context, args ...interface{})

Errorln ...

type DeviceAuthorizationResponse added in v0.2.0

type DeviceAuthorizationResponse struct {
	DeviceCode              string `json:"device_code"`                         // 设备码 / Device verification code
	UserCode                string `json:"user_code"`                           // 用户码 / User verification code
	VerificationURI         string `json:"verification_uri"`                    // 验证URI / Verification URI
	VerificationURIComplete string `json:"verification_uri_complete,omitempty"` // 完整验证URI / Complete verification URI with user code
	ExpiresIn               int64  `json:"expires_in"`                          // 过期时间(秒) / Expiration time in seconds
	Interval                int    `json:"interval"`                            // 轮询间隔(秒) / Polling interval in seconds
}

DeviceAuthorizationResponse 设备授权响应结构 / Device authorization response (RFC 8628)

type DeviceCodeValue added in v0.2.0

type DeviceCodeValue struct {
	OpenID string   `json:"open_id"` // 用户唯一标识 / User unique identifier
	Scope  []string `json:"scope"`   // 授权范围 / Authorized scopes
}

DeviceCodeValue 设备码存储值 / Device code storage value

func (*DeviceCodeValue) MarshalBinary added in v0.2.0

func (code *DeviceCodeValue) MarshalBinary() ([]byte, error)

MarshalBinary 序列化为JSON二进制 / Serialize to JSON binary

func (*DeviceCodeValue) UnmarshalBinary added in v0.2.0

func (code *DeviceCodeValue) UnmarshalBinary(data []byte) error

UnmarshalBinary 从JSON二进制反序列化 / Deserialize from JSON binary

type ErrorResponse

type ErrorResponse struct {
	Error string `json:"error"` // 错误码 / Error code
}

ErrorResponse 错误响应结构 / Error response structure

type GenerateAccessTokenFunc added in v0.1.0

type GenerateAccessTokenFunc func(ctx context.Context, issuer, clientID, scope, openID string, code *CodeValue) (token *TokenResponse, err error)

GenerateAccessTokenFunc 生成AccessToken委托

func NewDefaultGenerateAccessToken added in v0.1.0

func NewDefaultGenerateAccessToken(jwtVerifyKey []byte) GenerateAccessTokenFunc

NewDefaultGenerateAccessToken 创建默认生成AccessToken方法

type GenerateCodeFunc

type GenerateCodeFunc func(ctx context.Context, clientID, openID, redirectURI string, scope []string, codeChallenge, codeChallengeMethod string) (code string, err error)

GenerateCodeFunc 生成Code委托 支持 PKCE (RFC 7636):codeChallenge 和 codeChallengeMethod 用于公开客户端安全增强

type GenerateDeviceAuthorizationFunc added in v0.2.0

type GenerateDeviceAuthorizationFunc func(ctx context.Context, issuer, verificationURI, clientID string, scope []string) (resp *DeviceAuthorizationResponse, err error)

GenerateDeviceAuthorizationFunc 生成设备授权

type IntrospectionResponse added in v0.2.0

type IntrospectionResponse struct {
	Active   bool   `json:"active"`              // 令牌是否有效 / Whether the token is active
	ClientID string `json:"client_id,omitempty"` // 客户端ID / Client identifier
	Username string `json:"username,omitempty"`  // 用户名 / Resource owner username
	Scope    string `json:"scope,omitempty"`     // 授权范围 / Token scope
	Sub      string `json:"sub,omitempty"`       // 主体 / Subject (user identifier)
	Aud      string `json:"aud,omitempty"`       // 受众 / Audience
	Iss      int64  `json:"iss,omitempty"`       // 颁发者 / Issuer
	Exp      int64  `json:"exp,omitempty"`       // 过期时间 / Expiration time
}

IntrospectionResponse 令牌内省响应结构 / Token introspection response (RFC 7662)

type IssuerFunc added in v0.5.0

type IssuerFunc func(ctx context.Context, req IssuerRequest) string

IssuerFunc 动态获取Issuer的函数类型,用于SaaS多租户场景 Dynamic Issuer function type for SaaS multi-tenant scenarios

type IssuerRequest added in v0.5.0

type IssuerRequest struct {
	Host   string // 请求的Host,如 "tenant1.example.com"
	Scheme string // 协议,"http" 或 "https"
}

IssuerRequest 用于动态获取Issuer的请求信息,只包含必要字段 Request info for dynamic Issuer retrieval, contains only necessary fields

func DefaultIssuerRequestFunc added in v0.5.0

func DefaultIssuerRequestFunc(r *http.Request) IssuerRequest

DefaultIssuerRequestFunc 默认的IssuerRequest提取函数 Default IssuerRequest extraction function

func IssuerRequestFromContext added in v0.5.0

func IssuerRequestFromContext(ctx context.Context) (IssuerRequest, error)

IssuerRequestFromContext 从上下文中获取IssuerRequest / Get IssuerRequest from context

func ProxyIssuerRequestFunc added in v0.5.0

func ProxyIssuerRequestFunc(r *http.Request) IssuerRequest

ProxyIssuerRequestFunc 支持反向代理的IssuerRequest提取函数 IssuerRequest extraction function with reverse proxy support 从 X-Forwarded-Proto 和 X-Forwarded-Host 头部获取信息

type IssuerRequestFunc added in v0.5.0

type IssuerRequestFunc func(r *http.Request) IssuerRequest

IssuerRequestFunc 从HTTP请求提取IssuerRequest的函数类型 Function type for extracting IssuerRequest from HTTP request

type JwtClaims

type JwtClaims struct {
	JwtStandardClaims
	Scope string `json:"scope,omitempty"`
}

JwtClaims 在jwt标准上的扩展

func NewJwtClaims

func NewJwtClaims(issuer, audience, scope, openID string) *JwtClaims

NewJwtClaims ...

func ParseHS256JwtClaimsToken added in v0.2.1

func ParseHS256JwtClaimsToken(token string, jwtVerifyKey []byte) (claims *JwtClaims, err error)

ParseHS256JwtClaimsToken ...

func ParseHS256JwtClaimsTokenUnverified added in v0.5.0

func ParseHS256JwtClaimsTokenUnverified(token string) (claims *JwtClaims, err error)

ParseHS256JwtClaimsTokenUnverified 解析JWT Token但不验证签名,用于先获取issuer Parse JWT Token without verifying signature, used to get issuer first

func ParseJwtClaimsToken added in v0.2.1

func ParseJwtClaimsToken(token string, algorithm string, key interface{}) (claims *JwtClaims, err error)

ParseJwtClaimsToken ...

func (*JwtClaims) VerifyScope added in v0.2.0

func (c *JwtClaims) VerifyScope(scope string, req bool) bool

VerifyScope Compares the aud claim against cmp. If required is false, this method will return true if the value matches or is unset 如果required为false,如果值匹配或未设置,此方法将返回true

type JwtKeyFunc added in v0.5.0

type JwtKeyFunc func(ctx context.Context, issuer string) []byte

JwtKeyFunc 动态获取JWT密钥的函数类型,用于SaaS多租户场景 Dynamic JWT key function type for SaaS multi-tenant scenarios ctx 中包含 IssuerRequest 信息,可通过 IssuerRequestFromContext 获取

type JwtStandardClaims added in v0.2.0

type JwtStandardClaims struct {
	Audience  []string `json:"aud,omitempty"`
	ExpiresAt int64    `json:"exp,omitempty"`
	ID        string   `json:"jti,omitempty"`
	IssuedAt  int64    `json:"iat,omitempty"`
	Issuer    string   `json:"iss,omitempty"`
	NotBefore int64    `json:"nbf,omitempty"`
	Subject   string   `json:"sub,omitempty"`
}

JwtStandardClaims as referenced at https://tools.ietf.org/html/rfc7519#section-4.1

func ParseJwtStandardClaimsToken added in v0.2.1

func ParseJwtStandardClaimsToken(token string, algorithm string, key interface{}) (claims *JwtStandardClaims, err error)

ParseJwtStandardClaimsToken ...

func (JwtStandardClaims) Valid added in v0.2.0

func (c JwtStandardClaims) Valid() error

Valid time based claims "exp, iat, nbf". There is no accounting for clock skew. As well, if any of the above claims are not in the token, it will still be considered a valid claim.

func (*JwtStandardClaims) VerifyAudience added in v0.2.0

func (c *JwtStandardClaims) VerifyAudience(cmp []string, req bool) bool

VerifyAudience Compares the aud claim against cmp. If required is false, this method will return true if the value matches or is unset 如果required为false,如果值匹配或未设置,此方法将返回true

func (*JwtStandardClaims) VerifyExpiresAt added in v0.2.0

func (c *JwtStandardClaims) VerifyExpiresAt(cmp int64, req bool) bool

VerifyExpiresAt Compares the exp claim against cmp. If required is false, this method will return true if the value matches or is unset 如果required为false,如果值匹配或未设置,此方法将返回true

func (*JwtStandardClaims) VerifyIssuedAt added in v0.2.0

func (c *JwtStandardClaims) VerifyIssuedAt(cmp int64, req bool) bool

VerifyIssuedAt Compares the iat claim against cmp. If required is false, this method will return true if the value matches or is unset 如果required为false,如果值匹配或未设置,此方法将返回true

func (*JwtStandardClaims) VerifyIssuer added in v0.2.0

func (c *JwtStandardClaims) VerifyIssuer(cmp string, req bool) bool

VerifyIssuer Compares the iss claim against cmp. If required is false, this method will return true if the value matches or is unset 如果required为false,如果值匹配或未设置,此方法将返回true

func (*JwtStandardClaims) VerifyNotBefore added in v0.2.0

func (c *JwtStandardClaims) VerifyNotBefore(cmp int64, req bool) bool

VerifyNotBefore Compares the nbf claim against cmp. If required is false, this method will return true if the value matches or is unset 如果required为false,如果值匹配或未设置,此方法将返回true

type Logger

type Logger interface {
	// Debugf 测试
	Debugf(ctx context.Context, format string, args ...interface{})
	// Debugln 测试
	Debugln(ctx context.Context, args ...interface{})
	// Errorf 错误
	Errorf(ctx context.Context, format string, args ...interface{})
	// Errorln 错误
	Errorln(ctx context.Context, args ...interface{})
}

Logger logger

type ParseAccessTokenFunc added in v0.1.0

type ParseAccessTokenFunc func(ctx context.Context, accessToken string) (claims *JwtClaims, err error)

ParseAccessTokenFunc 解析AccessToken为JwtClaims委托

func NewDefaultParseAccessToken added in v0.1.0

func NewDefaultParseAccessToken(jwtVerifyKey []byte) ParseAccessTokenFunc

NewDefaultParseAccessToken 创建默认解析AccessToken方法

type RefreshAccessTokenFunc added in v0.1.0

type RefreshAccessTokenFunc func(ctx context.Context, clientID, refreshToken string) (token *TokenResponse, err error)

RefreshAccessTokenFunc 刷新AccessToken委托

func NewDefaultRefreshAccessToken added in v0.1.0

func NewDefaultRefreshAccessToken(jwtVerifyKey []byte) RefreshAccessTokenFunc

NewDefaultRefreshAccessToken 创建默认刷新AccessToken方法 Create default refresh access token method

刷新令牌验证逻辑: 1. 验证 refresh_token 签名和格式 2. 验证 refresh_token 的 Audience (clientID) 与请求的 clientID 匹配 3. 验证 refresh_token 的 Scope 为 refresh_token 4. 验证原 access_token 的 Audience (clientID) 与请求的 clientID 匹配

Refresh token validation logic: 1. Verify refresh_token signature and format 2. Verify refresh_token Audience (clientID) matches requesting clientID 3. Verify refresh_token Scope is refresh_token 4. Verify original access_token Audience (clientID) matches requesting clientID

type Server

type Server struct {
	VerifyClient                VerifyClientFunc
	VerifyClientID              VerifyClientIDFunc
	VerifyScope                 VerifyScopeFunc
	VerifyGrantType             VerifyGrantTypeFunc
	VerifyPassword              VerifyPasswordFunc
	VerifyRedirectURI           VerifyRedirectURIFunc
	GenerateCode                GenerateCodeFunc
	VerifyCode                  VerifyCodeFunc
	GenerateDeviceAuthorization GenerateDeviceAuthorizationFunc
	VerifyDeviceCode            VerifyDeviceCodeFunc
	VerifyIntrospectionToken    VerifyIntrospectionTokenFunc
	TokenRevocation             TokenRevocationFunc

	AccessToken AccessTokener
	// contains filtered or unexported fields
}

Server OAuth2Server

func NewServer

func NewServer(opts ...ServerOption) *Server

NewServer 创建服务器

func (*Server) HandleAuthorize

func (srv *Server) HandleAuthorize(w http.ResponseWriter, r *http.Request)

HandleAuthorize 处理Authorize

func (*Server) HandleDeviceAuthorization added in v0.2.0

func (srv *Server) HandleDeviceAuthorization(w http.ResponseWriter, r *http.Request)

HandleDeviceAuthorization 处理DeviceAuthorization https://tools.ietf.org/html/rfc8628#section-3.1

func (*Server) HandleToken

func (srv *Server) HandleToken(w http.ResponseWriter, r *http.Request)

HandleToken 处理Token

func (*Server) HandleTokenIntrospection added in v0.2.0

func (srv *Server) HandleTokenIntrospection(w http.ResponseWriter, r *http.Request)

HandleTokenIntrospection 处理内省端点 https://tools.ietf.org/html/rfc7662#section-2.1

func (*Server) HandleTokenRevocation added in v0.2.0

func (srv *Server) HandleTokenRevocation(w http.ResponseWriter, r *http.Request)

HandleTokenRevocation 处理Token销毁 https://tools.ietf.org/html/rfc7009

func (*Server) Init deprecated

func (srv *Server) Init(opts ...ServerOption)

Init 初始化服务器,验证必要的函数是否已设置,未设置则panic / Initialize server, panic if required functions are not set

Deprecated: 推荐使用 InitWithError 方法,它返回错误而不是panic / Use InitWithError instead, which returns error instead of panic

func (*Server) InitWithError added in v0.4.6

func (srv *Server) InitWithError(opts ...ServerOption) error

InitWithError 初始化服务器,验证必要的函数是否已设置,返回错误 / Initialize server, return error if required functions are not set

type ServerOption added in v0.2.0

type ServerOption func(*ServerOptions)

ServerOption 为可选参数赋值的函数

func ServerCustomGrantTypeAuthentication added in v0.3.3

func ServerCustomGrantTypeAuthentication(customGrantTypeAuthentication map[string]CustomGrantTypeAuthenticationFunc) ServerOption

ServerCustomGrantTypeAuthentication 设置自定义授权类型认证函数 / Set custom grant type authentication functions

func ServerCustomGrantTypeEnabled added in v0.3.3

func ServerCustomGrantTypeEnabled(customGrantTypeEnabled bool) ServerOption

ServerCustomGrantTypeEnabled 启用自定义授权类型 / Enable custom grant types

func ServerDeviceAuthorizationEndpointEnabled added in v0.2.0

func ServerDeviceAuthorizationEndpointEnabled(deviceAuthorizationEndpointEnabled bool) ServerOption

ServerDeviceAuthorizationEndpointEnabled 启用设备授权端点 / Enable device authorization endpoint (RFC 8628)

func ServerDeviceVerificationURI added in v0.2.0

func ServerDeviceVerificationURI(deviceVerificationURI string) ServerOption

ServerDeviceVerificationURI 设置设备验证URI / Set device verification URI

func ServerIntrospectEndpointEnabled added in v0.2.0

func ServerIntrospectEndpointEnabled(introspectEndpointEnabled bool) ServerOption

ServerIntrospectEndpointEnabled 启用令牌内省端点 / Enable token introspection endpoint (RFC 7662)

func ServerIssuer added in v0.2.0

func ServerIssuer(issuer string) ServerOption

ServerIssuer 设置JWT颁发者 / Set JWT issuer

func ServerIssuerFunc added in v0.5.0

func ServerIssuerFunc(issuerFunc IssuerFunc) ServerOption

ServerIssuerFunc 设置动态JWT颁发者函数,用于SaaS多租户场景 Set dynamic JWT issuer function for SaaS multi-tenant scenarios 示例 / Example:

ServerIssuerFunc(func(ctx context.Context, req oauth2.IssuerRequest) string {
    // 基于请求Host动态获取Issuer / Get Issuer dynamically based on request Host
    return fmt.Sprintf("%s://%s", req.Scheme, req.Host)
})

func ServerIssuerRequestFunc added in v0.5.0

func ServerIssuerRequestFunc(issuerRequestFunc IssuerRequestFunc) ServerOption

ServerIssuerRequestFunc 设置从HTTP请求提取IssuerRequest的函数 Set function for extracting IssuerRequest from HTTP request 示例 / Example:

// 使用内置的反向代理支持函数
ServerIssuerRequestFunc(oauth2.ProxyIssuerRequestFunc)

// 或自定义提取逻辑
ServerIssuerRequestFunc(func(r *http.Request) oauth2.IssuerRequest {
    return oauth2.IssuerRequest{
        Host:   r.Header.Get("X-Real-Host"),
        Scheme: r.Header.Get("X-Forwarded-Proto"),
    }
})

func ServerLogger added in v0.2.0

func ServerLogger(log Logger) ServerOption

ServerLogger 设置服务器日志记录器 / Set server logger

func ServerTokenRevocationEnabled added in v0.2.0

func ServerTokenRevocationEnabled(tokenRevocationEnabled bool) ServerOption

ServerTokenRevocationEnabled 启用令牌撤销端点 / Enable token revocation endpoint (RFC 7009)

type ServerOptions added in v0.2.0

type ServerOptions struct {
	Log                                Logger
	Issuer                             string            // 静态Issuer / Static Issuer
	IssuerFunc                         IssuerFunc        // 动态Issuer函数,优先级高于静态Issuer / Dynamic Issuer function, takes precedence over static Issuer
	IssuerRequestFunc                  IssuerRequestFunc // 从HTTP请求提取IssuerRequest的函数 / Function to extract IssuerRequest from HTTP request
	DeviceAuthorizationEndpointEnabled bool              // https://tools.ietf.org/html/rfc8628
	DeviceVerificationURI              string            // https://tools.ietf.org/html/rfc8628#section-3.2
	IntrospectEndpointEnabled          bool              // https://tools.ietf.org/html/rfc7662
	TokenRevocationEnabled             bool              // https://tools.ietf.org/html/rfc7009
	CustomGrantTypeEnabled             bool              // 自定义身份验证
	CustomGrantTypeAuthentication      map[string]CustomGrantTypeAuthenticationFunc
}

ServerOptions server可选参数列表

func (*ServerOptions) GetIssuerFromContext added in v0.5.0

func (o *ServerOptions) GetIssuerFromContext(ctx context.Context) string

GetIssuerFromContext 从上下文获取Issuer,用于内部调用 Get Issuer from context, for internal use

func (*ServerOptions) GetIssuerRequest added in v0.5.0

func (o *ServerOptions) GetIssuerRequest(r *http.Request) IssuerRequest

GetIssuerRequest 从HTTP请求获取IssuerRequest Get IssuerRequest from HTTP request

type TokenResponse

type TokenResponse struct {
	AccessToken  string      `json:"access_token"`            // 访问令牌 / Access token
	TokenType    string      `json:"token_type,omitempty"`    // 令牌类型 / Token type (e.g., Bearer)
	ExpiresIn    int64       `json:"expires_in"`              // 过期时间(秒) / Expiration time in seconds
	RefreshToken string      `json:"refresh_token,omitempty"` // 刷新令牌 / Refresh token
	Data         interface{} `json:"data,omitempty"`          // 自定义数据 / Custom data
	Scope        string      `json:"scope,omitempty"`         // 授权范围 / Authorized scope
	IDToken      string      `json:"id_token,omitempty"`      // ID令牌 / ID token (OpenID Connect)
}

TokenResponse 令牌响应结构 / Token response structure

type TokenRevocationFunc added in v0.2.0

type TokenRevocationFunc func(ctx context.Context, token, clientID string, tokenTypeHint ...string)

TokenRevocationFunc Token撤销委托 https://tools.ietf.org/html/rfc7009#section-2.2

type VerifyClientFunc

type VerifyClientFunc func(ctx context.Context, basic *ClientBasic) (err error)

VerifyClientFunc 验证客户端委托

type VerifyClientIDFunc added in v0.3.0

type VerifyClientIDFunc func(ctx context.Context, clientID string) (err error)

VerifyClientIDFunc 验证客户端ID委托

type VerifyCodeFunc

type VerifyCodeFunc func(ctx context.Context, code, clientID, redirectURI string) (value *CodeValue, err error)

VerifyCodeFunc 验证Code委托

type VerifyDeviceCodeFunc added in v0.2.0

type VerifyDeviceCodeFunc func(ctx context.Context, deviceCode, clientID string) (value *DeviceCodeValue, err error)

VerifyDeviceCodeFunc 验证DeviceCode委托

type VerifyGrantTypeFunc added in v0.4.0

type VerifyGrantTypeFunc func(ctx context.Context, clientID, grantType string) (err error)

VerifyGrantTypeFunc 验证授权类型委托

type VerifyIntrospectionTokenFunc added in v0.2.0

type VerifyIntrospectionTokenFunc func(ctx context.Context, token, clientID string, tokenTypeHint ...string) (resp *IntrospectionResponse, err error)

VerifyIntrospectionTokenFunc 验证IntrospectionToken委托

type VerifyPasswordFunc

type VerifyPasswordFunc func(ctx context.Context, clientID, username, password string) (openID string, err error)

VerifyPasswordFunc 验证账号密码委托

type VerifyRedirectURIFunc added in v0.0.3

type VerifyRedirectURIFunc func(ctx context.Context, clientID, redirectURI string) (err error)

VerifyRedirectURIFunc 验证RedirectURI委托

type VerifyScopeFunc added in v0.0.3

type VerifyScopeFunc func(ctx context.Context, scope []string, clientID string) (err error)

VerifyScopeFunc 验证范围委托

Directories

Path Synopsis
examples module

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL