Documentation
¶
Overview ¶
Package server implements an OpenID Connect server with federated logins.
Index ¶
- Constants
- Variables
- func GrantTypeAllowed(configuredTypes []string, grantType string) bool
- func NewAPI(s storage.Storage, logger *slog.Logger, version string, server *Server) api.DexServer
- func WithRemoteIP(ctx context.Context, ip string) context.Context
- func WithRequestID(ctx context.Context) context.Context
- type Config
- type Connector
- type ConnectorConfig
- type Introspection
- type IntrospectionExtra
- type MFAProvider
- type PKCEConfig
- type Prompt
- type RefreshTokenPolicy
- type Server
- type SessionConfig
- type TOTPProvider
- type TokenTypeEnum
- type WebAuthnProvider
- type WebConfig
Constants ¶
const ( // ErrMsgLoginError is a generic login error message shown to users. // Used when authentication fails due to internal server errors. ErrMsgLoginError = "Login error. Please contact your administrator or try again later." // ErrMsgAuthenticationFailed is shown when callback/SAML authentication fails. ErrMsgAuthenticationFailed = "Authentication failed. Please contact your administrator or try again later." // ErrMsgInternalServerError is a generic internal server error message. ErrMsgInternalServerError = "Internal server error. Please contact your administrator or try again later." // ErrMsgDatabaseError is shown when database operations fail. ErrMsgDatabaseError = "A database error occurred. Please try again later." // ErrMsgInvalidRequest is shown when request parsing fails. ErrMsgInvalidRequest = "Invalid request. Please try again." // ErrMsgMethodNotAllowed is shown when an unsupported HTTP method is used. ErrMsgMethodNotAllowed = "Method not allowed." // ErrMsgNotInRequiredGroups is shown when a user authenticates successfully // but is not a member of any of the groups required by the connector. ErrMsgNotInRequiredGroups = "You are not a member of any of the required groups to authenticate." )
const ( RequestKeyRequestID logRequestKey = "request_id" RequestKeyRemoteIP logRequestKey = "client_remote_addr" )
const LocalConnector = "local"
LocalConnector is the local passwordDB connector which is an internal connector maintained by the server.
Variables ¶
var ConnectorGrantTypes = map[string]bool{ // contains filtered or unexported fields }
ConnectorGrantTypes is the set of grant types that can be restricted per connector.
var ConnectorsConfig = map[string]func() ConnectorConfig{ "keystone": func() ConnectorConfig { return new(keystone.Config) }, "mockCallback": func() ConnectorConfig { return new(mock.CallbackConfig) }, "mockPassword": func() ConnectorConfig { return new(mock.PasswordConfig) }, "ldap": func() ConnectorConfig { return new(ldap.Config) }, "gitea": func() ConnectorConfig { return new(gitea.Config) }, "github": func() ConnectorConfig { return new(github.Config) }, "gitlab": func() ConnectorConfig { return new(gitlab.Config) }, "google": func() ConnectorConfig { return new(google.Config) }, "oidc": func() ConnectorConfig { return new(oidc.Config) }, "oauth": func() ConnectorConfig { return new(oauth.Config) }, "saml": func() ConnectorConfig { return new(saml.Config) }, "authproxy": func() ConnectorConfig { return new(authproxy.Config) }, "linkedin": func() ConnectorConfig { return new(linkedin.Config) }, "microsoft": func() ConnectorConfig { return new(microsoft.Config) }, "bitbucket-cloud": func() ConnectorConfig { return new(bitbucketcloud.Config) }, "openshift": func() ConnectorConfig { return new(openshift.Config) }, "atlassian-crowd": func() ConnectorConfig { return new(atlassiancrowd.Config) }, "samlExperimental": func() ConnectorConfig { return new(saml.Config) }, }
ConnectorsConfig variable provides an easy way to return a config struct depending on the connector type.
Functions ¶
func GrantTypeAllowed ¶
GrantTypeAllowed checks if the given grant type is allowed for this connector. If no grant types are configured, all are allowed.
Types ¶
type Config ¶
type Config struct {
Issuer string
// The backing persistence layer.
Storage storage.Storage
AllowedGrantTypes []string
// Valid values are "code" to enable the code flow and "token" to enable the implicit
// flow. If no response types are supplied this value defaults to "code".
SupportedResponseTypes []string
// Headers is a map of headers to be added to the all responses.
Headers http.Header
// Header to extract real ip from.
RealIPHeader string
TrustedRealIPCIDRs []netip.Prefix
// List of allowed origins for CORS requests on discovery, token and keys endpoint.
// If none are indicated, CORS requests are disabled. Passing in "*" will allow any
// domain.
AllowedOrigins []string
// List of allowed headers for CORS requests on discovery, token, and keys endpoint.
AllowedHeaders []string
// If enabled, the server won't prompt the user to approve authorization requests.
// Logging in implies approval.
SkipApprovalScreen bool
// If enabled, the connectors selection page will always be shown even if there's only one
AlwaysShowLoginScreen bool
IDTokensValidFor time.Duration // Defaults to 24 hours
AuthRequestsValidFor time.Duration // Defaults to 24 hours
DeviceRequestsValidFor time.Duration // Defaults to 5 minutes
// Refresh token expiration settings
RefreshTokenPolicy *RefreshTokenPolicy
// If set, the server will use this connector to handle password grants
PasswordConnector string
// PKCE configuration
PKCE PKCEConfig
GCFrequency time.Duration // Defaults to 5 minutes
// If specified, the server will use this function for determining time.
Now func() time.Time
Web WebConfig
Logger *slog.Logger
// Signer is used to sign tokens.
Signer signer.Signer
PrometheusRegistry *prometheus.Registry
HealthChecker gosundheit.Health
// If enabled, the server will continue starting even if some connectors fail to initialize.
// This allows the server to operate with a subset of connectors if some are misconfigured.
ContinueOnConnectorFailure bool
// SessionConfig holds session settings. Nil when sessions are disabled.
SessionConfig *SessionConfig
// MFAProviders maps authenticator IDs to their provider implementations.
MFAProviders map[string]MFAProvider
// DefaultMFAChain is applied to clients that don't specify their own mfaChain.
DefaultMFAChain []string
}
Config holds the server's configuration options.
Multiple servers using the same storage are expected to be configured identically.
type Connector ¶
type Connector struct {
Type string
ResourceVersion string
Connector connector.Connector
GrantTypes []string
}
Connector is a connector with resource version metadata.
type ConnectorConfig ¶
type ConnectorConfig interface {
Open(id string, logger *slog.Logger) (connector.Connector, error)
}
ConnectorConfig is a configuration that can open a connector.
type Introspection ¶
type Introspection struct {
// Boolean indicator of whether or not the presented token
// is currently active. The specifics of a token's "active" state
// will vary depending on the implementation of the authorization
// server and the information it keeps about its tokens, but a "true"
// value return for the "active" property will generally indicate
// that a given token has been issued by this authorization server,
// has not been revoked by the resource owner, and is within its
// given time window of validity (e.g., after its issuance time and
// before its expiration time).
Active bool `json:"active"`
// JSON string containing a space-separated list of
// scopes associated with this token.
Scope string `json:"scope,omitempty"`
// Client identifier for the OAuth 2.0 client that
// requested this token.
ClientID string `json:"client_id"`
// Subject of the token, as defined in JWT [RFC7519].
// Usually a machine-readable identifier of the resource owner who
// authorized this token.
Subject string `json:"sub"`
// Integer timestamp, measured in the number of seconds
// since January 1 1970 UTC, indicating when this token will expire.
Expiry int64 `json:"exp"`
// Integer timestamp, measured in the number of seconds
// since January 1 1970 UTC, indicating when this token was
// originally issued.
IssuedAt int64 `json:"iat"`
// Integer timestamp, measured in the number of seconds
// since January 1 1970 UTC, indicating when this token is not to be
// used before.
NotBefore int64 `json:"nbf"`
// Human-readable identifier for the resource owner who
// authorized this token.
Username string `json:"username,omitempty"`
// Service-specific string identifier or list of string
// identifiers representing the intended audience for this token, as
// defined in JWT
Audience audience `json:"aud"`
// String representing the issuer of this token, as
// defined in JWT
Issuer string `json:"iss"`
// String identifier for the token, as defined in JWT [RFC7519].
JwtTokenID string `json:"jti,omitempty"`
// TokenType is the introspected token's type, typically `bearer`.
TokenType string `json:"token_type"`
// TokenUse is the introspected token's use, for example `access_token` or `refresh_token`.
TokenUse string `json:"token_use"`
// Extra is arbitrary data set from the token claims.
Extra IntrospectionExtra `json:"ext,omitempty"`
}
Introspection contains an access token's session data as specified by [IETF RFC 7662](https://tools.ietf.org/html/rfc7662)
type IntrospectionExtra ¶
type IntrospectionExtra struct {
AuthorizingParty string `json:"azp,omitempty"`
Email string `json:"email,omitempty"`
EmailVerified *bool `json:"email_verified,omitempty"`
Groups []string `json:"groups,omitempty"`
Name string `json:"name,omitempty"`
PreferredUsername string `json:"preferred_username,omitempty"`
FederatedIDClaims *federatedIDClaims `json:"federated_claims,omitempty"`
}
type MFAProvider ¶
type MFAProvider interface {
// Type returns the authenticator type identifier (e.g., "TOTP").
Type() string
// EnabledForConnectorType returns true if this provider applies to the given connector type.
// If no connector types are configured, the provider applies to all.
EnabledForConnectorType(connectorType string) bool
}
MFAProvider is a pluggable multi-factor authentication method.
type PKCEConfig ¶
type PKCEConfig struct {
// If true, PKCE is required for all authorization code flows.
Enforce bool
// Supported code challenge methods. Defaults to ["S256", "plain"].
CodeChallengeMethodsSupported []string
}
PKCEConfig holds PKCE (Proof Key for Code Exchange) settings.
type Prompt ¶
type Prompt struct {
// contains filtered or unexported fields
}
Prompt represents the parsed OIDC "prompt" parameter (RFC 6749 / OpenID Connect Core 3.1.2.1). The parameter is space-separated and may contain: "none", "login", "consent", "select_account". "none" must not be combined with any other value.
func ParsePrompt ¶
ParsePrompt parses and validates the raw prompt query parameter. Returns an error suitable for returning as an OAuth2 invalid_request if the value is invalid.
func (Prompt) SelectAccount ¶
SelectAccount returns true if the caller requested account/connector selection.
type RefreshTokenPolicy ¶
type RefreshTokenPolicy struct {
// contains filtered or unexported fields
}
func NewRefreshTokenPolicy ¶
func (*RefreshTokenPolicy) AllowedToReuse ¶
func (r *RefreshTokenPolicy) AllowedToReuse(lastUsed time.Time) bool
func (*RefreshTokenPolicy) CompletelyExpired ¶
func (r *RefreshTokenPolicy) CompletelyExpired(lastUsed time.Time) bool
func (*RefreshTokenPolicy) ExpiredBecauseUnused ¶
func (r *RefreshTokenPolicy) ExpiredBecauseUnused(lastUsed time.Time) bool
func (*RefreshTokenPolicy) RotationEnabled ¶
func (r *RefreshTokenPolicy) RotationEnabled() bool
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server is the top level object.
func (*Server) CloseConnector ¶
CloseConnector removes the connector from the server's in-memory map.
func (*Server) OpenConnector ¶
OpenConnector updates server connector map with specified connector object.
type SessionConfig ¶
type SessionConfig struct {
CookieName string
CookieEncryptionKey []byte
AbsoluteLifetime time.Duration
ValidIfNotUsedFor time.Duration
RememberMeCheckedByDefault bool
// "all" = share with all clients, "none" or "" = share with no one (default).
SSOSharedWithDefault string
}
SessionConfig holds resolved session configuration.
type TOTPProvider ¶
type TOTPProvider struct {
// contains filtered or unexported fields
}
TOTPProvider implements TOTP-based multi-factor authentication.
func NewTOTPProvider ¶
func NewTOTPProvider(issuer string, connectorTypes []string) *TOTPProvider
NewTOTPProvider creates a new TOTP MFA provider.
func (*TOTPProvider) EnabledForConnectorType ¶
func (p *TOTPProvider) EnabledForConnectorType(connectorType string) bool
func (*TOTPProvider) Type ¶
func (p *TOTPProvider) Type() string
type TokenTypeEnum ¶
type TokenTypeEnum int
const ( AccessToken TokenTypeEnum = iota RefreshToken )
func (TokenTypeEnum) String ¶
func (t TokenTypeEnum) String() string
type WebAuthnProvider ¶
type WebAuthnProvider struct {
// contains filtered or unexported fields
}
WebAuthnProvider implements WebAuthn-based multi-factor authentication.
func NewWebAuthnProvider ¶
func NewWebAuthnProvider(rpDisplayName, rpID string, rpOrigins []string, attestationPreference, timeout, issuerURL string, connectorTypes []string, ) (*WebAuthnProvider, error)
NewWebAuthnProvider creates a new WebAuthn MFA provider. If rpID or rpOrigins are empty, they are derived from the issuerURL.
func (*WebAuthnProvider) EnabledForConnectorType ¶
func (p *WebAuthnProvider) EnabledForConnectorType(connectorType string) bool
func (*WebAuthnProvider) Type ¶
func (p *WebAuthnProvider) Type() string
type WebConfig ¶
type WebConfig struct {
// A file path to static web assets.
//
// It is expected to contain the following directories:
//
// * static - Static static served at "( issuer URL )/static".
// * templates - HTML templates controlled by dex.
// * themes/(theme) - Static static served at "( issuer URL )/theme".
Dir string
// Alternative way to programmatically configure static web assets.
// If Dir is specified, WebFS is ignored.
// It's expected to contain the same files and directories as mentioned above.
//
// Note: this is experimental. Might get removed without notice!
WebFS fs.FS
// Defaults to "( issuer URL )/theme/logo.png"
LogoURL string
// Defaults to "dex"
Issuer string
// Defaults to "light"
Theme string
// Map of extra values passed into the templates
Extra map[string]string
}
WebConfig holds the server's frontend templates and asset configuration.