oidc

package
v0.45.7 Latest Latest
Warning

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

Go to latest
Published: Oct 29, 2026 License: MIT Imports: 29 Imported by: 0

Documentation

Overview

Package oidc implements generic OpenID Connect support for go-auth.

The package owns issuer discovery, JWKS validation, authorization-code browser SSO orchestration, claim mapping, and provider-neutral identity linking. It deliberately does not depend on go-admin and does not write HTTP cookies directly; browser callbacks return a BrowserSessionResult that host handlers can use with auth.RouteAuthenticator.SetAuthCookie.

Index

Examples

Constants

View Source
const (
	TextCodeOIDCInvalidConfig    = "OIDC_INVALID_CONFIG"
	TextCodeOIDCDiscoveryFailed  = "OIDC_DISCOVERY_FAILED"
	TextCodeOIDCInvalidState     = "OIDC_INVALID_STATE"
	TextCodeOIDCInvalidNonce     = "OIDC_INVALID_NONCE"
	TextCodeOIDCUnsafeRedirect   = "OIDC_UNSAFE_REDIRECT"
	TextCodeOIDCTokenExchange    = "OIDC_TOKEN_EXCHANGE_FAILED" // #nosec G101 -- Error text code, not a credential.
	TextCodeOIDCInvalidIDToken   = "OIDC_INVALID_ID_TOKEN"      // #nosec G101 -- Error text code, not a credential.
	TextCodeOIDCUserInfoFailed   = "OIDC_USERINFO_FAILED"
	TextCodeOIDCLinkingRejected  = "OIDC_LINKING_REJECTED"
	TextCodeOIDCDuplicateSubject = "OIDC_DUPLICATE_SUBJECT"
)
View Source
const (
	DefaultDocumentBodyBytes  int64 = 1 << 20
	DefaultTokenBodyBytes     int64 = 256 << 10
	DefaultEncodedTokenBytes        = 64 << 10
	DefaultCallbackCodeBytes        = 8 << 10
	DefaultCallbackStateBytes       = 1 << 10
	DefaultRedirectBytes            = 8 << 10
	DefaultProviderKeyBytes         = 128
	DefaultJWKSKeys                 = 100
	DefaultRequestTimeout           = 10 * time.Second
)
View Source
const (
	LinkActionExisting      = "existing_subject"
	LinkActionCreated       = "created_user"
	LinkActionEmailFallback = "email_fallback"
	LinkActionRejected      = "rejected"
)
View Source
const (
	DefaultResponseType  = "code"
	DefaultGrantType     = "authorization_code"
	DefaultScopeOpenID   = "openid"
	DefaultStateCapacity = 10_000
)

Variables

View Source
var (
	ErrInvalidConfig = errors.New("oidc configuration is invalid", errors.CategoryValidation).
						WithTextCode(TextCodeOIDCInvalidConfig).
						WithCode(errors.CodeBadRequest)
	ErrDiscoveryFailed = errors.New("oidc discovery failed", errors.CategoryExternal).
						WithTextCode(TextCodeOIDCDiscoveryFailed).
						WithCode(errors.CodeInternal)
	ErrInvalidState = errors.New("oidc state is invalid", errors.CategoryAuth).
					WithTextCode(TextCodeOIDCInvalidState).
					WithCode(errors.CodeUnauthorized)
	ErrInvalidNonce = errors.New("oidc nonce is invalid", errors.CategoryAuth).
					WithTextCode(TextCodeOIDCInvalidNonce).
					WithCode(errors.CodeUnauthorized)
	ErrUnsafeRedirect = errors.New("oidc redirect target is not allowed", errors.CategoryValidation).
						WithTextCode(TextCodeOIDCUnsafeRedirect).
						WithCode(errors.CodeBadRequest)
	ErrTokenExchangeFailed = errors.New("oidc token exchange failed", errors.CategoryExternal).
							WithTextCode(TextCodeOIDCTokenExchange).
							WithCode(errors.CodeInternal)
	ErrInvalidIDToken = errors.New("oidc id token is invalid", errors.CategoryAuth).
						WithTextCode(TextCodeOIDCInvalidIDToken).
						WithCode(errors.CodeUnauthorized)
	ErrUserInfoFailed = errors.New("oidc userinfo request failed", errors.CategoryExternal).
						WithTextCode(TextCodeOIDCUserInfoFailed).
						WithCode(errors.CodeInternal)
	ErrLinkingRejected = errors.New("oidc identity linking was rejected", errors.CategoryAuthz).
						WithTextCode(TextCodeOIDCLinkingRejected).
						WithCode(errors.CodeForbidden)
	ErrDuplicateSubject = errors.New("oidc subject maps to more than one user", errors.CategoryConflict).
						WithTextCode(TextCodeOIDCDuplicateSubject).
						WithCode(errors.CodeConflict)
)

Functions

func PrincipalLocalClaims added in v0.45.0

func PrincipalLocalClaims(principal auth.AuthenticatedPrincipal, policy LocalClaimPolicy) (map[string]any, error)

PrincipalLocalClaims returns only the normalized claims explicitly named by policy. Application subject remains the local JWT subject and is not copied.

func SafeRedirect

func SafeRedirect(raw string, fallback string, allowedOrigins []string) (string, error)

Types

type AuditMetadata

type AuditMetadata struct {
	EventType auth.ActivityEventType
	UserID    string
	Metadata  map[string]any
}

type AuthorizationRequest

type AuthorizationRequest struct {
	ProviderKey string
	RedirectTo  string
	LoginHint   string
}

type AuthorizationResponse

type AuthorizationResponse struct {
	ProviderKey string
	RedirectURL string
	// Deprecated: state is retained for source compatibility. HTTP adapters
	// must use RedirectURL and keep callback state server-side.
	State string
	// Deprecated: nonce is retained for source compatibility.
	Nonce string
	// Deprecated: PKCE verifier is retained for source compatibility.
	CodeVerifier string
	ExpiresAt    time.Time
}

func (AuthorizationResponse) Format added in v0.45.0

func (r AuthorizationResponse) Format(state fmt.State, _ rune)

func (AuthorizationResponse) GoString added in v0.45.0

func (r AuthorizationResponse) GoString() string

func (AuthorizationResponse) HTTPRedirectURL added in v0.45.0

func (r AuthorizationResponse) HTTPRedirectURL() string

HTTPRedirectURL is the safe adapter boundary for starting browser login.

func (AuthorizationResponse) LogValue added in v0.45.0

func (r AuthorizationResponse) LogValue() slog.Value

func (AuthorizationResponse) MarshalJSON added in v0.45.0

func (r AuthorizationResponse) MarshalJSON() ([]byte, error)

func (AuthorizationResponse) String added in v0.45.0

func (r AuthorizationResponse) String() string

type BrowserAuthenticator

type BrowserAuthenticator struct {
	// contains filtered or unexported fields
}

func (*BrowserAuthenticator) BeginLogin

func (*BrowserAuthenticator) CompleteCallback

type BrowserAuthenticatorConfig

type BrowserAuthenticatorConfig struct {
	Providers              []*Provider
	StateStore             StateStore
	TokenExchanger         TokenExchanger
	UserInfoFetcher        UserInfoFetcher
	IdentityLinker         IdentityLinker
	TokenIssuer            BrowserTokenIssuer
	PrincipalTokenIssuer   PrincipalTokenIssuer
	PrincipalMapper        PrincipalMapper
	SessionHandoff         ProviderSessionHandoff
	SessionMode            BrowserSessionMode
	LocalClaimPolicy       LocalClaimPolicy
	DefaultRedirect        string
	AllowedRedirectOrigins []string
	Clock                  func() time.Time
	StateTTL               time.Duration
	StateCapacity          int
}
Example (ProviderSessionMode)
package main

import (
	"context"
	"fmt"

	auth "github.com/goliatone/go-auth"
	"github.com/goliatone/go-auth/provider/oidc"
)

func main() {
	config := oidc.BrowserAuthenticatorConfig{
		SessionMode: oidc.ProviderSessionMode,
		SessionHandoff: oidc.ProviderSessionHandoffFunc(func(_ context.Context, principal auth.AuthenticatedPrincipal, tokens auth.ProviderTokenSet) (oidc.ProviderSessionHandoffResult, error) {
			// Persist tokens atomically in encrypted server-side storage.
			return oidc.NewProviderSessionHandoffResult(
				auth.NewSecret("opaque-host-session"),
				"local-session-id",
			)
		}),
	}

	fmt.Println(config.SessionMode)
}
Output:
1

type BrowserSessionMode added in v0.45.0

type BrowserSessionMode uint8
const (
	LocalTokenMode BrowserSessionMode = iota
	ProviderSessionMode
)

type BrowserSessionResult

type BrowserSessionResult struct {
	LocalToken     string
	HostSession    auth.Secret
	Principal      auth.AuthenticatedPrincipal
	Identity       ExternalIdentity
	Claims         *auth.JWTClaims
	ProviderKey    string
	RedirectTarget string
	Audit          AuditMetadata
}

func (BrowserSessionResult) Format added in v0.45.0

func (r BrowserSessionResult) Format(state fmt.State, _ rune)

func (BrowserSessionResult) GoString added in v0.45.0

func (r BrowserSessionResult) GoString() string

func (BrowserSessionResult) LogValue added in v0.45.0

func (r BrowserSessionResult) LogValue() slog.Value

func (BrowserSessionResult) MarshalJSON added in v0.45.0

func (r BrowserSessionResult) MarshalJSON() ([]byte, error)

func (BrowserSessionResult) MarshalText added in v0.45.0

func (r BrowserSessionResult) MarshalText() ([]byte, error)

func (BrowserSessionResult) SessionSecret added in v0.45.0

func (r BrowserSessionResult) SessionSecret() (auth.Secret, error)

SessionSecret returns the one browser cookie value without exposing provider tokens. It rejects missing and ambiguous callback results.

func (BrowserSessionResult) String added in v0.45.0

func (r BrowserSessionResult) String() string

type BrowserTokenIssuer

type BrowserTokenIssuer interface {
	Generate(identity auth.Identity, resourceRoles map[string]string) (string, error)
}

type CallbackRequest

type CallbackRequest struct {
	ProviderKey string
	Code        string
	State       string
	RedirectTo  string
}

func (CallbackRequest) Format added in v0.45.0

func (r CallbackRequest) Format(state fmt.State, _ rune)

func (CallbackRequest) GoString added in v0.45.0

func (r CallbackRequest) GoString() string

func (CallbackRequest) LogValue added in v0.45.0

func (r CallbackRequest) LogValue() slog.Value

func (CallbackRequest) MarshalJSON added in v0.45.0

func (r CallbackRequest) MarshalJSON() ([]byte, error)

func (CallbackRequest) MarshalText added in v0.45.0

func (r CallbackRequest) MarshalText() ([]byte, error)

func (CallbackRequest) String added in v0.45.0

func (r CallbackRequest) String() string

type ClaimKeys

type ClaimKeys struct {
	Roles          []string
	Groups         []string
	Permissions    []string
	ResourceRoles  []string
	TenantID       []string
	OrganizationID []string
}

type ClaimSource added in v0.45.0

type ClaimSource string
const (
	ClaimSourceIDToken     ClaimSource = "id_token"
	ClaimSourceAccessToken ClaimSource = "access_token"
	ClaimSourceUserInfo    ClaimSource = "userinfo"
)

type ClaimsMapper

type ClaimsMapper interface {
	MapClaims(ctx context.Context, provider ProviderConfig, claims jwt.MapClaims, userInfo map[string]any) (ExternalIdentity, *auth.JWTClaims, error)
}

type ClaimsMapperFunc

type ClaimsMapperFunc func(ctx context.Context, provider ProviderConfig, claims jwt.MapClaims, userInfo map[string]any) (ExternalIdentity, *auth.JWTClaims, error)

func (ClaimsMapperFunc) MapClaims

func (f ClaimsMapperFunc) MapClaims(ctx context.Context, provider ProviderConfig, claims jwt.MapClaims, userInfo map[string]any) (ExternalIdentity, *auth.JWTClaims, error)

type Config

type Config struct {
	Providers              []ProviderConfig
	HTTPClient             *http.Client
	Clock                  func() time.Time
	AllowedRedirectOrigins []string
	DefaultRedirect        string
	StateTTL               time.Duration
	AllowSignup            bool
	EmailFallback          EmailFallbackPolicy
}

type DefaultClaimsMapper

type DefaultClaimsMapper struct{}

func (DefaultClaimsMapper) MapClaims

func (DefaultClaimsMapper) MapClaims(_ context.Context, provider ProviderConfig, claims jwt.MapClaims, userInfo map[string]any) (ExternalIdentity, *auth.JWTClaims, error)

type DefaultIdentityLinker

type DefaultIdentityLinker struct {
	// contains filtered or unexported fields
}

func NewIdentityLinker

func NewIdentityLinker(cfg LinkerConfig) (*DefaultIdentityLinker, error)

func (*DefaultIdentityLinker) IdentifierBindingMode added in v0.45.0

func (l *DefaultIdentityLinker) IdentifierBindingMode() IdentifierBindingMode
func (l *DefaultIdentityLinker) RecordManualLink(ctx context.Context, userID string, identity ExternalIdentity, metadata map[string]any)
func (l *DefaultIdentityLinker) RecordUnlink(ctx context.Context, userID string, identity ExternalIdentity, metadata map[string]any)

func (*DefaultIdentityLinker) Resolve

func (l *DefaultIdentityLinker) Unlink(ctx context.Context, userID string, identity ExternalIdentity) error

type DefaultPrincipalMapper added in v0.45.0

type DefaultPrincipalMapper struct{}

func (DefaultPrincipalMapper) MapPrincipal added in v0.45.0

type DiscoveryMetadata

type DiscoveryMetadata struct {
	Issuer                   string   `json:"issuer"`
	AuthorizationEndpoint    string   `json:"authorization_endpoint"`
	TokenEndpoint            string   `json:"token_endpoint"`
	UserInfoEndpoint         string   `json:"userinfo_endpoint"`
	JWKSURI                  string   `json:"jwks_uri"`
	EndSessionEndpoint       string   `json:"end_session_endpoint,omitempty"`
	Algorithms               []string `json:"id_token_signing_alg_values_supported,omitempty"`
	Scopes                   []string `json:"scopes_supported,omitempty"`
	TokenEndpointAuthMethods []string `json:"token_endpoint_auth_methods_supported,omitempty"`
}

func Discover

func Discover(ctx context.Context, provider ProviderConfig, client *http.Client) (DiscoveryMetadata, error)

type EmailFallbackPolicy

type EmailFallbackPolicy struct {
	Enabled              bool
	RequireVerifiedEmail bool
}

type ExternalIdentity

type ExternalIdentity struct {
	Provider       string
	Subject        string
	Email          string
	EmailVerified  bool
	Name           string
	GivenName      string
	FamilyName     string
	Nickname       string
	Picture        string
	TenantID       string
	OrganizationID string
	Roles          []string
	Permissions    []string
	ResourceRoles  map[string]string
	Metadata       map[string]any
}

type GeneratedIdentityIDStrategy added in v0.45.0

type GeneratedIdentityIDStrategy struct{}

GeneratedIdentityIDStrategy preserves the historical random UUID behavior.

func (GeneratedIdentityIDStrategy) UserID added in v0.45.0

type HTTPTokenExchanger

type HTTPTokenExchanger struct {
	Client *http.Client
}

func (HTTPTokenExchanger) Exchange

func (e HTTPTokenExchanger) Exchange(ctx context.Context, provider ProviderConfig, metadata DiscoveryMetadata, code string, codeVerifier string) (TokenResponse, error)

type HTTPUserInfoFetcher

type HTTPUserInfoFetcher struct {
	Client *http.Client
}

func (HTTPUserInfoFetcher) FetchUserInfo

func (f HTTPUserInfoFetcher) FetchUserInfo(ctx context.Context, provider ProviderConfig, metadata DiscoveryMetadata, accessToken string) (map[string]any, error)

type IDTokenValidator

type IDTokenValidator interface {
	ValidateIDToken(ctx context.Context, rawIDToken string, nonce string) (jwt.MapClaims, error)
}

type IdentifierBindingMode added in v0.45.0

type IdentifierBindingMode uint8
const (
	// IdentifierBindingLegacyCompatible permits mutable Upsert fallback.
	// Deprecated: hardened and provider-session flows must use an immutable or
	// transactional mode.
	IdentifierBindingLegacyCompatible IdentifierBindingMode = iota
	IdentifierBindingImmutableRequired
	IdentifierBindingTransactionalRequired
)

type IdentityIDStrategy added in v0.45.0

type IdentityIDStrategy interface {
	UserID(context.Context, ExternalIdentity) (uuid.UUID, error)
}

IdentityIDStrategy selects a local user ID before persistence. Strategies must validate provider subjects before returning an ID.

type IdentityIDStrategyFunc added in v0.45.0

type IdentityIDStrategyFunc func(context.Context, ExternalIdentity) (uuid.UUID, error)

IdentityIDStrategyFunc adapts a function to IdentityIDStrategy.

func (IdentityIDStrategyFunc) UserID added in v0.45.0

type IdentityLinker

type IdentityLinker interface {
	Resolve(ctx context.Context, identity ExternalIdentity) (auth.Identity, LinkingDecision, error)
}

type IdentityLinkerSecurityCapability added in v0.45.0

type IdentityLinkerSecurityCapability interface {
	IdentifierBindingMode() IdentifierBindingMode
}

IdentityLinkerSecurityCapability lets hardened browser composition verify that an injected linker cannot reassign an external subject.

type Limits added in v0.45.0

type Limits struct {
	DiscoveryBodyBytes int64
	JWKSBodyBytes      int64
	UserInfoBodyBytes  int64
	TokenBodyBytes     int64
	EncodedTokenBytes  int
	CallbackCodeBytes  int
	CallbackStateBytes int
	RedirectBytes      int
	ProviderKeyBytes   int
	JWKSKeys           int
}

type LinkerConfig

type LinkerConfig struct {
	Users         auth.Users
	Identifiers   auth.IdentifierStore
	BindingMode   IdentifierBindingMode
	AllowSignup   bool
	EmailFallback EmailFallbackPolicy
	DefaultRole   auth.UserRole
	IDStrategy    IdentityIDStrategy
	UserFactory   UserFactory
	ActivitySink  auth.ActivitySink
}

type LinkingDecision

type LinkingDecision struct {
	Action   string
	UserID   string
	Metadata map[string]any
}

type LocalClaim added in v0.45.0

type LocalClaim string
const (
	LocalClaimProvider           LocalClaim = "provider"
	LocalClaimProviderSubject    LocalClaim = "provider_subject"
	LocalClaimProviderSessionID  LocalClaim = "provider_session_id"
	LocalClaimClientID           LocalClaim = "client_id"
	LocalClaimAssuranceLevel     LocalClaim = "assurance_level"
	LocalClaimAssuranceMethods   LocalClaim = "assurance_methods"
	LocalClaimAuthenticationTime LocalClaim = "authentication_time"
	LocalClaimTenantID           LocalClaim = "tenant_id"
	LocalClaimOrganizationID     LocalClaim = "organization_id"
	LocalClaimPermissionVersion  LocalClaim = "permission_version"
)

type LocalClaimPolicy added in v0.45.0

type LocalClaimPolicy struct {
	Allow []LocalClaim
}

func (LocalClaimPolicy) Enabled added in v0.45.0

func (p LocalClaimPolicy) Enabled() bool

type MemoryStateStore

type MemoryStateStore struct {
	// contains filtered or unexported fields
}

func NewMemoryStateStore

func NewMemoryStateStore(clock func() time.Time) *MemoryStateStore

func NewMemoryStateStoreWithCapacity added in v0.45.0

func NewMemoryStateStoreWithCapacity(clock func() time.Time, capacity int) *MemoryStateStore

func (*MemoryStateStore) Consume

func (s *MemoryStateStore) Consume(_ context.Context, state string) (StateRecord, error)

func (*MemoryStateStore) Save

func (s *MemoryStateStore) Save(_ context.Context, state StateRecord) error

type PrincipalMapper added in v0.45.0

type PrincipalMapper interface {
	MapPrincipal(ctx context.Context, provider ProviderConfig, idToken auth.ValidatedTokenContext, accessToken *auth.ValidatedTokenContext, idClaims jwt.MapClaims, accessClaims jwt.MapClaims, userInfo map[string]any) (ValidatedProviderIdentity, error)
}

type PrincipalMapperFunc added in v0.45.0

func (PrincipalMapperFunc) MapPrincipal added in v0.45.0

func (f PrincipalMapperFunc) MapPrincipal(ctx context.Context, provider ProviderConfig, idToken auth.ValidatedTokenContext, accessToken *auth.ValidatedTokenContext, idClaims jwt.MapClaims, accessClaims jwt.MapClaims, userInfo map[string]any) (ValidatedProviderIdentity, error)

type PrincipalTokenIssuer added in v0.45.0

type PrincipalTokenIssuer interface {
	GeneratePrincipal(identity auth.Identity, normalizedClaims map[string]any) (string, error)
}

type PrincipalTokenIssuerFunc added in v0.45.0

type PrincipalTokenIssuerFunc func(auth.Identity, map[string]any) (string, error)

func (PrincipalTokenIssuerFunc) GeneratePrincipal added in v0.45.0

func (f PrincipalTokenIssuerFunc) GeneratePrincipal(identity auth.Identity, normalizedClaims map[string]any) (string, error)

type Provider

type Provider struct {
	Config    ProviderConfig
	Metadata  DiscoveryMetadata
	Validator *TokenValidator
}

func NewProvider

func NewProvider(ctx context.Context, provider ProviderConfig, opts ...ProviderOption) (*Provider, error)

type ProviderConfig

type ProviderConfig struct {
	Key          string
	Issuer       string
	DiscoveryURL string
	ClientID     string
	// Deprecated: use ClientSecretValue. This field remains source-compatible
	// for one release and is redacted from default output.
	ClientSecret             string
	ClientSecretValue        auth.Secret
	TokenEndpointAuthMethod  TokenEndpointAuthMethod
	RedirectURL              string
	Scopes                   []string
	Audience                 []string
	IDTokenAudience          []string
	AccessTokenAudience      []string
	RequireAccessTokenClaims bool
	AllowedAlgorithms        []string
	CacheTTL                 time.Duration
	JWKSRefreshCooldown      time.Duration
	// AllowInsecureHTTP permits provider and callback HTTP endpoints only when
	// their host is loopback. It is intended for local development and tests.
	AllowInsecureHTTP   bool
	UserInfo            bool
	Display             ProviderDisplay
	ClaimMapper         ClaimsMapper
	ClaimKeys           ClaimKeys
	AdditionalAuthParam map[string]string
	Limits              Limits
	RequestTimeout      time.Duration
}
Example (Auth0AsOIDC)
package main

import (
	"fmt"

	auth "github.com/goliatone/go-auth"
	"github.com/goliatone/go-auth/provider/oidc"
	"github.com/goliatone/go-auth/provider/oidc/preset"
)

func main() {
	provider := preset.Apply(oidc.ProviderConfig{
		Key:                     "auth0",
		ClientID:                "go-auth-admin",
		ClientSecretValue:       auth.NewSecret("use-secret-manager"),
		TokenEndpointAuthMethod: oidc.TokenEndpointAuthClientSecretPost,
		RedirectURL:             "https://app.example.com/admin/sso/callback/auth0",
		Audience:                []string{"https://api.example.com"},
		AllowedAlgorithms:       []string{"RS256"},
	}, preset.Auth0("tenant.us.auth0.com"))

	fmt.Println(provider.Issuer)
}
Output:
https://tenant.us.auth0.com/
Example (GenericOIDC)
package main

import (
	"fmt"

	auth "github.com/goliatone/go-auth"
	"github.com/goliatone/go-auth/provider/oidc"
)

func main() {
	provider := oidc.ProviderConfig{
		Key:                     "enterprise",
		Issuer:                  "https://idp.example.com/",
		ClientID:                "go-auth-admin",
		ClientSecretValue:       auth.NewSecret("use-secret-manager"),
		TokenEndpointAuthMethod: oidc.TokenEndpointAuthClientSecretBasic,
		RedirectURL:             "https://app.example.com/admin/sso/callback/enterprise",
		Scopes:                  []string{"openid", "profile", "email", "groups"},
		Audience:                []string{"go-auth-admin"},
		AllowedAlgorithms:       []string{"RS256"},
		Display: oidc.ProviderDisplay{
			Label: "Enterprise SSO",
			Icon:  "building",
		},
	}

	_ = oidc.Config{
		Providers:              []oidc.ProviderConfig{provider},
		DefaultRedirect:        "/admin",
		AllowedRedirectOrigins: []string{"https://app.example.com"},
		AllowSignup:            true,
		EmailFallback: oidc.EmailFallbackPolicy{
			Enabled:              true,
			RequireVerifiedEmail: true,
		},
	}

	fmt.Println(provider.Scopes[0])
}
Output:
openid
Example (SupabaseConfidentialClient)
package main

import (
	"fmt"

	auth "github.com/goliatone/go-auth"
	"github.com/goliatone/go-auth/provider/oidc"
)

func main() {
	provider := oidc.ProviderConfig{
		Key:                     "supabase",
		Issuer:                  "https://project.supabase.co/auth/v1",
		ClientID:                "backoffice",
		ClientSecretValue:       auth.NewSecret("use-secret-manager"),
		TokenEndpointAuthMethod: oidc.TokenEndpointAuthClientSecretBasic,
		RedirectURL:             "https://backoffice.example.com/sso/callback/supabase",
		AllowedAlgorithms:       []string{"ES256"},
	}

	fmt.Println(provider.TokenEndpointAuthMethod, provider.AllowedAlgorithms[0])
}
Output:
client_secret_basic ES256

func (ProviderConfig) Format added in v0.45.0

func (p ProviderConfig) Format(state fmt.State, _ rune)

func (ProviderConfig) GoString added in v0.45.0

func (p ProviderConfig) GoString() string

func (ProviderConfig) LogValue added in v0.45.0

func (p ProviderConfig) LogValue() slog.Value

func (ProviderConfig) MarshalJSON added in v0.45.0

func (p ProviderConfig) MarshalJSON() ([]byte, error)

func (ProviderConfig) MarshalText added in v0.45.0

func (p ProviderConfig) MarshalText() ([]byte, error)

func (ProviderConfig) String added in v0.45.0

func (p ProviderConfig) String() string

type ProviderDisplay

type ProviderDisplay struct {
	Label          string
	Icon           string
	IconURL        string
	Disabled       bool
	DisabledReason string
}

type ProviderInfo

type ProviderInfo struct {
	Key            string `json:"key"`
	Label          string `json:"label"`
	LoginURL       string `json:"login_url"`
	Icon           string `json:"icon,omitempty"`
	IconURL        string `json:"icon_url,omitempty"`
	DisabledReason string `json:"disabled_reason,omitempty"`
}

type ProviderOption

type ProviderOption func(*providerOptions)

func WithProviderHTTPClient

func WithProviderHTTPClient(client *http.Client) ProviderOption

type ProviderSessionHandoff added in v0.45.0

type ProviderSessionHandoff interface {
	CreateProviderSession(ctx context.Context, principal auth.AuthenticatedPrincipal, tokens auth.ProviderTokenSet) (ProviderSessionHandoffResult, error)
}

type ProviderSessionHandoffFunc added in v0.45.0

func (ProviderSessionHandoffFunc) CreateProviderSession added in v0.45.0

type ProviderSessionHandoffResult added in v0.45.0

type ProviderSessionHandoffResult struct {
	// contains filtered or unexported fields
}

ProviderSessionHandoffResult is the atomic output of server-side provider session creation. The local ID is bound to the normalized principal while the host session secret remains opaque.

func NewProviderSessionHandoffResult added in v0.45.0

func NewProviderSessionHandoffResult(hostSession auth.Secret, localSessionID string) (ProviderSessionHandoffResult, error)

func (ProviderSessionHandoffResult) Format added in v0.45.0

func (r ProviderSessionHandoffResult) Format(state fmt.State, _ rune)

func (ProviderSessionHandoffResult) GoString added in v0.45.0

func (r ProviderSessionHandoffResult) GoString() string

func (ProviderSessionHandoffResult) HostSession added in v0.45.0

func (r ProviderSessionHandoffResult) HostSession() auth.Secret

func (ProviderSessionHandoffResult) LocalSessionID added in v0.45.0

func (r ProviderSessionHandoffResult) LocalSessionID() string

func (ProviderSessionHandoffResult) LogValue added in v0.45.0

func (ProviderSessionHandoffResult) MarshalJSON added in v0.45.0

func (r ProviderSessionHandoffResult) MarshalJSON() ([]byte, error)

func (ProviderSessionHandoffResult) MarshalText added in v0.45.0

func (r ProviderSessionHandoffResult) MarshalText() ([]byte, error)

func (ProviderSessionHandoffResult) String added in v0.45.0

type ProviderSubjectUUIDIDStrategy added in v0.45.0

type ProviderSubjectUUIDIDStrategy struct {
	Provider string
}

ProviderSubjectUUIDIDStrategy uses a validated UUID provider subject as the local user ID. Provider optionally restricts the strategy to one provider.

func (ProviderSubjectUUIDIDStrategy) UserID added in v0.45.0

type SessionCreatorHandoff added in v0.45.0

type SessionCreatorHandoff struct {
	Creator auth.ProviderSessionCreator
}

SessionCreatorHandoff adapts the provider-neutral session creator to the OIDC callback handoff without exposing repository or token-vault internals.

func (SessionCreatorHandoff) CreateProviderSession added in v0.45.0

type StateRecord

type StateRecord struct {
	State        string
	Nonce        string
	CodeVerifier string
	ProviderKey  string
	RedirectTo   string
	CreatedAt    time.Time
	ExpiresAt    time.Time
}

func (StateRecord) Format added in v0.45.0

func (r StateRecord) Format(state fmt.State, _ rune)

func (StateRecord) GoString added in v0.45.0

func (r StateRecord) GoString() string

func (StateRecord) LogValue added in v0.45.0

func (r StateRecord) LogValue() slog.Value

func (StateRecord) MarshalJSON added in v0.45.0

func (r StateRecord) MarshalJSON() ([]byte, error)

func (StateRecord) MarshalText added in v0.45.0

func (r StateRecord) MarshalText() ([]byte, error)

func (StateRecord) String added in v0.45.0

func (r StateRecord) String() string

type StateStore

type StateStore interface {
	Save(ctx context.Context, state StateRecord) error
	Consume(ctx context.Context, state string) (StateRecord, error)
}

type TokenEndpointAuthMethod added in v0.45.0

type TokenEndpointAuthMethod string
const (
	TokenEndpointAuthUnspecified       TokenEndpointAuthMethod = ""
	TokenEndpointAuthNone              TokenEndpointAuthMethod = "none"
	TokenEndpointAuthClientSecretBasic TokenEndpointAuthMethod = "client_secret_basic"
	TokenEndpointAuthClientSecretPost  TokenEndpointAuthMethod = "client_secret_post"
)

type TokenExchanger

type TokenExchanger interface {
	Exchange(ctx context.Context, provider ProviderConfig, metadata DiscoveryMetadata, code string, codeVerifier string) (TokenResponse, error)
}

type TokenExchangerFunc

type TokenExchangerFunc func(ctx context.Context, provider ProviderConfig, metadata DiscoveryMetadata, code string, codeVerifier string) (TokenResponse, error)

func (TokenExchangerFunc) Exchange

func (f TokenExchangerFunc) Exchange(ctx context.Context, provider ProviderConfig, metadata DiscoveryMetadata, code string, codeVerifier string) (TokenResponse, error)

type TokenResponse

type TokenResponse struct {
	// Deprecated: use the secret-bearing Value fields.
	AccessToken       string
	IDToken           string
	RefreshToken      string
	AccessTokenValue  auth.Secret
	IDTokenValue      auth.Secret
	RefreshTokenValue auth.Secret
	TokenType         string `json:"token_type"`
	ExpiresIn         int64  `json:"expires_in,omitempty"`
	RefreshExpiresIn  int64  `json:"refresh_expires_in,omitempty"`
	Scope             string `json:"scope,omitempty"`
}

func (TokenResponse) Format added in v0.45.0

func (r TokenResponse) Format(state fmt.State, _ rune)

func (TokenResponse) GoString added in v0.45.0

func (r TokenResponse) GoString() string

func (TokenResponse) LogValue added in v0.45.0

func (r TokenResponse) LogValue() slog.Value

func (TokenResponse) MarshalJSON added in v0.45.0

func (r TokenResponse) MarshalJSON() ([]byte, error)

func (TokenResponse) MarshalText added in v0.45.0

func (r TokenResponse) MarshalText() ([]byte, error)

func (TokenResponse) String added in v0.45.0

func (r TokenResponse) String() string

type TokenValidator

type TokenValidator struct {
	// contains filtered or unexported fields
}

func NewTokenValidator

func NewTokenValidator(ctx context.Context, provider ProviderConfig, metadata DiscoveryMetadata, opts ...ValidatorOption) (*TokenValidator, error)

func (*TokenValidator) Validate

func (v *TokenValidator) Validate(tokenString string) (auth.AuthClaims, error)

func (*TokenValidator) ValidateAccessToken added in v0.45.0

func (v *TokenValidator) ValidateAccessToken(ctx context.Context, rawAccessToken string) (jwt.MapClaims, error)

func (*TokenValidator) ValidateIDToken

func (v *TokenValidator) ValidateIDToken(ctx context.Context, rawIDToken string, nonce string) (jwt.MapClaims, error)

func (*TokenValidator) ValidateIDTokenWithAccessToken added in v0.45.0

func (v *TokenValidator) ValidateIDTokenWithAccessToken(ctx context.Context, rawIDToken string, nonce string, rawAccessToken string) (jwt.MapClaims, error)

type UserFactory added in v0.45.0

type UserFactory interface {
	NewUser(context.Context, ExternalIdentity, auth.UserRole) (*auth.User, error)
}

UserFactory builds a local user before create-and-bind. Hosts can use it for provider-specific defaults without changing the linker transaction boundary.

type UserFactoryFunc added in v0.45.0

type UserFactoryFunc func(context.Context, ExternalIdentity, auth.UserRole) (*auth.User, error)

UserFactoryFunc adapts a function to UserFactory.

func (UserFactoryFunc) NewUser added in v0.45.0

func (f UserFactoryFunc) NewUser(ctx context.Context, identity ExternalIdentity, role auth.UserRole) (*auth.User, error)

type UserInfoFetcher

type UserInfoFetcher interface {
	FetchUserInfo(ctx context.Context, provider ProviderConfig, metadata DiscoveryMetadata, accessToken string) (map[string]any, error)
}

type UserInfoFetcherFunc

type UserInfoFetcherFunc func(ctx context.Context, provider ProviderConfig, metadata DiscoveryMetadata, accessToken string) (map[string]any, error)

func (UserInfoFetcherFunc) FetchUserInfo

func (f UserInfoFetcherFunc) FetchUserInfo(ctx context.Context, provider ProviderConfig, metadata DiscoveryMetadata, accessToken string) (map[string]any, error)

type ValidatedProviderIdentity added in v0.45.0

type ValidatedProviderIdentity struct {
	Provider          string
	Subject           string
	Email             string
	EmailVerified     bool
	Name              string
	GivenName         string
	FamilyName        string
	Nickname          string
	Picture           string
	ProviderSessionID string
	ClientID          string
	AssuranceLevel    string
	AssuranceMethods  []string
	AuthenticationAt  time.Time
	IssuedAt          time.Time
	ExpiresAt         time.Time
	TokenID           string
	TenantID          string
	OrganizationID    string
	PermissionVersion string
	ResourceRoles     map[string]string
	Metadata          map[string]string
	Provenance        map[string]ClaimSource
}

type ValidatorOption

type ValidatorOption func(*validatorOptions)

func WithValidatorClock

func WithValidatorClock(clock func() time.Time) ValidatorOption

func WithValidatorContext

func WithValidatorContext(fn func() context.Context) ValidatorOption

func WithValidatorHTTPClient

func WithValidatorHTTPClient(client *http.Client) ValidatorOption

Directories

Path Synopsis
Package preset contains thin provider conventions for generic OIDC.
Package preset contains thin provider conventions for generic OIDC.

Jump to

Keyboard shortcuts

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