Documentation
¶
Index ¶
- Variables
- func Init(configs ...Config) error
- func IsPKCESupported(provider string) bool
- func IsRetryable(err error) bool
- func PKCEParams(pkce *PKCEChallenge) map[string]string
- func PKCETokenParams(pkce *PKCEChallenge) map[string]string
- func Reset()
- func ValidatePKCEChallenge(verifier, challenge, method string) bool
- type AuthorizationRequest
- type AuthorizationResponse
- type Builder
- type Config
- type GitHubProvider
- func (g *GitHubProvider) Exchange(ctx context.Context, code string, pkce *PKCEChallenge) (*Token, error)
- func (g *GitHubProvider) GetAuthURL(state string, pkce *PKCEChallenge) string
- func (g *GitHubProvider) GetUserInfo(ctx context.Context, accessToken string) (*UserInfo, error)
- func (g *GitHubProvider) Name() string
- func (g *GitHubProvider) RefreshToken(ctx context.Context, refreshToken string) (*Token, error)
- func (g *GitHubProvider) RevokeToken(ctx context.Context, token string) error
- func (g *GitHubProvider) SetHTTPClient(client HTTPClient)
- func (g *GitHubProvider) SupportsPKCE() bool
- func (g *GitHubProvider) SupportsRefresh() bool
- func (g *GitHubProvider) ValidateConfig() error
- type GitHubUser
- type HTTPClient
- type MemorySessionStore
- type MemoryTokenStore
- type OAuthError
- type PKCEChallenge
- type Provider
- func NewAppleProvider(config ProviderConfig) (Provider, error)
- func NewCustomProvider(config ProviderConfig) (Provider, error)
- func NewGitHubProvider(config ProviderConfig) (Provider, error)
- func NewGoogleProvider(config ProviderConfig) (Provider, error)
- func NewTwitterProvider(config ProviderConfig) (Provider, error)
- type ProviderConfig
- type SecureStateGenerator
- type Service
- func (s *Service) Config() Config
- func (s *Service) Exchange(ctx context.Context, code, state string) (*Token, error)
- func (s *Service) GetAuthURL(ctx context.Context) (string, error)
- func (s *Service) GetUserInfo(ctx context.Context, accessToken string) (*UserInfo, error)
- func (s *Service) Provider() Provider
- func (s *Service) RefreshToken(ctx context.Context, refreshToken string) (*Token, error)
- func (s *Service) ValidateState(ctx context.Context, state string) error
- type SessionData
- type SessionStore
- type StateGenerator
- type Token
- type TokenStore
- type UUIDStateGenerator
- type UserInfo
Constants ¶
This section is empty.
Variables ¶
var ( // ErrInvalidConfig indicates invalid configuration ErrInvalidConfig = errors.New("invalid configuration") // ErrNotInitialized indicates the service hasn't been initialized ErrNotInitialized = errors.New("oauth service not initialized") // ErrProviderNotFound indicates the requested provider doesn't exist ErrProviderNotFound = errors.New("oauth provider not found") // ErrInvalidState indicates state parameter mismatch (CSRF protection) ErrInvalidState = errors.New("invalid state parameter") // ErrTokenExpired indicates the token has expired ErrTokenExpired = errors.New("token expired") // ErrNoRefreshToken indicates no refresh token is available ErrNoRefreshToken = errors.New("no refresh token available") // ErrPKCENotSupported indicates PKCE is not supported by provider ErrPKCENotSupported = errors.New("PKCE not supported by provider") // ErrSessionNotFound indicates session data not found ErrSessionNotFound = errors.New("session not found") // ErrInvalidCode indicates invalid authorization code ErrInvalidCode = errors.New("invalid authorization code") // ErrNetworkError indicates a network error occurred ErrNetworkError = errors.New("network error") // ErrInvalidResponse indicates invalid response from provider ErrInvalidResponse = errors.New("invalid response from provider") // ErrAccessDenied indicates user denied access ErrAccessDenied = errors.New("access denied by user") // ErrUnsupportedResponseType indicates unsupported response type ErrUnsupportedResponseType = errors.New("unsupported response type") // ErrInvalidScope indicates invalid or unauthorized scope ErrInvalidScope = errors.New("invalid scope") // ErrServerError indicates provider server error ErrServerError = errors.New("provider server error") ErrTemporarilyUnavailable = errors.New("service temporarily unavailable") )
Package-level errors
Functions ¶
func IsPKCESupported ¶
IsPKCESupported checks if a provider supports PKCE based on provider name
func PKCEParams ¶
func PKCEParams(pkce *PKCEChallenge) map[string]string
PKCEParams returns URL parameters for PKCE
func PKCETokenParams ¶
func PKCETokenParams(pkce *PKCEChallenge) map[string]string
PKCETokenParams returns token exchange parameters for PKCE
func ValidatePKCEChallenge ¶
ValidatePKCEChallenge validates that a verifier matches a challenge
Types ¶
type AuthorizationRequest ¶
type AuthorizationRequest struct {
State string
PKCEChallenge *PKCEChallenge
RedirectURL string
Scopes []string
ExtraParams map[string]string
}
AuthorizationRequest represents an OAuth authorization request
type AuthorizationResponse ¶
AuthorizationResponse represents the response from an OAuth authorization
type Builder ¶
type Builder struct {
// contains filtered or unexported fields
}
Builder pattern for custom prefixes
func WithPrefix ¶
WithPrefix creates a new Builder with the specified prefix
type Config ¶
type Config struct {
// Provider specifies the OAuth provider (google, github, apple, twitter, custom)
Provider string `env:"OAUTH_PROVIDER,default:google"`
// ClientID is the OAuth application's client ID
ClientID string `env:"OAUTH_CLIENT_ID,required"`
// ClientSecret is the OAuth application's client secret
ClientSecret string `env:"OAUTH_CLIENT_SECRET,required"`
// RedirectURL is the callback URL after authentication
RedirectURL string `env:"OAUTH_REDIRECT_URL,required"`
// Scopes is a comma-separated list of OAuth scopes
Scopes string `env:"OAUTH_SCOPES,default:openid,profile,email"`
// State is the default state parameter for CSRF protection
State string `env:"OAUTH_STATE"`
// StateGenerator defines how to generate state tokens (uuid, secure, custom)
StateGenerator string `env:"OAUTH_STATE_GENERATOR,default:secure"`
// PKCEEnabled enables PKCE flow for enhanced security
PKCEEnabled bool `env:"OAUTH_PKCE_ENABLED,default:true"`
// PKCEMethod is the PKCE challenge method (S256 or plain)
PKCEMethod string `env:"OAUTH_PKCE_METHOD,default:S256"`
// TokenCacheDuration is how long to cache tokens
TokenCacheDuration time.Duration `env:"OAUTH_TOKEN_CACHE_DURATION,default:1h"`
// HTTPTimeout is the timeout for HTTP requests
HTTPTimeout time.Duration `env:"OAUTH_HTTP_TIMEOUT,default:30s"`
// Debug enables debug logging
Debug bool `env:"OAUTH_DEBUG,default:false"`
// Custom provider configuration (for generic OAuth2 providers)
AuthURL string `env:"OAUTH_AUTH_URL"`
TokenURL string `env:"OAUTH_TOKEN_URL"`
UserInfoURL string `env:"OAUTH_USERINFO_URL"`
// Provider-specific configurations
AppleTeamID string `env:"OAUTH_APPLE_TEAM_ID"`
AppleKeyID string `env:"OAUTH_APPLE_KEY_ID"`
ApplePrivateKey string `env:"OAUTH_APPLE_PRIVATE_KEY"`
// Twitter API version (1.1 or 2)
TwitterAPIVersion string `env:"OAUTH_TWITTER_API_VERSION,default:2"`
}
Config defines the OAuth service configuration
type GitHubProvider ¶
type GitHubProvider struct {
// contains filtered or unexported fields
}
GitHubProvider implements OAuth provider for GitHub
func NewGitHub ¶
func NewGitHub(config ProviderConfig) *GitHubProvider
NewGitHub creates a new GitHub OAuth provider
func (*GitHubProvider) Exchange ¶
func (g *GitHubProvider) Exchange(ctx context.Context, code string, pkce *PKCEChallenge) (*Token, error)
Exchange exchanges an authorization code for tokens
func (*GitHubProvider) GetAuthURL ¶
func (g *GitHubProvider) GetAuthURL(state string, pkce *PKCEChallenge) string
GetAuthURL returns the authorization URL with PKCE parameters if enabled
func (*GitHubProvider) GetUserInfo ¶
GetUserInfo retrieves user information using the access token
func (*GitHubProvider) RefreshToken ¶
RefreshToken refreshes the access token
func (*GitHubProvider) RevokeToken ¶
func (g *GitHubProvider) RevokeToken(ctx context.Context, token string) error
RevokeToken revokes the access token
func (*GitHubProvider) SetHTTPClient ¶
func (g *GitHubProvider) SetHTTPClient(client HTTPClient)
SetHTTPClient sets a custom HTTP client
func (*GitHubProvider) SupportsPKCE ¶
func (g *GitHubProvider) SupportsPKCE() bool
SupportsPKCE indicates if the provider supports PKCE
func (*GitHubProvider) SupportsRefresh ¶
func (g *GitHubProvider) SupportsRefresh() bool
SupportsRefresh indicates if the provider supports token refresh
func (*GitHubProvider) ValidateConfig ¶
func (g *GitHubProvider) ValidateConfig() error
ValidateConfig validates the provider configuration
type GitHubUser ¶
type GitHubUser struct {
ID int64 `json:"id"`
Login string `json:"login"`
Email string `json:"email"`
Name string `json:"name"`
AvatarURL string `json:"avatar_url"`
Bio string `json:"bio"`
Company string `json:"company"`
Location string `json:"location"`
Blog string `json:"blog"`
TwitterUsername string `json:"twitter_username"`
}
GitHubUser represents the user data returned by GitHub
type HTTPClient ¶
HTTPClient interface for mocking in tests
type MemorySessionStore ¶
type MemorySessionStore struct {
// contains filtered or unexported fields
}
MemorySessionStore implements SessionStore with in-memory storage
func NewMemorySessionStore ¶
func NewMemorySessionStore(ttl time.Duration) *MemorySessionStore
func (*MemorySessionStore) Delete ¶
func (s *MemorySessionStore) Delete(ctx context.Context, key string) error
func (*MemorySessionStore) Retrieve ¶
func (s *MemorySessionStore) Retrieve(ctx context.Context, key string) (*SessionData, error)
func (*MemorySessionStore) Store ¶
func (s *MemorySessionStore) Store(ctx context.Context, key string, data *SessionData) error
type MemoryTokenStore ¶
type MemoryTokenStore struct {
// contains filtered or unexported fields
}
MemoryTokenStore implements TokenStore with in-memory storage
func NewMemoryTokenStore ¶
func NewMemoryTokenStore(ttl time.Duration) *MemoryTokenStore
func (*MemoryTokenStore) Delete ¶
func (s *MemoryTokenStore) Delete(ctx context.Context, key string) error
type OAuthError ¶
type OAuthError struct {
Code string // OAuth error code (e.g., "invalid_request")
Description string // Human-readable error description
URI string // Optional URI with error details
Provider string // Provider where error occurred
Err error // Underlying error
}
OAuthError represents a detailed OAuth error
func NewOAuthError ¶
func NewOAuthError(provider, code, description string) *OAuthError
NewOAuthError creates a new OAuth error
func ParseOAuthError ¶
func ParseOAuthError(provider string, code, description, uri string) *OAuthError
ParseOAuthError parses OAuth error from response
func WrapOAuthError ¶
func WrapOAuthError(provider string, err error) *OAuthError
WrapOAuthError wraps an error with OAuth context
func (*OAuthError) Is ¶
func (e *OAuthError) Is(target error) bool
Is checks if the error matches a target error
type PKCEChallenge ¶
type PKCEChallenge struct {
Verifier string `json:"verifier"`
Challenge string `json:"challenge"`
ChallengeMethod string `json:"challenge_method"`
}
PKCEChallenge represents PKCE challenge parameters
func GeneratePKCEChallenge ¶
func GeneratePKCEChallenge(method string) (*PKCEChallenge, error)
GeneratePKCEChallenge generates a PKCE challenge with verifier and challenge
type Provider ¶
type Provider interface {
// GetAuthURL returns the authorization URL with PKCE parameters if enabled
GetAuthURL(state string, pkce *PKCEChallenge) string
// Exchange exchanges an authorization code for tokens
Exchange(ctx context.Context, code string, pkce *PKCEChallenge) (*Token, error)
// RefreshToken refreshes an access token using a refresh token
RefreshToken(ctx context.Context, refreshToken string) (*Token, error)
// GetUserInfo retrieves user information using an access token
GetUserInfo(ctx context.Context, accessToken string) (*UserInfo, error)
// Name returns the provider name
Name() string
// SupportsRefresh indicates if the provider supports token refresh
SupportsRefresh() bool
// SupportsPKCE indicates if the provider supports PKCE
SupportsPKCE() bool
}
Provider defines the interface that all OAuth providers must implement
func NewAppleProvider ¶
func NewAppleProvider(config ProviderConfig) (Provider, error)
func NewCustomProvider ¶
func NewCustomProvider(config ProviderConfig) (Provider, error)
func NewGitHubProvider ¶
func NewGitHubProvider(config ProviderConfig) (Provider, error)
func NewGoogleProvider ¶
func NewGoogleProvider(config ProviderConfig) (Provider, error)
func NewTwitterProvider ¶
func NewTwitterProvider(config ProviderConfig) (Provider, error)
type ProviderConfig ¶
type ProviderConfig struct {
ClientID string
ClientSecret string
RedirectURL string
Scopes []string
AuthURL string
TokenURL string
UserInfoURL string
HTTPClient HTTPClient
Debug bool
// Apple-specific
TeamID string
KeyID string
PrivateKey string
// Twitter-specific
APIVersion string
}
ProviderConfig represents configuration for a specific OAuth provider
type SecureStateGenerator ¶
type SecureStateGenerator struct{}
SecureStateGenerator generates cryptographically secure state tokens
func (*SecureStateGenerator) Generate ¶
func (g *SecureStateGenerator) Generate() (string, error)
type Service ¶
type Service struct {
// contains filtered or unexported fields
}
Service is the main OAuth service
func (*Service) GetAuthURL ¶
GetAuthURL generates an authorization URL
func (*Service) GetUserInfo ¶
GetUserInfo retrieves user information
func (*Service) RefreshToken ¶
RefreshToken refreshes an access token
type SessionData ¶
type SessionData struct {
State string `json:"state"`
PKCEChallenge *PKCEChallenge `json:"pkce_challenge,omitempty"`
CreatedAt time.Time `json:"created_at"`
ExpiresAt time.Time `json:"expires_at"`
Provider string `json:"provider"`
}
SessionData represents OAuth session data that can be stored
func (*SessionData) IsExpired ¶
func (s *SessionData) IsExpired() bool
IsExpired checks if the session data is expired
type SessionStore ¶
type SessionStore interface {
// Store stores session data with a key
Store(ctx context.Context, key string, data *SessionData) error
// Retrieve gets session data by key
Retrieve(ctx context.Context, key string) (*SessionData, error)
// Delete removes session data by key
Delete(ctx context.Context, key string) error
}
SessionStore interface for storing OAuth session data
type StateGenerator ¶
StateGenerator interface for generating state tokens
type Token ¶
type Token struct {
AccessToken string `json:"access_token"`
TokenType string `json:"token_type"`
RefreshToken string `json:"refresh_token,omitempty"`
ExpiresIn int `json:"expires_in,omitempty"`
ExpiresAt time.Time `json:"expires_at,omitempty"`
IDToken string `json:"id_token,omitempty"` // For OpenID Connect
Scope string `json:"scope,omitempty"`
}
Token represents OAuth tokens
func (*Token) TimeUntilExpiry ¶
TimeUntilExpiry returns the duration until the token expires
type TokenStore ¶
type TokenStore interface {
// Store stores a token with a key
Store(ctx context.Context, key string, token *Token) error
// Retrieve gets a token by key
Retrieve(ctx context.Context, key string) (*Token, error)
// Delete removes a token by key
Delete(ctx context.Context, key string) error
}
TokenStore interface for caching OAuth tokens
type UUIDStateGenerator ¶
type UUIDStateGenerator struct{}
UUIDStateGenerator generates UUID-based state tokens
func (*UUIDStateGenerator) Generate ¶
func (g *UUIDStateGenerator) Generate() (string, error)
type UserInfo ¶
type UserInfo struct {
ID string `json:"id"`
Email string `json:"email"`
EmailVerified bool `json:"email_verified"`
Name string `json:"name"`
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
Picture string `json:"picture"`
Locale string `json:"locale"`
Provider string `json:"provider"`
Raw map[string]interface{} `json:"raw"` // Raw response from provider
}
UserInfo represents user information from OAuth providers