sso

package
v1.0.7 Latest Latest
Warning

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

Go to latest
Published: Mar 14, 2026 License: MIT Imports: 19 Imported by: 0

Documentation

Index

Constants

View Source
const (
	SessionContextKey contextKey = "sso_session"
	UserContextKey    contextKey = "sso_user"
)
View Source
const (
	ErrInvalidRequest           = "invalid_request"
	ErrInvalidToken             = "invalid_token"
	ErrInvalidSignature         = "invalid_signature"
	ErrExpiredToken             = "expired_token"
	ErrInvalidAssertion         = "invalid_assertion"
	ErrMissingRequiredAttribute = "missing_required_attribute"
	ErrUserNotAllowed           = "user_not_allowed"
	ErrDomainNotAllowed         = "domain_not_allowed"
	ErrSessionExpired           = "session_expired"
	ErrProviderNotConfigured    = "provider_not_configured"
	ErrInvalidAuthnRequest      = "invalid_authn_request"
	ErrInvalidCallback          = "invalid_callback"
	ErrStateMismatch            = "state_mismatch"
	ErrMissingDiscovery         = "missing_discovery"
	ErrCertificateError         = "certificate_error"
	ErrMetadataError            = "metadata_error"
)

Common SSO error codes

Variables

This section is empty.

Functions

func ContextWithSession

func ContextWithSession(ctx context.Context, session *SSOSession) context.Context

ContextWithSession adds a session to context

func ContextWithUser

func ContextWithUser(ctx context.Context, user *SSOUser) context.Context

ContextWithUser adds a user to context

Types

type Assertion

type Assertion struct {
	XMLName            xml.Name            `xml:"urn:oasis:names:tc:SAML:2.0:assertion Assertion"`
	ID                 string              `xml:"ID,attr"`
	IssueInstant       string              `xml:"IssueInstant,attr"`
	Version            string              `xml:"Version,attr"`
	AssertionIssuer    *AssertionIssuer    `xml:"urn:oasis:names:tc:SAML:2.0:assertion Issuer"`
	Subject            *Subject            `xml:"urn:oasis:names:tc:SAML:2.0:assertion Subject"`
	Conditions         *Conditions         `xml:"urn:oasis:names:tc:SAML:2.0:assertion Conditions"`
	AuthnStatement     *AuthnStatement     `xml:"urn:oasis:names:tc:SAML:2.0:assertion AuthnStatement"`
	AttributeStatement *AttributeStatement `xml:"urn:oasis:names:tc:SAML:2.0:assertion AttributeStatement"`
}

type AssertionConsumerService

type AssertionConsumerService struct {
	Index     int    `xml:"index,attr"`
	IsDefault bool   `xml:"isDefault,attr,omitempty"`
	Binding   string `xml:"Binding,attr"`
	Location  string `xml:"Location,attr"`
}

type AssertionIssuer

type AssertionIssuer struct {
	Format string `xml:"Format,attr,omitempty"`
	Value  string `xml:",chardata"`
}

AssertionIssuer is used to avoid XML tag conflicts

type Attribute

type Attribute struct {
	Name            string           `xml:"Name,attr"`
	NameFormat      string           `xml:"NameFormat,attr,omitempty"`
	AttributeValues []AttributeValue `xml:"urn:oasis:names:tc:SAML:2.0:assertion AttributeValue"`
}

type AttributeMapping

type AttributeMapping struct {
	IDAttribute           string
	UsernameAttribute     string
	EmailAttribute        string
	NameAttribute         string
	FirstNameAttribute    string
	LastNameAttribute     string
	DisplayNameAttribute  string
	GroupAttribute        string
	RoleAttribute         string
	DepartmentAttribute   string
	OrganizationAttribute string
	TitleAttribute        string
	CustomMappings        map[string]string
}

AttributeMapping defines how IdP attributes map to user fields

func DefaultAttributeMapping

func DefaultAttributeMapping() *AttributeMapping

DefaultAttributeMapping returns default attribute mappings

func SAMLAttributeMapping

func SAMLAttributeMapping() *AttributeMapping

SAMLAttributeMapping returns SAML-specific attribute mappings

type AttributeStatement

type AttributeStatement struct {
	Attributes []Attribute `xml:"urn:oasis:names:tc:SAML:2.0:assertion Attribute"`
}

type AttributeValue

type AttributeValue struct {
	Type  string `xml:"xsi:type,attr,omitempty"`
	Value string `xml:",chardata"`
}

type AudienceRestriction

type AudienceRestriction struct {
	Audience []string `xml:"urn:oasis:names:tc:SAML:2.0:assertion Audience"`
}

type AuthnContext

type AuthnContext struct {
	AuthnContextClassRef *AuthnContextClassRefInner `xml:"urn:oasis:names:tc:SAML:2.0:assertion AuthnContextClassRef"`
}

type AuthnContextClassRef

type AuthnContextClassRef struct {
	XMLName xml.Name `xml:"saml:AuthnContextClassRef"`
	Value   string   `xml:",chardata"`
}

type AuthnContextClassRefInner

type AuthnContextClassRefInner struct {
	Value string `xml:",chardata"`
}

AuthnContextClassRefInner is used to avoid XML tag conflicts

type AuthnRequest

type AuthnRequest struct {
	XMLName               xml.Name               `xml:"samlp:AuthnRequest"`
	ID                    string                 `xml:"ID,attr"`
	Version               string                 `xml:"Version,attr"`
	IssueInstant          string                 `xml:"IssueInstant,attr"`
	Destination           string                 `xml:"Destination,attr,omitempty"`
	ForceAuthn            string                 `xml:"ForceAuthn,attr,omitempty"`
	IsPassive             string                 `xml:"IsPassive,attr,omitempty"`
	Issuer                *Issuer                `xml:"saml:Issuer"`
	NameIDPolicy          *NameIDPolicy          `xml:"samlp:NameIDPolicy"`
	RequestedAuthnContext *RequestedAuthnContext `xml:"samlp:RequestedAuthnContext"`
}

type AuthnStatement

type AuthnStatement struct {
	AuthnInstant string        `xml:"AuthnInstant,attr"`
	SessionIndex string        `xml:"SessionIndex,attr,omitempty"`
	AuthnContext *AuthnContext `xml:"urn:oasis:names:tc:SAML:2.0:assertion AuthnContext"`
}

type CanonicalizationMethod

type CanonicalizationMethod struct {
	Algorithm string `xml:"Algorithm,attr"`
}

type Conditions

type Conditions struct {
	NotBefore           string               `xml:"NotBefore,attr"`
	NotOnOrAfter        string               `xml:"NotOnOrAfter,attr"`
	AudienceRestriction *AudienceRestriction `xml:"urn:oasis:names:tc:SAML:2.0:assertion AudienceRestriction"`
}

type CookieOptions

type CookieOptions struct {
	Secure   bool
	HTTPOnly bool
	SameSite string
	Path     string
	Domain   string
	MaxAge   int
}

CookieOptions holds cookie configuration

func DefaultCookieOptions

func DefaultCookieOptions() CookieOptions

DefaultCookieOptions returns default cookie options

type DigestMethod

type DigestMethod struct {
	Algorithm string `xml:"Algorithm,attr"`
}

type EntityDescriptor

type EntityDescriptor struct {
	XMLName          xml.Name             `xml:"urn:oasis:names:tc:SAML:2.0:metadata EntityDescriptor"`
	EntityID         string               `xml:"entityID,attr"`
	ValidUntil       string               `xml:"validUntil,attr,omitempty"`
	SPSSODescriptor  *SPSSODescriptor     `xml:"urn:oasis:names:tc:SAML:2.0:metadata SPSSODescriptor"`
	IDPSSODescriptor *IDPSSODescriptorXML `xml:"urn:oasis:names:tc:SAML:2.0:metadata IDPSSODescriptor"`
}

type IDPSSODescriptor

type IDPSSODescriptor struct {
	EntityID               string
	SSOURLs                []string
	SLOURLs                []string
	SigningCertificates    []*x509.Certificate
	EncryptionCertificates []*x509.Certificate
	NameIDFormats          []string
	Attributes             []string
}

IDPSSODescriptor represents IdP SSO Descriptor from metadata

type IDPSSODescriptorXML

type IDPSSODescriptorXML struct {
	XMLName                 xml.Name              `xml:"urn:oasis:names:tc:SAML:2.0:metadata IDPSSODescriptor"`
	WantAuthnRequestsSigned bool                  `xml:"WantAuthnRequestsSigned,attr"`
	SingleSignOnService     []SingleSignOnService `xml:"urn:oasis:names:tc:SAML:2.0:metadata SingleSignOnService"`
	SingleLogoutService     []SingleLogoutService `xml:"urn:oasis:names:tc:SAML:2.0:metadata SingleLogoutService"`
	NameIDFormats           []string              `xml:"urn:oasis:names:tc:SAML:2.0:metadata NameIDFormat"`
	KeyDescriptors          []KeyDescriptor       `xml:"urn:oasis:names:tc:SAML:2.0:metadata KeyDescriptor"`
}

type Issuer

type Issuer struct {
	XMLName xml.Name `xml:"saml:Issuer"`
	Format  string   `xml:"Format,attr,omitempty"`
	Value   string   `xml:",chardata"`
}

type KeyDescriptor

type KeyDescriptor struct {
	Use     string      `xml:"use,attr"`
	KeyInfo *KeyInfoXML `xml:"http://www.w3.org/2000/09/xmldsig# KeyInfo"`
}

type KeyInfo

type KeyInfo struct {
	X509Data *X509Data `xml:"http://www.w3.org/2000/09/xmldsig# X509Data"`
}

type KeyInfoXML

type KeyInfoXML struct {
	X509Data *X509DataXML `xml:"http://www.w3.org/2000/09/xmldsig# X509Data"`
}

type LogoutRequest

type LogoutRequest struct {
	XMLName      xml.Name `xml:"samlp:LogoutRequest"`
	ID           string   `xml:"ID,attr"`
	Version      string   `xml:"Version,attr"`
	IssueInstant string   `xml:"IssueInstant,attr"`
	Destination  string   `xml:"Destination,attr,omitempty"`
	Issuer       *Issuer  `xml:"saml:Issuer"`
	NameID       *NameID  `xml:"NameID"`
	SessionIndex string   `xml:"samlp:SessionIndex"`
}

type Manager

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

Manager manages SSO providers and sessions

func NewManager

func NewManager(config *ManagerConfig) (*Manager, error)

NewManager creates a new SSO manager

func (*Manager) CheckDomainAccess

func (m *Manager) CheckDomainAccess(providerName, email string) error

CheckDomainAccess checks if a domain is allowed for a provider

func (*Manager) CleanupSessions

func (m *Manager) CleanupSessions() error

CleanupSessions removes expired sessions

func (*Manager) GetProvider

func (m *Manager) GetProvider(name string) (SSOProviderInterface, error)

GetProvider returns an SSO provider by name

func (*Manager) GetProviderMetadata

func (m *Manager) GetProviderMetadata(providerName string) ([]byte, error)

GetProviderMetadata returns the metadata for a provider

func (*Manager) GetSession

func (m *Manager) GetSession(sessionID string) (*SSOSession, error)

GetSession returns a session by ID

func (*Manager) GetUserSessions

func (m *Manager) GetUserSessions(userID string) ([]*SSOSession, error)

GetUserSessions returns all sessions for a user

func (*Manager) HandleCallback

func (m *Manager) HandleCallback(providerName string, params map[string]string) (*SSOResponse, error)

HandleCallback handles the SSO callback from the provider

func (*Manager) InitiateLogin

func (m *Manager) InitiateLogin(providerName string) (string, *SSORequest, error)

InitiateLogin initiates SSO login for a provider

func (*Manager) ListProviders

func (m *Manager) ListProviders() []string

ListProviders returns all registered provider names

func (*Manager) Logout

func (m *Manager) Logout(sessionID string) (string, error)

Logout logs out an SSO session

func (*Manager) RefreshSession

func (m *Manager) RefreshSession(sessionID string) (*SSOSession, error)

RefreshSession refreshes an OIDC session's tokens

func (*Manager) RegisterProvider

func (m *Manager) RegisterProvider(config *SSOConfig) error

RegisterProvider registers an SSO provider

func (*Manager) Stats

func (m *Manager) Stats() (*ManagerStats, error)

Stats returns manager statistics

func (*Manager) TerminateUserSessions

func (m *Manager) TerminateUserSessions(userID string) error

TerminateUserSessions terminates all sessions for a user

func (*Manager) UnregisterProvider

func (m *Manager) UnregisterProvider(name string) error

UnregisterProvider unregisters an SSO provider

func (*Manager) ValidateSession

func (m *Manager) ValidateSession(sessionID string) (*SSOSession, error)

ValidateSession validates an SSO session

type ManagerConfig

type ManagerConfig struct {
	SessionStore   SessionStore
	RequestStore   RequestStore
	DefaultConfig  *SSOConfig
	HTTPClient     *http.Client
	SessionTimeout time.Duration
}

ManagerConfig holds manager configuration

type ManagerStats

type ManagerStats struct {
	Providers      int
	ActiveSessions int
}

Stats returns manager statistics

type MemoryRequestStore

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

MemoryRequestStore implements RequestStore in memory

func NewMemoryRequestStore

func NewMemoryRequestStore() *MemoryRequestStore

NewMemoryRequestStore creates a new memory request store

func (*MemoryRequestStore) Create

func (s *MemoryRequestStore) Create(request *SSORequest) error

Create stores a new request

func (*MemoryRequestStore) Delete

func (s *MemoryRequestStore) Delete(id string) error

Delete removes a request

func (*MemoryRequestStore) Get

func (s *MemoryRequestStore) Get(id string) (*SSORequest, error)

Get retrieves a request by ID

func (*MemoryRequestStore) GetByState

func (s *MemoryRequestStore) GetByState(state string) (*SSORequest, error)

GetByState retrieves a request by state

type MemorySessionStore

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

MemorySessionStore implements SessionStore in memory

func NewMemorySessionStore

func NewMemorySessionStore() *MemorySessionStore

NewMemorySessionStore creates a new memory session store

func (*MemorySessionStore) Cleanup

func (s *MemorySessionStore) Cleanup() error

Cleanup removes expired sessions

func (*MemorySessionStore) Create

func (s *MemorySessionStore) Create(session *SSOSession) error

Create stores a new session

func (*MemorySessionStore) Delete

func (s *MemorySessionStore) Delete(id string) error

Delete removes a session

func (*MemorySessionStore) DeleteByUserID

func (s *MemorySessionStore) DeleteByUserID(userID string) error

DeleteByUserID removes all sessions for a user

func (*MemorySessionStore) Get

func (s *MemorySessionStore) Get(id string) (*SSOSession, error)

Get retrieves a session by ID

func (*MemorySessionStore) GetByUserID

func (s *MemorySessionStore) GetByUserID(userID string) ([]*SSOSession, error)

GetByUserID returns all sessions for a user

func (*MemorySessionStore) Update

func (s *MemorySessionStore) Update(session *SSOSession) error

Update updates an existing session

type Middleware

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

Middleware provides SSO authentication middleware

func NewMiddleware

func NewMiddleware(manager *Manager, opts *CookieOptions) *Middleware

NewMiddleware creates a new SSO middleware

func (*Middleware) CallbackHandler

func (m *Middleware) CallbackHandler(providerName string, onSuccess, onFailure string) http.Handler

CallbackHandler returns a handler for SSO callbacks

func (*Middleware) LoginHandler

func (m *Middleware) LoginHandler(providerName string) http.Handler

LoginHandler returns a handler that initiates SSO login

func (*Middleware) LogoutHandler

func (m *Middleware) LogoutHandler(redirectURL string) http.Handler

LogoutHandler returns a handler for SSO logout

func (*Middleware) MetadataHandler

func (m *Middleware) MetadataHandler(providerName string) http.Handler

MetadataHandler returns SAML metadata for a provider

func (*Middleware) OptionalSession

func (m *Middleware) OptionalSession(next http.Handler) http.Handler

OptionalSession middleware adds session info if available but doesn't require it

func (*Middleware) RequireAnyRole

func (m *Middleware) RequireAnyRole(roles ...auth.Role) func(http.Handler) http.Handler

RequireAnyRole middleware requires any of the specified roles

func (*Middleware) RequireDomain

func (m *Middleware) RequireDomain(domains ...string) func(http.Handler) http.Handler

RequireDomain middleware requires the user to be from a specific domain

func (*Middleware) RequireGroup

func (m *Middleware) RequireGroup(groups ...string) func(http.Handler) http.Handler

RequireGroup middleware requires the user to be in a specific group

func (*Middleware) RequireRole

func (m *Middleware) RequireRole(role auth.Role) func(http.Handler) http.Handler

RequireRole middleware requires a specific role

func (*Middleware) RequireSession

func (m *Middleware) RequireSession(next http.Handler) http.Handler

RequireSession middleware requires a valid SSO session

type NameID

type NameID struct {
	XMLName         xml.Name `xml:"urn:oasis:names:tc:SAML:2.0:assertion NameID"`
	Format          string   `xml:"Format,attr,omitempty"`
	NameQualifier   string   `xml:"NameQualifier,attr,omitempty"`
	SPNameQualifier string   `xml:"SPNameQualifier,attr,omitempty"`
	Value           string   `xml:",chardata"`
}

type NameIDPolicy

type NameIDPolicy struct {
	XMLName         xml.Name `xml:"samlp:NameIDPolicy"`
	Format          string   `xml:"Format,attr,omitempty"`
	SPNameQualifier string   `xml:"SPNameQualifier,attr,omitempty"`
	AllowCreate     bool     `xml:"AllowCreate,attr,omitempty"`
}

type OIDCConfig

type OIDCConfig struct {
	IssuerURL           string
	AuthURL             string
	TokenURL            string
	UserInfoURL         string
	JWKSURL             string
	EndSessionURL       string
	ClientID            string
	ClientSecret        string
	RedirectURL         string
	Scopes              []string
	UsePKCE             bool
	PKCEChallenge       string
	ValidateAccessToken bool
	ValidateIDToken     bool
	SkipIssuerCheck     bool
	SkipExpiryCheck     bool
	AzureADTenant       string
	GSuiteDomain        string
	OktaDomain          string
	ProviderType        string
}

OIDCConfig holds OpenID Connect specific configuration

func (*OIDCConfig) Validate

func (c *OIDCConfig) Validate() error

Validate validates OIDC configuration

type OIDCDiscoveryDocument

type OIDCDiscoveryDocument struct {
	Issuer                           string
	AuthorizationEndpoint            string
	TokenEndpoint                    string
	UserInfoEndpoint                 string
	JWKSEndpoint                     string
	RegistrationEndpoint             string
	ScopesSupported                  []string
	ResponseTypesSupported           []string
	ResponseModesSupported           []string
	GrantTypesSupported              []string
	SubjectTypesSupported            []string
	IDTokenSigningAlgValuesSupported []string
	ClaimsSupported                  []string
	EndSessionEndpoint               string
}

OIDCDiscoveryDocument represents OIDC discovery document

type OIDCIDTokenClaims

type OIDCIDTokenClaims struct {
	Issuer            string
	Subject           string
	Audience          []string
	Expiration        int64
	IssuedAt          int64
	AuthTime          int64
	Nonce             string
	ACR               string
	Email             string
	EmailVerified     bool
	Name              string
	GivenName         string
	FamilyName        string
	PreferredUsername string
	Picture           string
	Groups            []string
	Roles             []string
}

OIDCIDTokenClaims represents claims in an ID token

type OIDCProvider

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

OIDCProvider implements OpenID Connect SSO

func NewOIDCProvider

func NewOIDCProvider(config *SSOConfig, store RequestStore) (*OIDCProvider, error)

NewOIDCProvider creates a new OIDC provider

func (*OIDCProvider) HandleCallback

func (p *OIDCProvider) HandleCallback(request *SSORequest, params map[string]string) (*SSOResponse, error)

HandleCallback processes the OIDC callback

func (*OIDCProvider) InitiateLogin

func (p *OIDCProvider) InitiateLogin(state string) (string, *SSORequest, error)

InitiateLogin creates an OIDC authorization request

func (*OIDCProvider) Logout

func (p *OIDCProvider) Logout(session *SSOSession) (string, error)

Logout initiates OIDC logout

func (*OIDCProvider) Metadata

func (p *OIDCProvider) Metadata() ([]byte, error)

Metadata returns provider metadata

func (*OIDCProvider) Name

func (p *OIDCProvider) Name() string

Name returns the provider name

func (*OIDCProvider) RefreshToken

func (p *OIDCProvider) RefreshToken(refreshToken string) (*OIDCToken, error)

RefreshToken refreshes an OIDC access token

func (*OIDCProvider) Type

func (p *OIDCProvider) Type() SSOProvider

Type returns the provider type

func (*OIDCProvider) ValidateSession

func (p *OIDCProvider) ValidateSession(session *SSOSession) error

ValidateSession validates an existing OIDC session

type OIDCToken

type OIDCToken struct {
	AccessToken  string
	TokenType    string
	ExpiresIn    int64
	RefreshToken string
	IDToken      string
	Scope        string
}

OIDCToken represents an OIDC token response

type Reference

type Reference struct {
	URI          string        `xml:"URI,attr"`
	Transforms   *Transforms   `xml:"http://www.w3.org/2000/09/xmldsig# Transforms"`
	DigestMethod *DigestMethod `xml:"http://www.w3.org/2000/09/xmldsig# DigestMethod"`
	DigestValue  string        `xml:"http://www.w3.org/2000/09/xmldsig# DigestValue"`
}

type RequestStore

type RequestStore interface {
	Create(request *SSORequest) error
	Get(id string) (*SSORequest, error)
	GetByState(state string) (*SSORequest, error)
	Delete(id string) error
}

RequestStore interface for SSO request state persistence

type RequestedAuthnContext

type RequestedAuthnContext struct {
	XMLName              xml.Name              `xml:"samlp:RequestedAuthnContext"`
	Comparison           string                `xml:"Comparison,attr"`
	AuthnContextClassRef *AuthnContextClassRef `xml:"saml:AuthnContextClassRef"`
}

type Response

type Response struct {
	XMLName      xml.Name        `xml:"urn:oasis:names:tc:SAML:2.0:protocol Response"`
	ID           string          `xml:"ID,attr"`
	InResponseTo string          `xml:"InResponseTo,attr,omitempty"`
	Version      string          `xml:"Version,attr"`
	IssueInstant string          `xml:"IssueInstant,attr"`
	Destination  string          `xml:"Destination,attr,omitempty"`
	Issuer       *ResponseIssuer `xml:"urn:oasis:names:tc:SAML:2.0:assertion Issuer"`
	Status       *Status         `xml:"urn:oasis:names:tc:SAML:2.0:protocol Status"`
	Assertion    *Assertion      `xml:"urn:oasis:names:tc:SAML:2.0:assertion Assertion"`
	Signature    *Signature      `xml:"http://www.w3.org/2000/09/xmldsig# Signature"`
}

type ResponseIssuer

type ResponseIssuer struct {
	Format string `xml:"Format,attr,omitempty"`
	Value  string `xml:",chardata"`
}

ResponseIssuer is used to avoid XML tag conflicts

type RoleMapping

type RoleMapping struct {
	IdPRole    string
	IdPType    string
	AppRole    auth.Role
	Priority   int
	Conditions map[string]string
}

RoleMapping maps IdP groups/roles to application roles

type SAMLConfig

type SAMLConfig struct {
	EntityID                       string
	MetadataURL                    string
	ACSURL                         string
	SLSURL                         string
	CertFile                       string
	KeyFile                        string
	Certificate                    *x509.Certificate
	PrivateKey                     interface{}
	IDPEntityID                    string
	IDPMetadataURL                 string
	IDPMetadata                    []byte
	IDPSSODescriptor               *IDPSSODescriptor
	NameIDFormat                   string
	AuthnContextClass              string
	AllowCreate                    bool
	ForceAuthn                     bool
	IsPassive                      bool
	ValidateSignature              bool
	SignatureAlgorithm             string
	DigestAlgorithm                string
	AttributeConsumingServiceIndex int
	WantAssertionsSigned           bool
	WantResponseSigned             bool
}

SAMLConfig holds SAML 2.0 specific configuration

func (*SAMLConfig) Validate

func (c *SAMLConfig) Validate() error

Validate validates SAML configuration

type SAMLMetadataType

type SAMLMetadataType struct {
	XMLName  xml.Name
	Xmlns    string
	EntityID string
}

SAMLMetadataType represents SAML metadata

type SAMLProvider

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

SAMLProvider implements SAML 2.0 SSO

func NewSAMLProvider

func NewSAMLProvider(config *SSOConfig, store RequestStore) (*SAMLProvider, error)

NewSAMLProvider creates a new SAML provider

func (*SAMLProvider) HandleCallback

func (p *SAMLProvider) HandleCallback(request *SSORequest, params map[string]string) (*SSOResponse, error)

HandleCallback processes the SAML response from the IdP

func (*SAMLProvider) InitiateLogin

func (p *SAMLProvider) InitiateLogin(state string) (string, *SSORequest, error)

InitiateLogin creates a SAML authentication request

func (*SAMLProvider) LoadIDPMetadata

func (p *SAMLProvider) LoadIDPMetadata(metadataURL string, metadataBytes []byte) error

LoadIDPMetadata loads IdP metadata from URL or bytes

func (*SAMLProvider) Logout

func (p *SAMLProvider) Logout(session *SSOSession) (string, error)

Logout initiates SAML single logout

func (*SAMLProvider) Metadata

func (p *SAMLProvider) Metadata() ([]byte, error)

Metadata generates the SP metadata

func (*SAMLProvider) Name

func (p *SAMLProvider) Name() string

Name returns the provider name

func (*SAMLProvider) Type

func (p *SAMLProvider) Type() SSOProvider

Type returns the provider type

func (*SAMLProvider) ValidateSession

func (p *SAMLProvider) ValidateSession(session *SSOSession) error

ValidateSession validates an existing SSO session

type SPSSODescriptor

type SPSSODescriptor struct {
	AuthnRequestsSigned        bool                       `xml:"AuthnRequestsSigned,attr"`
	WantAssertionsSigned       bool                       `xml:"WantAssertionsSigned,attr"`
	ProtocolSupportEnumeration string                     `xml:"protocolSupportEnumeration,attr"`
	NameIDFormats              []string                   `xml:"urn:oasis:names:tc:SAML:2.0:metadata NameIDFormat"`
	AssertionConsumerService   []AssertionConsumerService `xml:"urn:oasis:names:tc:SAML:2.0:metadata AssertionConsumerService"`
	SingleLogoutService        []SingleLogoutService      `xml:"urn:oasis:names:tc:SAML:2.0:metadata SingleLogoutService"`
}

type SSOConfig

type SSOConfig struct {
	Provider           SSOProvider
	Name               string
	DisplayName        string
	Enabled            bool
	Priority           int
	SAML               *SAMLConfig
	OIDC               *OIDCConfig
	SessionDuration    time.Duration
	MaxSessionAge      time.Duration
	ClockSkewTolerance time.Duration
	CookieName         string
	CookieSecure       bool
	CookieHTTPOnly     bool
	CookieSameSite     string
	CookieDomain       string
	RequireHTTPS       bool
	AllowIDPInitiated  bool
	StrictAudience     bool
	AttributeMapping   *AttributeMapping
	RoleMappings       []RoleMapping
	AllowedDomains     []string
	BlockedDomains     []string
}

SSOConfig holds configuration for SSO providers

func DefaultSSOConfig

func DefaultSSOConfig() *SSOConfig

DefaultSSOConfig returns default SSO configuration

func (*SSOConfig) Validate

func (c *SSOConfig) Validate() error

Validate validates the SSO configuration

type SSOError

type SSOError struct {
	Code        string
	Message     string
	Description string
	Provider    SSOProvider
	StatusCode  int
	Cause       error
}

SSOError represents SSO-specific errors

func NewSSOError

func NewSSOError(code, message string) *SSOError

NewSSOError creates a new SSO error

func (*SSOError) Error

func (e *SSOError) Error() string

func (*SSOError) Unwrap

func (e *SSOError) Unwrap() error

func (*SSOError) WithCause

func (e *SSOError) WithCause(cause error) *SSOError

WithCause adds a cause to the error

type SSOProvider

type SSOProvider string

SSOProvider represents the type of SSO provider

const (
	ProviderSAML  SSOProvider = "saml"
	ProviderOIDC  SSOProvider = "oidc"
	ProviderOAuth SSOProvider = "oauth2"
)

type SSOProviderInterface

type SSOProviderInterface interface {
	Name() string
	Type() SSOProvider
	InitiateLogin(state string) (loginURL string, request *SSORequest, err error)
	HandleCallback(request *SSORequest, params map[string]string) (*SSOResponse, error)
	ValidateSession(session *SSOSession) error
	Logout(session *SSOSession) (logoutURL string, err error)
	Metadata() ([]byte, error)
}

SSOProviderInterface defines the interface for SSO providers

type SSORequest

type SSORequest struct {
	ID              string
	Provider        string
	SAMLRequest     string
	RelayState      string
	Destination     string
	ProtocolBinding string
	State           string
	CodeVerifier    string
	Nonce           string
	RedirectURL     string
	CreatedAt       time.Time
	ExpiresAt       time.Time
	IPAddress       string
	UserAgent       string
}

SSORequest represents an SSO authentication request

type SSOResponse

type SSOResponse struct {
	Success     bool
	User        *SSOUser
	Session     *SSOSession
	Error       *SSOError
	RedirectURL string
	Attributes  map[string]interface{}
}

SSOResponse represents an SSO authentication response

type SSOSession

type SSOSession struct {
	ID             string
	User           *SSOUser
	UserID         string
	SessionID      string
	Provider       SSOProvider
	ProviderName   string
	CreatedAt      time.Time
	ExpiresAt      time.Time
	LastActivity   time.Time
	LastRefreshed  time.Time
	IPAddress      string
	UserAgent      string
	InitialIDP     string
	NameID         string
	SessionIndex   string
	AccessToken    string
	RefreshToken   string
	IDToken        string
	TokenExpiresAt time.Time
	Active         bool
	Flags          map[string]bool
	Metadata       map[string]interface{}
}

SSOSession represents an SSO authentication session

func SessionFromContext

func SessionFromContext(ctx context.Context) *SSOSession

SessionFromContext retrieves the session from context

func (*SSOSession) IsExpired

func (s *SSOSession) IsExpired() bool

IsExpired checks if the session has expired

func (*SSOSession) IsTokenExpired

func (s *SSOSession) IsTokenExpired() bool

IsTokenExpired checks if the OIDC token has expired Returns false if no token is set (for SAML sessions or sessions without tokens)

func (*SSOSession) IsValid

func (s *SSOSession) IsValid() bool

IsValid checks if the session is active and not expired

func (*SSOSession) NeedsTokenRefresh

func (s *SSOSession) NeedsTokenRefresh(buffer time.Duration) bool

NeedsTokenRefresh checks if the access token needs refresh

func (*SSOSession) Refresh

func (s *SSOSession) Refresh(duration time.Duration)

Refresh extends the session expiration

type SSOUser

type SSOUser struct {
	*auth.User
	SSOProvider   SSOProvider
	SSOProviderID string
	RawAttributes map[string]interface{}
	UpstreamID    string
	UpstreamName  string
	SessionIndex  string
	NameID        string
	AuthnContext  string
	AuthnInstant  time.Time
	AcrValues     []string
	AccessToken   string
	TokenType     string
	RefreshToken  string
	TokenExpiry   time.Time
	IDToken       string
	Groups        []string
}

SSOUser extends auth.User with SSO-specific attributes

func UserFromContext

func UserFromContext(ctx context.Context) *SSOUser

UserFromContext retrieves the user from context

type SessionStore

type SessionStore interface {
	Create(session *SSOSession) error
	Get(id string) (*SSOSession, error)
	Update(session *SSOSession) error
	Delete(id string) error
	GetByUserID(userID string) ([]*SSOSession, error)
	DeleteByUserID(userID string) error
	Cleanup() error
}

SessionStore interface for session persistence

type Signature

type Signature struct {
	SignedInfo     *SignedInfo     `xml:"http://www.w3.org/2000/09/xmldsig# SignedInfo"`
	SignatureValue *SignatureValue `xml:"http://www.w3.org/2000/09/xmldsig# SignatureValue"`
	KeyInfo        *KeyInfo        `xml:"http://www.w3.org/2000/09/xmldsig# KeyInfo"`
}

type SignatureMethod

type SignatureMethod struct {
	Algorithm string `xml:"Algorithm,attr"`
}

type SignatureValue

type SignatureValue struct {
	Value string `xml:",chardata"`
}

type SignedInfo

type SignedInfo struct {
	CanonicalizationMethod *CanonicalizationMethod `xml:"http://www.w3.org/2000/09/xmldsig# CanonicalizationMethod"`
	SignatureMethod        *SignatureMethod        `xml:"http://www.w3.org/2000/09/xmldsig# SignatureMethod"`
	Reference              *Reference              `xml:"http://www.w3.org/2000/09/xmldsig# Reference"`
}

type SingleLogoutService

type SingleLogoutService struct {
	Binding  string `xml:"Binding,attr"`
	Location string `xml:"Location,attr"`
}

type SingleSignOnService

type SingleSignOnService struct {
	Binding  string `xml:"Binding,attr"`
	Location string `xml:"Location,attr"`
}

type Status

type Status struct {
	StatusCode *StatusCode `xml:"urn:oasis:names:tc:SAML:2.0:protocol StatusCode"`
}

type StatusCode

type StatusCode struct {
	Value string `xml:"Value,attr"`
}

type Subject

type Subject struct {
	NameID *SubjectNameID `xml:"urn:oasis:names:tc:SAML:2.0:assertion NameID"`
}

type SubjectNameID

type SubjectNameID struct {
	Format          string `xml:"Format,attr,omitempty"`
	NameQualifier   string `xml:"NameQualifier,attr,omitempty"`
	SPNameQualifier string `xml:"SPNameQualifier,attr,omitempty"`
	Value           string `xml:",chardata"`
}

SubjectNameID is used to avoid XML tag conflicts

type Transform

type Transform struct {
	Algorithm string `xml:"Algorithm,attr"`
}

type Transforms

type Transforms struct {
	Transform []Transform `xml:"http://www.w3.org/2000/09/xmldsig# Transform"`
}

type X509Data

type X509Data struct {
	X509Certificate string `xml:"http://www.w3.org/2000/09/xmldsig# X509Certificate"`
}

type X509DataXML

type X509DataXML struct {
	X509Certificate string `xml:"http://www.w3.org/2000/09/xmldsig# X509Certificate"`
}

Jump to

Keyboard shortcuts

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