Documentation
¶
Index ¶
- Variables
- func AccessRequestFromContext(ctx context.Context) fosite.AccessRequester
- func ContextWithOwnerID(ctx context.Context, ownerID uuid.UUID) context.Context
- func LoggerFromContext(ctx context.Context) *slog.Logger
- func SaveConfig(cfg *Config, path string) error
- func WithAccessRequest(ctx context.Context, ar fosite.AccessRequester) context.Context
- type AuthCodeData
- type AuthMethod
- type AuthSession
- type AuthenticateRequest
- type AuthenticationProvider
- type AuthorizationSession
- type AuthorizeInput
- type AuthorizeOutput
- type Client
- func (c *Client) GetAudience() fosite.Arguments
- func (c *Client) GetGrantTypes() fosite.Arguments
- func (c *Client) GetHashedSecret() []byte
- func (c *Client) GetID() string
- func (c *Client) GetRedirectURIs() []string
- func (c *Client) GetResponseTypes() fosite.Arguments
- func (c *Client) GetScopes() fosite.Arguments
- func (c *Client) IsPublic() bool
- func (c *Client) ValidateSecret(secret string) bool
- type ClientConfig
- type ClientManager
- type ClientType
- type Config
- type ConfigFormat
- type ConsentSession
- type CoreControlDiscovery
- type CredentialType
- type DatabaseConfig
- type DefaultIdentitySyncHandler
- type DefaultSessionProvider
- func (p *DefaultSessionProvider) GetAuthenticatedUser(r *http.Request) string
- func (p *DefaultSessionProvider) GetUserClaims(_ context.Context, userID string, _ []string) map[string]interface{}
- func (p *DefaultSessionProvider) HasConsent(_ context.Context, _, _ string, _ []string) bool
- func (p *DefaultSessionProvider) RedirectToConsent(returnURL string) string
- func (p *DefaultSessionProvider) RedirectToLogin(returnURL string) string
- func (p *DefaultSessionProvider) SaveConsent(_ context.Context, _, _ string, _ []string) error
- type DefaultSessionProviderOption
- type DeviceInfo
- type Duration
- func (d Duration) Duration() time.Duration
- func (Duration) JSONSchema() *jsonschema.Schema
- func (d Duration) MarshalJSON() ([]byte, error)
- func (d Duration) MarshalYAML() (interface{}, error)
- func (d *Duration) UnmarshalJSON(b []byte) error
- func (d *Duration) UnmarshalYAML(unmarshal func(interface{}) error) error
- type EmbeddedAuthProvider
- func (p *EmbeddedAuthProvider) Authenticate(ctx context.Context, req *AuthenticateRequest) (*AuthSession, error)
- func (p *EmbeddedAuthProvider) ListSessions(ctx context.Context, identityID uuid.UUID) ([]*AuthSession, error)
- func (p *EmbeddedAuthProvider) RefreshSession(ctx context.Context, sessionToken string) (*AuthSession, error)
- func (p *EmbeddedAuthProvider) RevokeSession(ctx context.Context, sessionToken string) error
- func (p *EmbeddedAuthProvider) RevokeSessions(ctx context.Context, identityID uuid.UUID) error
- func (p *EmbeddedAuthProvider) ValidateSession(ctx context.Context, sessionToken string) (*AuthSession, error)
- type EmbeddedAuthProviderOption
- type EmbeddedIdentityProvider
- func (p *EmbeddedIdentityProvider) CreateIdentity(ctx context.Context, identity *Identity) error
- func (p *EmbeddedIdentityProvider) DeleteIdentity(ctx context.Context, id uuid.UUID) error
- func (p *EmbeddedIdentityProvider) GetIdentity(ctx context.Context, id uuid.UUID) (*Identity, error)
- func (p *EmbeddedIdentityProvider) GetIdentityByEmail(ctx context.Context, email string) (*Identity, error)
- func (p *EmbeddedIdentityProvider) ListIdentities(ctx context.Context, filter *IdentityFilter) ([]*Identity, error)
- func (p *EmbeddedIdentityProvider) UpdateIdentity(ctx context.Context, identity *Identity) error
- type EmbeddedOAuthClientStore
- func (s *EmbeddedOAuthClientStore) CreateClient(ctx context.Context, client *OAuthClient) error
- func (s *EmbeddedOAuthClientStore) DeleteClient(ctx context.Context, clientID string) error
- func (s *EmbeddedOAuthClientStore) GetClient(ctx context.Context, clientID string) (*OAuthClient, error)
- func (s *EmbeddedOAuthClientStore) ListClients(ctx context.Context) ([]*OAuthClient, error)
- func (s *EmbeddedOAuthClientStore) UpdateClient(ctx context.Context, client *OAuthClient) error
- type EmbeddedOAuthProvider
- func (p *EmbeddedOAuthProvider) AcceptConsent(ctx context.Context, challenge string, accept *OAuthConsentAccept) (*OAuthConsentResponse, error)
- func (p *EmbeddedOAuthProvider) AcceptLogin(ctx context.Context, challenge string, accept *OAuthLoginAccept) (*OAuthLoginResponse, error)
- func (p *EmbeddedOAuthProvider) Authorize(ctx context.Context, req *OAuthAuthorizeRequest) (*OAuthAuthorizeResponse, error)
- func (p *EmbeddedOAuthProvider) GetConsentRequest(ctx context.Context, challenge string) (*OAuthConsentRequest, error)
- func (p *EmbeddedOAuthProvider) GetLoginRequest(ctx context.Context, challenge string) (*OAuthLoginRequest, error)
- func (p *EmbeddedOAuthProvider) Introspect(ctx context.Context, token string, tokenTypeHint string) (*OAuthIntrospection, error)
- func (p *EmbeddedOAuthProvider) RejectConsent(ctx context.Context, challenge string, reject *OAuthConsentReject) (*OAuthConsentResponse, error)
- func (p *EmbeddedOAuthProvider) RejectLogin(ctx context.Context, challenge string, reject *OAuthLoginReject) (*OAuthLoginResponse, error)
- func (p *EmbeddedOAuthProvider) Revoke(ctx context.Context, token string, tokenTypeHint string) error
- func (p *EmbeddedOAuthProvider) Token(ctx context.Context, req *OAuthTokenRequest) (*OAuthTokenResponse, error)
- func (p *EmbeddedOAuthProvider) UserInfo(ctx context.Context, accessToken string) (*OAuthUserInfo, error)
- type EntStorage
- func (s *EntStorage) ClientAssertionJWTValid(ctx context.Context, jti string) error
- func (s *EntStorage) CreateAccessTokenSession(ctx context.Context, signature string, request fosite.Requester) error
- func (s *EntStorage) CreateAuthorizeCodeSession(ctx context.Context, code string, request fosite.Requester) error
- func (s *EntStorage) CreateClient(ctx context.Context, client *Client) error
- func (s *EntStorage) CreatePKCERequestSession(ctx context.Context, signature string, requester fosite.Requester) error
- func (s *EntStorage) CreateRefreshTokenSession(ctx context.Context, signature string, accessSignature string, ...) error
- func (s *EntStorage) CreateUser(ctx context.Context, user *User) error
- func (s *EntStorage) DeleteAccessTokenSession(ctx context.Context, signature string) error
- func (s *EntStorage) DeleteClient(ctx context.Context, id string) error
- func (s *EntStorage) DeletePKCERequestSession(ctx context.Context, signature string) error
- func (s *EntStorage) DeleteRefreshTokenSession(ctx context.Context, signature string) error
- func (s *EntStorage) DeleteUser(ctx context.Context, id uuid.UUID) error
- func (s *EntStorage) GetAccessTokenSession(ctx context.Context, signature string, session fosite.Session) (fosite.Requester, error)
- func (s *EntStorage) GetAuthorizeCodeSession(ctx context.Context, code string, session fosite.Session) (fosite.Requester, error)
- func (s *EntStorage) GetClient(ctx context.Context, clientID string) (fosite.Client, error)
- func (s *EntStorage) GetClientByID(ctx context.Context, id string) (*Client, error)
- func (s *EntStorage) GetPKCERequestSession(ctx context.Context, signature string, session fosite.Session) (fosite.Requester, error)
- func (s *EntStorage) GetRefreshTokenSession(ctx context.Context, signature string, session fosite.Session) (fosite.Requester, error)
- func (s *EntStorage) GetUserByEmail(ctx context.Context, email string) (*User, error)
- func (s *EntStorage) GetUserByFederationID(ctx context.Context, federationID uuid.UUID) (*User, error)
- func (s *EntStorage) GetUserByID(ctx context.Context, id uuid.UUID) (*User, error)
- func (s *EntStorage) InvalidateAuthorizeCodeSession(ctx context.Context, code string) error
- func (s *EntStorage) ListClients(ctx context.Context) ([]*Client, error)
- func (s *EntStorage) RevokeAccessToken(ctx context.Context, requestID string) error
- func (s *EntStorage) RevokeRefreshToken(ctx context.Context, requestID string) error
- func (s *EntStorage) RotateRefreshToken(ctx context.Context, requestID string, refreshTokenSignature string) error
- func (s *EntStorage) SetClientAssertionJWT(ctx context.Context, jti string, exp time.Time) error
- func (s *EntStorage) UpdateClient(ctx context.Context, client *Client) error
- func (s *EntStorage) UpdateUser(ctx context.Context, user *User) error
- func (s *EntStorage) ValidateSecretArgon2id(ctx context.Context, clientID, secret string) error
- type EntStorageOption
- type FeatureConfig
- type FederationClient
- func (c *FederationClient) Config() *FederationConfig
- func (c *FederationClient) Discovery() *CoreControlDiscovery
- func (c *FederationClient) ExchangeCode(ctx context.Context, code, redirectURI string) (*SSOTokenResponse, error)
- func (c *FederationClient) GetGlobalIdentity(ctx context.Context, globalID uuid.UUID) (*GlobalIdentity, error)
- func (c *FederationClient) GetIdentityMapping(ctx context.Context, globalID uuid.UUID) (*IdentityMapping, error)
- func (c *FederationClient) GetSSOAuthorizationURL(ctx context.Context, state, redirectURI string) (string, error)
- func (c *FederationClient) Initialize(ctx context.Context) error
- func (c *FederationClient) NotifyAppAccess(ctx context.Context, sessionID uuid.UUID) error
- func (c *FederationClient) RegisterWithCoreControl(ctx context.Context, federationID uuid.UUID, displayName, baseURL string, ...) error
- func (c *FederationClient) ValidateSSOSession(ctx context.Context, sessionID uuid.UUID) (*SSOSession, error)
- type FederationConfig
- type FederationEndpoints
- type FederationHealthResponse
- type GlobalIdentity
- type Identity
- type IdentityCredential
- type IdentityFilter
- type IdentityMapping
- type IdentityProvider
- type IdentityState
- type IdentitySyncHandler
- type IdentitySyncRequest
- type IdentitySyncResponse
- type IdentityTraits
- type IntrospectInput
- type IntrospectOutput
- type IntrospectResponse
- type JWKSInput
- type JWKSOutput
- type KeyConfig
- type MemoryStorage
- func (s *MemoryStorage) CleanupExpired(ctx context.Context) error
- func (s *MemoryStorage) ClientAssertionJWTValid(ctx context.Context, jti string) error
- func (s *MemoryStorage) CreateAccessTokenSession(ctx context.Context, signature string, request fosite.Requester) error
- func (s *MemoryStorage) CreateAuthorizeCodeSession(ctx context.Context, code string, request fosite.Requester) error
- func (s *MemoryStorage) CreateClient(ctx context.Context, client *Client) error
- func (s *MemoryStorage) CreatePKCERequestSession(ctx context.Context, signature string, requester fosite.Requester) error
- func (s *MemoryStorage) CreateRefreshTokenSession(ctx context.Context, signature string, accessSignature string, ...) error
- func (s *MemoryStorage) CreateUser(ctx context.Context, user *User) error
- func (s *MemoryStorage) DeleteAccessTokenSession(ctx context.Context, signature string) error
- func (s *MemoryStorage) DeleteClient(ctx context.Context, id string) error
- func (s *MemoryStorage) DeletePKCERequestSession(ctx context.Context, signature string) error
- func (s *MemoryStorage) DeleteRefreshTokenSession(ctx context.Context, signature string) error
- func (s *MemoryStorage) DeleteUser(ctx context.Context, id uuid.UUID) error
- func (s *MemoryStorage) GetAccessTokenSession(ctx context.Context, signature string, session fosite.Session) (fosite.Requester, error)
- func (s *MemoryStorage) GetAuthorizeCodeSession(ctx context.Context, code string, session fosite.Session) (fosite.Requester, error)
- func (s *MemoryStorage) GetClient(ctx context.Context, id string) (fosite.Client, error)
- func (s *MemoryStorage) GetClientByID(ctx context.Context, id string) (*Client, error)
- func (s *MemoryStorage) GetPKCERequestSession(ctx context.Context, signature string, session fosite.Session) (fosite.Requester, error)
- func (s *MemoryStorage) GetRefreshTokenSession(ctx context.Context, signature string, session fosite.Session) (fosite.Requester, error)
- func (s *MemoryStorage) GetUserByEmail(ctx context.Context, email string) (*User, error)
- func (s *MemoryStorage) GetUserByFederationID(ctx context.Context, federationID uuid.UUID) (*User, error)
- func (s *MemoryStorage) GetUserByID(ctx context.Context, id uuid.UUID) (*User, error)
- func (s *MemoryStorage) InvalidateAuthorizeCodeSession(ctx context.Context, code string) error
- func (s *MemoryStorage) ListClients(ctx context.Context) ([]*Client, error)
- func (s *MemoryStorage) RevokeAccessToken(ctx context.Context, requestID string) error
- func (s *MemoryStorage) RevokeRefreshToken(ctx context.Context, requestID string) error
- func (s *MemoryStorage) RotateRefreshToken(ctx context.Context, requestID string, refreshTokenSignature string) error
- func (s *MemoryStorage) SetClientAssertionJWT(ctx context.Context, jti string, exp time.Time) error
- func (s *MemoryStorage) UpdateClient(ctx context.Context, client *Client) error
- func (s *MemoryStorage) UpdateUser(ctx context.Context, user *User) error
- type OAuthAuthorizeRequest
- type OAuthAuthorizeResponse
- type OAuthClient
- type OAuthClientStore
- type OAuthConsentAccept
- type OAuthConsentReject
- type OAuthConsentRequest
- type OAuthConsentResponse
- type OAuthError
- type OAuthIntrospection
- type OAuthLoginAccept
- type OAuthLoginReject
- type OAuthLoginRequest
- type OAuthLoginResponse
- type OAuthProvider
- type OAuthTokenRequest
- type OAuthTokenResponse
- type OAuthUserInfo
- type OpenIDConfigInput
- type OpenIDConfigOutput
- type OpenIDConfiguration
- type Option
- type Providers
- type ProvidersOption
- type RevokeInput
- type RevokeOutput
- type SSOSession
- type SSOTokenResponse
- type Server
- func (s *Server) GetClient(id string) (*Client, error)
- func (s *Server) Huma() huma.API
- func (s *Server) Logger() *slog.Logger
- func (s *Server) Middleware() func(http.Handler) http.Handler
- func (s *Server) OAuth2Provider() fosite.OAuth2Provider
- func (s *Server) OIDCSession(subject string, claims map[string]interface{}) *openid.DefaultSession
- func (s *Server) Observability() *observability.Observability
- func (s *Server) PublicKey() *rsa.PublicKey
- func (s *Server) RegisterClient(client *Client) error
- func (s *Server) RequireScopes(scopes ...string) func(http.Handler) http.Handler
- func (s *Server) Router() chi.Router
- func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (s *Server) Session(subject string) *openid.DefaultSession
- func (s *Server) SessionProvider() SessionProvider
- func (s *Server) Storage() Storage
- type SessionProvider
- type Storage
- type StoredRequest
- type StoredSession
- type TokenConfig
- type TokenData
- type TokenInput
- type TokenOutput
- type TokenResponse
- type User
Constants ¶
This section is empty.
Variables ¶
var ( // ErrMissingIssuer is returned when the issuer is not configured. ErrMissingIssuer = errors.New("coreauth: issuer is required") // ErrKeyGenerationFailed is returned when key generation fails. ErrKeyGenerationFailed = errors.New("coreauth: failed to generate signing key") // ErrStorageInitFailed is returned when storage initialization fails. ErrStorageInitFailed = errors.New("coreauth: failed to initialize storage") )
Configuration errors.
var ( // ErrClientNotFound is returned when a client is not found. ErrClientNotFound = errors.New("coreauth: client not found") // ErrClientExists is returned when trying to create a client that already exists. ErrClientExists = errors.New("coreauth: client already exists") // ErrInvalidClientType is returned when the client type is invalid. ErrInvalidClientType = errors.New("coreauth: invalid client type") )
Client errors.
var ( // ErrTokenNotFound is returned when a token is not found. ErrTokenNotFound = errors.New("coreauth: token not found") // ErrTokenExpired is returned when a token has expired. ErrTokenExpired = errors.New("coreauth: token expired") // ErrTokenRevoked is returned when a token has been revoked. ErrTokenRevoked = errors.New("coreauth: token revoked") // ErrInvalidToken is returned when a token is invalid. ErrInvalidToken = errors.New("coreauth: invalid token") )
Token errors.
var ( // ErrAuthCodeNotFound is returned when an authorization code is not found. ErrAuthCodeNotFound = errors.New("coreauth: authorization code not found") // ErrAuthCodeExpired is returned when an authorization code has expired. ErrAuthCodeExpired = errors.New("coreauth: authorization code expired") // ErrAuthCodeUsed is returned when an authorization code has already been used. ErrAuthCodeUsed = errors.New("coreauth: authorization code already used") // ErrPKCEVerificationFailed is returned when PKCE verification fails. ErrPKCEVerificationFailed = errors.New("coreauth: PKCE verification failed") )
Authorization errors.
var ( // ErrFederationNotConfigured is returned when federation is not configured. ErrFederationNotConfigured = errors.New("coreauth: federation not configured") // ErrFederationConnectionFailed is returned when connection to CoreControl fails. ErrFederationConnectionFailed = errors.New("coreauth: failed to connect to CoreControl") // ErrInvalidGlobalToken is returned when a global identity token is invalid. ErrInvalidGlobalToken = errors.New("coreauth: invalid global identity token") )
Federation errors.
var ( // ErrUserNotFound is returned when a user is not found. ErrUserNotFound = errors.New("coreauth: user not found") // ErrUserExists is returned when trying to create a user that already exists. ErrUserExists = errors.New("coreauth: user already exists") )
User errors.
var ( ErrInvalidCredentials = errors.New("invalid credentials") ErrSessionNotFound = errors.New("session not found") ErrSessionExpired = errors.New("session expired") ErrSessionRevoked = errors.New("session revoked") )
Common authentication errors.
Functions ¶
func AccessRequestFromContext ¶
func AccessRequestFromContext(ctx context.Context) fosite.AccessRequester
AccessRequestFromContext retrieves the access request from context.
func ContextWithOwnerID ¶
ContextWithOwnerID adds an owner ID to the context.
func LoggerFromContext ¶
LoggerFromContext returns the logger from context, or slog.Default() if not set.
func SaveConfig ¶
SaveConfig saves configuration to a file. The format is determined by the file extension.
func WithAccessRequest ¶
WithAccessRequest adds the access request to the context.
Types ¶
type AuthCodeData ¶
type AuthCodeData struct {
// Signature is the hashed authorization code.
Signature string
// ClientID is the client that requested the code.
ClientID string
// Subject is the user ID.
Subject string
// RedirectURI is the callback URI.
RedirectURI string
// Scopes are the requested scopes.
Scopes []string
// GrantedScopes are the granted scopes.
GrantedScopes []string
// State is the CSRF state parameter.
State string
// CodeChallenge is the PKCE code challenge.
CodeChallenge string
// CodeChallengeMethod is the PKCE method (S256 or plain).
CodeChallengeMethod string
// Nonce is the OpenID Connect nonce.
Nonce string
// Session holds the session data.
Session *StoredSession
// ExpiresAt is when the code expires.
ExpiresAt int64
// Used indicates the code has been exchanged.
Used bool
}
AuthCodeData holds authorization code storage data.
type AuthMethod ¶ added in v0.3.0
type AuthMethod string
AuthMethod is the authentication method.
const ( AuthMethodPassword AuthMethod = "password" AuthMethodOIDC AuthMethod = "oidc" AuthMethodWebAuthn AuthMethod = "webauthn" AuthMethodTOTP AuthMethod = "totp" )
type AuthSession ¶ added in v0.3.0
type AuthSession struct {
// ID is the session ID.
ID string `json:"id"`
// Token is the session token (cookie value).
Token string `json:"token"`
// IdentityID is the authenticated identity.
IdentityID uuid.UUID `json:"identity_id"`
// Identity contains identity details (optional, may be nil).
Identity *Identity `json:"identity,omitempty"`
// AuthenticatedAt is when authentication occurred.
AuthenticatedAt time.Time `json:"authenticated_at"`
// ExpiresAt is when the session expires.
ExpiresAt time.Time `json:"expires_at"`
// AuthenticationMethods used in this session.
AuthenticationMethods []AuthMethod `json:"authentication_methods,omitempty"`
// Active indicates if the session is still valid.
Active bool `json:"active"`
// DeviceInfo about the session.
DeviceInfo *DeviceInfo `json:"device_info,omitempty"`
}
AuthSession represents an authentication session.
type AuthenticateRequest ¶ added in v0.3.0
type AuthenticateRequest struct {
// Method is the authentication method.
Method AuthMethod `json:"method"`
// Identifier is the user identifier (email, username, etc.).
Identifier string `json:"identifier"`
// Password is used for password authentication.
Password string `json:"password,omitempty"`
// OIDCToken is used for OIDC authentication.
OIDCToken string `json:"oidc_token,omitempty"`
// OIDCProvider is the OIDC provider name.
OIDCProvider string `json:"oidc_provider,omitempty"`
// DeviceInfo contains device/client information.
DeviceInfo *DeviceInfo `json:"device_info,omitempty"`
}
AuthenticateRequest contains authentication credentials.
type AuthenticationProvider ¶ added in v0.3.0
type AuthenticationProvider interface {
// Authenticate validates credentials and creates a session.
Authenticate(ctx context.Context, req *AuthenticateRequest) (*AuthSession, error)
// ValidateSession validates a session token and returns session info.
ValidateSession(ctx context.Context, sessionToken string) (*AuthSession, error)
// RefreshSession extends a session's lifetime.
RefreshSession(ctx context.Context, sessionToken string) (*AuthSession, error)
// RevokeSession invalidates a session.
RevokeSession(ctx context.Context, sessionToken string) error
// RevokeSessions invalidates all sessions for an identity.
RevokeSessions(ctx context.Context, identityID uuid.UUID) error
// ListSessions lists active sessions for an identity.
ListSessions(ctx context.Context, identityID uuid.UUID) ([]*AuthSession, error)
}
AuthenticationProvider manages user authentication sessions. In Ory Kratos, this maps to the session management API.
type AuthorizationSession ¶
type AuthorizationSession struct {
// RequestID uniquely identifies this authorization request.
RequestID string `json:"request_id"`
// ClientID is the OAuth client requesting authorization.
ClientID string `json:"client_id"`
// RedirectURI is the client's callback URL.
RedirectURI string `json:"redirect_uri"`
// Scopes requested by the client.
Scopes []string `json:"scopes"`
// State is the client's CSRF token.
State string `json:"state"`
// Nonce is the OpenID Connect nonce for replay protection.
Nonce string `json:"nonce,omitempty"`
// CodeChallenge is the PKCE code challenge.
CodeChallenge string `json:"code_challenge,omitempty"`
// CodeChallengeMethod is the PKCE challenge method.
CodeChallengeMethod string `json:"code_challenge_method,omitempty"`
// UserID is set after authentication.
UserID string `json:"user_id,omitempty"`
// ConsentGranted is set after user consents to scopes.
ConsentGranted bool `json:"consent_granted"`
// GrantedScopes are the scopes the user consented to.
GrantedScopes []string `json:"granted_scopes,omitempty"`
// CreatedAt is when this session was created.
CreatedAt time.Time `json:"created_at"`
// ExpiresAt is when this session expires.
ExpiresAt time.Time `json:"expires_at"`
}
AuthorizationSession holds the session data for an authorization request. This can be stored in a session store to persist across redirects.
func NewAuthorizationSession ¶
func NewAuthorizationSession(ar fosite.AuthorizeRequester) *AuthorizationSession
NewAuthorizationSession creates a new authorization session from a Fosite request.
func (*AuthorizationSession) IsExpired ¶
func (s *AuthorizationSession) IsExpired() bool
IsExpired returns true if the session has expired.
type AuthorizeInput ¶
type AuthorizeInput struct {
ResponseType string `query:"response_type" required:"true" enum:"code,token" doc:"OAuth 2.0 response type"`
ClientID string `query:"client_id" required:"true" doc:"Client identifier"`
RedirectURI string `query:"redirect_uri" doc:"URI to redirect after authorization"`
Scope string `query:"scope" doc:"Space-separated list of requested scopes"`
State string `query:"state" doc:"Opaque value for CSRF protection"`
CodeChallenge string `query:"code_challenge" doc:"PKCE code challenge"`
CodeChallengeMethod string `query:"code_challenge_method" enum:"S256,plain" doc:"PKCE code challenge method"`
Nonce string `query:"nonce" doc:"OpenID Connect nonce for replay protection"`
}
AuthorizeInput represents the OAuth 2.0 authorization request parameters.
type AuthorizeOutput ¶
type AuthorizeOutput struct {
Location string `header:"Location" doc:"Redirect URI with authorization code or token"`
}
AuthorizeOutput represents the authorization response (redirect).
type Client ¶
type Client struct {
// ID is the client identifier.
ID string `json:"id"`
// Secret is the client secret (never serialized).
Secret string `json:"-"`
// SecretHash is the bcrypt hash of the secret.
SecretHash string `json:"secret_hash,omitempty"`
// Type is "public" or "confidential".
Type ClientType `json:"type"`
// Name is a human-readable name.
Name string `json:"name"`
// Description is an optional description.
Description string `json:"description,omitempty"`
// RedirectURIs are allowed redirect URIs.
RedirectURIs []string `json:"redirect_uris"`
// GrantTypes are allowed grant types.
GrantTypes []string `json:"grant_types"`
// ResponseTypes are allowed response types.
ResponseTypes []string `json:"response_types"`
// Scopes are allowed scopes.
Scopes []string `json:"scopes"`
// Audience restricts the token audience.
Audience []string `json:"audience,omitempty"`
// AccessTokenLifetime overrides the default for this client.
AccessTokenLifetime *time.Duration `json:"access_token_lifetime,omitempty"`
// RefreshTokenLifetime overrides the default for this client.
RefreshTokenLifetime *time.Duration `json:"refresh_token_lifetime,omitempty"`
// Metadata holds arbitrary client metadata.
Metadata map[string]any `json:"metadata,omitempty"`
// CreatedAt is when the client was created.
CreatedAt time.Time `json:"created_at"`
// UpdatedAt is when the client was last updated.
UpdatedAt time.Time `json:"updated_at"`
}
Client represents an OAuth 2.0 client.
func NewClientFromConfig ¶
func NewClientFromConfig(cfg ClientConfig) (*Client, error)
NewClientFromConfig creates a Client from a ClientConfig.
func (*Client) GetAudience ¶
GetAudience returns the allowed audiences.
func (*Client) GetGrantTypes ¶
GetGrantTypes returns the allowed grant types.
func (*Client) GetHashedSecret ¶
GetHashedSecret returns the hashed client secret.
func (*Client) GetRedirectURIs ¶
GetRedirectURIs returns the allowed redirect URIs.
func (*Client) GetResponseTypes ¶
GetResponseTypes returns the allowed response types.
func (*Client) ValidateSecret ¶
ValidateSecret checks if the provided secret matches the stored hash.
type ClientConfig ¶
type ClientConfig struct {
// ID is the client identifier.
ID string `json:"id" yaml:"id" jsonschema:"required,description=Unique client identifier"`
// Secret is the client secret (for confidential clients).
// Supports environment variable expansion: ${CLIENT_SECRET}
Secret string `json:"secret,omitempty" yaml:"secret,omitempty" jsonschema:"description=Client secret (supports env var expansion)"`
// Type is "public" or "confidential".
Type string `json:"type" yaml:"type" jsonschema:"required,enum=public,enum=confidential,description=Client type"`
// Name is a human-readable name.
Name string `json:"name" yaml:"name" jsonschema:"required,description=Human-readable client name"`
// Description is an optional description.
Description string `json:"description,omitempty" yaml:"description,omitempty" jsonschema:"description=Client description"`
// RedirectURIs are allowed redirect URIs.
RedirectURIs []string `json:"redirect_uris,omitempty" yaml:"redirect_uris,omitempty" jsonschema:"description=Allowed redirect URIs"`
// GrantTypes are allowed grant types.
// Options: "authorization_code", "refresh_token", "client_credentials"
GrantTypes []string `json:"grant_types,omitempty" yaml:"grant_types,omitempty" jsonschema:"description=Allowed OAuth grant types"`
// ResponseTypes are allowed response types.
// Options: "code", "token"
ResponseTypes []string `json:"response_types,omitempty" yaml:"response_types,omitempty" jsonschema:"description=Allowed OAuth response types"`
// Scopes are allowed scopes.
Scopes []string `json:"scopes,omitempty" yaml:"scopes,omitempty" jsonschema:"description=Allowed OAuth scopes"`
// Audience restricts the token audience.
Audience []string `json:"audience,omitempty" yaml:"audience,omitempty" jsonschema:"description=Allowed token audiences"`
// AccessTokenLifetime overrides the default for this client.
AccessTokenLifetime *Duration `` /* 140-byte string literal not displayed */
// RefreshTokenLifetime overrides the default for this client.
RefreshTokenLifetime *Duration `` /* 143-byte string literal not displayed */
}
ClientConfig defines a statically configured OAuth client.
type ClientManager ¶
type ClientManager interface {
// CreateClient creates a new OAuth client.
CreateClient(ctx context.Context, client *Client) error
// GetClientByID retrieves a client by ID.
GetClientByID(ctx context.Context, id string) (*Client, error)
// UpdateClient updates an existing client.
UpdateClient(ctx context.Context, client *Client) error
// DeleteClient deletes a client.
DeleteClient(ctx context.Context, id string) error
// ListClients returns all clients.
ListClients(ctx context.Context) ([]*Client, error)
}
ClientManager provides CRUD operations for OAuth clients.
type ClientType ¶
type ClientType string
ClientType defines whether a client is public or confidential.
const ( // ClientTypePublic is for clients that cannot keep secrets (SPAs, mobile apps). ClientTypePublic ClientType = "public" // ClientTypeConfidential is for clients that can keep secrets (server apps). ClientTypeConfidential ClientType = "confidential" )
type Config ¶
type Config struct {
// Issuer is the OAuth/OIDC issuer URL (required).
// Example: "https://auth.example.com"
Issuer string `json:"issuer" yaml:"issuer" jsonschema:"required,format=uri,description=OAuth/OIDC issuer URL"`
// Database configures persistent storage.
// If nil, in-memory storage is used (suitable for embedded mode).
Database *DatabaseConfig `json:"database,omitempty" yaml:"database,omitempty" jsonschema:"description=Database configuration for persistent storage"`
// Keys configures signing key management.
Keys KeyConfig `json:"keys,omitempty" yaml:"keys,omitempty" jsonschema:"description=Signing key configuration"`
// Tokens configures token lifetimes.
Tokens TokenConfig `json:"tokens,omitempty" yaml:"tokens,omitempty" jsonschema:"description=Token lifetime configuration"`
// Clients defines statically configured OAuth clients.
Clients []ClientConfig `json:"clients,omitempty" yaml:"clients,omitempty" jsonschema:"description=Static OAuth client configurations"`
// Federation configures CoreControl integration.
Federation *FederationConfig `json:"federation,omitempty" yaml:"federation,omitempty" jsonschema:"description=CoreControl federation configuration"`
// Features enables/disables optional features.
Features FeatureConfig `json:"features,omitempty" yaml:"features,omitempty" jsonschema:"description=Feature flags"`
}
Config holds CoreAuth server configuration. This is the root configuration object for both embedded and standalone modes.
func DefaultConfig ¶
DefaultConfig returns a Config with sensible defaults for embedded mode.
func LoadConfig ¶
LoadConfig loads configuration from a file. Supports both YAML (.yaml, .yml) and JSON (.json) formats. The format is detected by file extension.
func ParseConfig ¶
func ParseConfig(data []byte, format ConfigFormat) (*Config, error)
ParseConfig parses configuration from bytes in the specified format.
func (*Config) ApplyDefaults ¶
func (c *Config) ApplyDefaults()
ApplyDefaults fills in missing values with defaults.
type ConfigFormat ¶
type ConfigFormat string
ConfigFormat represents a configuration file format.
const ( // FormatYAML indicates YAML format. FormatYAML ConfigFormat = "yaml" // FormatJSON indicates JSON format. FormatJSON ConfigFormat = "json" )
type ConsentSession ¶ added in v0.3.0
type ConsentSession struct {
AccessToken map[string]any `json:"access_token,omitempty"`
IDToken map[string]any `json:"id_token,omitempty"`
}
ConsentSession holds session data for consent.
type CoreControlDiscovery ¶
type CoreControlDiscovery 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"`
IntrospectionEndpoint string `json:"introspection_endpoint"`
RevocationEndpoint string `json:"revocation_endpoint"`
ScopesSupported []string `json:"scopes_supported"`
}
CoreControlDiscovery holds the OIDC discovery configuration from CoreControl.
type CredentialType ¶ added in v0.3.0
type CredentialType string
CredentialType is the type of credential.
const ( CredentialTypePassword CredentialType = "password" CredentialTypeOIDC CredentialType = "oidc" CredentialTypeWebAuthn CredentialType = "webauthn" CredentialTypeTOTP CredentialType = "totp" )
type DatabaseConfig ¶
type DatabaseConfig struct {
// Driver is the database driver: "postgres", "sqlite", "mysql"
Driver string `json:"driver" yaml:"driver" jsonschema:"required,enum=postgres,enum=sqlite,enum=mysql,description=Database driver"`
// DSN is the database connection string.
// Supports environment variable expansion: ${DATABASE_URL}
DSN string `json:"dsn" yaml:"dsn" jsonschema:"required,description=Database connection string (supports env var expansion)"`
}
DatabaseConfig configures persistent storage.
type DefaultIdentitySyncHandler ¶
type DefaultIdentitySyncHandler struct {
// contains filtered or unexported fields
}
DefaultIdentitySyncHandler provides a basic implementation that creates local users.
func NewDefaultIdentitySyncHandler ¶
func NewDefaultIdentitySyncHandler(storage Storage) *DefaultIdentitySyncHandler
NewDefaultIdentitySyncHandler creates a sync handler that uses the storage.
func (*DefaultIdentitySyncHandler) SyncIdentity ¶
func (h *DefaultIdentitySyncHandler) SyncIdentity(ctx context.Context, req *IdentitySyncRequest) (*IdentitySyncResponse, error)
SyncIdentity implements IdentitySyncHandler.
type DefaultSessionProvider ¶
type DefaultSessionProvider struct {
// contains filtered or unexported fields
}
DefaultSessionProvider provides a basic session provider for testing. In production, implement SessionProvider with your authentication system.
func NewDefaultSessionProvider ¶
func NewDefaultSessionProvider(opts ...DefaultSessionProviderOption) *DefaultSessionProvider
NewDefaultSessionProvider creates a default session provider.
func (*DefaultSessionProvider) GetAuthenticatedUser ¶
func (p *DefaultSessionProvider) GetAuthenticatedUser(r *http.Request) string
GetAuthenticatedUser returns the user ID from the configured header.
func (*DefaultSessionProvider) GetUserClaims ¶
func (p *DefaultSessionProvider) GetUserClaims(_ context.Context, userID string, _ []string) map[string]interface{}
GetUserClaims returns an empty map. Override this in production to return actual user claims.
func (*DefaultSessionProvider) HasConsent ¶
HasConsent always returns the value of skipConsent. Override this in production to check actual consent records.
func (*DefaultSessionProvider) RedirectToConsent ¶
func (p *DefaultSessionProvider) RedirectToConsent(returnURL string) string
RedirectToConsent returns the consent URL with return URL parameter.
func (*DefaultSessionProvider) RedirectToLogin ¶
func (p *DefaultSessionProvider) RedirectToLogin(returnURL string) string
RedirectToLogin returns the login URL with return URL parameter.
func (*DefaultSessionProvider) SaveConsent ¶
SaveConsent is a no-op in the default provider. Override this in production to persist consent records.
type DefaultSessionProviderOption ¶
type DefaultSessionProviderOption func(*DefaultSessionProvider)
DefaultSessionProviderOption configures a DefaultSessionProvider.
func WithConsentURL ¶
func WithConsentURL(url string) DefaultSessionProviderOption
WithConsentURL sets the consent redirect URL.
func WithLoginURL ¶
func WithLoginURL(url string) DefaultSessionProviderOption
WithLoginURL sets the login redirect URL.
func WithSkipConsent ¶
func WithSkipConsent(skip bool) DefaultSessionProviderOption
WithSkipConsent enables automatic consent for all requests.
func WithUserIDHeader ¶
func WithUserIDHeader(header string) DefaultSessionProviderOption
WithUserIDHeader sets the header to read user ID from. Default is "X-User-ID".
type DeviceInfo ¶ added in v0.3.0
type DeviceInfo struct {
IPAddress string `json:"ip_address,omitempty"`
UserAgent string `json:"user_agent,omitempty"`
DeviceID string `json:"device_id,omitempty"`
}
DeviceInfo contains information about the authenticating device.
type Duration ¶
Duration is a wrapper around time.Duration that supports human-readable string serialization (e.g., "15m", "1h", "7d").
func (Duration) JSONSchema ¶
func (Duration) JSONSchema() *jsonschema.Schema
JSONSchema implements jsonschema.JSONSchemaer for Duration.
func (Duration) MarshalJSON ¶
MarshalJSON implements json.Marshaler.
func (Duration) MarshalYAML ¶
MarshalYAML implements yaml.Marshaler.
func (*Duration) UnmarshalJSON ¶
UnmarshalJSON implements json.Unmarshaler.
func (*Duration) UnmarshalYAML ¶
UnmarshalYAML implements yaml.Unmarshaler.
type EmbeddedAuthProvider ¶ added in v0.3.0
type EmbeddedAuthProvider struct {
// contains filtered or unexported fields
}
EmbeddedAuthProvider implements AuthenticationProvider with in-memory session storage. For production, use a persistent session store (Redis, database, etc.).
func NewEmbeddedAuthProvider ¶ added in v0.3.0
func NewEmbeddedAuthProvider(identityProvider IdentityProvider, opts ...EmbeddedAuthProviderOption) *EmbeddedAuthProvider
NewEmbeddedAuthProvider creates an AuthenticationProvider with in-memory sessions.
func (*EmbeddedAuthProvider) Authenticate ¶ added in v0.3.0
func (p *EmbeddedAuthProvider) Authenticate(ctx context.Context, req *AuthenticateRequest) (*AuthSession, error)
Authenticate implements AuthenticationProvider.
func (*EmbeddedAuthProvider) ListSessions ¶ added in v0.3.0
func (p *EmbeddedAuthProvider) ListSessions(ctx context.Context, identityID uuid.UUID) ([]*AuthSession, error)
ListSessions implements AuthenticationProvider.
func (*EmbeddedAuthProvider) RefreshSession ¶ added in v0.3.0
func (p *EmbeddedAuthProvider) RefreshSession(ctx context.Context, sessionToken string) (*AuthSession, error)
RefreshSession implements AuthenticationProvider.
func (*EmbeddedAuthProvider) RevokeSession ¶ added in v0.3.0
func (p *EmbeddedAuthProvider) RevokeSession(ctx context.Context, sessionToken string) error
RevokeSession implements AuthenticationProvider.
func (*EmbeddedAuthProvider) RevokeSessions ¶ added in v0.3.0
RevokeSessions implements AuthenticationProvider.
func (*EmbeddedAuthProvider) ValidateSession ¶ added in v0.3.0
func (p *EmbeddedAuthProvider) ValidateSession(ctx context.Context, sessionToken string) (*AuthSession, error)
ValidateSession implements AuthenticationProvider.
type EmbeddedAuthProviderOption ¶ added in v0.3.0
type EmbeddedAuthProviderOption func(*EmbeddedAuthProvider)
EmbeddedAuthProviderOption configures an EmbeddedAuthProvider.
func WithPasswordVerifier ¶ added in v0.3.0
func WithPasswordVerifier(verifier func(ctx context.Context, identityID uuid.UUID, password string) (bool, error)) EmbeddedAuthProviderOption
WithPasswordVerifier sets the password verification function.
func WithSessionDuration ¶ added in v0.3.0
func WithSessionDuration(d time.Duration) EmbeddedAuthProviderOption
WithSessionDuration sets the session duration.
type EmbeddedIdentityProvider ¶ added in v0.3.0
type EmbeddedIdentityProvider struct {
// contains filtered or unexported fields
}
EmbeddedIdentityProvider implements IdentityProvider using the embedded storage.
func NewEmbeddedIdentityProvider ¶ added in v0.3.0
func NewEmbeddedIdentityProvider(storage Storage) *EmbeddedIdentityProvider
NewEmbeddedIdentityProvider creates an IdentityProvider backed by CoreAuth storage.
func (*EmbeddedIdentityProvider) CreateIdentity ¶ added in v0.3.0
func (p *EmbeddedIdentityProvider) CreateIdentity(ctx context.Context, identity *Identity) error
CreateIdentity implements IdentityProvider.
func (*EmbeddedIdentityProvider) DeleteIdentity ¶ added in v0.3.0
DeleteIdentity implements IdentityProvider.
func (*EmbeddedIdentityProvider) GetIdentity ¶ added in v0.3.0
func (p *EmbeddedIdentityProvider) GetIdentity(ctx context.Context, id uuid.UUID) (*Identity, error)
GetIdentity implements IdentityProvider.
func (*EmbeddedIdentityProvider) GetIdentityByEmail ¶ added in v0.3.0
func (p *EmbeddedIdentityProvider) GetIdentityByEmail(ctx context.Context, email string) (*Identity, error)
GetIdentityByEmail implements IdentityProvider.
func (*EmbeddedIdentityProvider) ListIdentities ¶ added in v0.3.0
func (p *EmbeddedIdentityProvider) ListIdentities(ctx context.Context, filter *IdentityFilter) ([]*Identity, error)
ListIdentities implements IdentityProvider. Note: The embedded storage doesn't support listing, so this returns an error.
func (*EmbeddedIdentityProvider) UpdateIdentity ¶ added in v0.3.0
func (p *EmbeddedIdentityProvider) UpdateIdentity(ctx context.Context, identity *Identity) error
UpdateIdentity implements IdentityProvider.
type EmbeddedOAuthClientStore ¶ added in v0.3.0
type EmbeddedOAuthClientStore struct {
// contains filtered or unexported fields
}
EmbeddedOAuthClientStore implements OAuthClientStore using CoreAuth storage.
func NewEmbeddedOAuthClientStore ¶ added in v0.3.0
func NewEmbeddedOAuthClientStore(storage Storage) *EmbeddedOAuthClientStore
NewEmbeddedOAuthClientStore creates an OAuthClientStore backed by CoreAuth storage.
func (*EmbeddedOAuthClientStore) CreateClient ¶ added in v0.3.0
func (s *EmbeddedOAuthClientStore) CreateClient(ctx context.Context, client *OAuthClient) error
CreateClient implements OAuthClientStore.
func (*EmbeddedOAuthClientStore) DeleteClient ¶ added in v0.3.0
func (s *EmbeddedOAuthClientStore) DeleteClient(ctx context.Context, clientID string) error
DeleteClient implements OAuthClientStore.
func (*EmbeddedOAuthClientStore) GetClient ¶ added in v0.3.0
func (s *EmbeddedOAuthClientStore) GetClient(ctx context.Context, clientID string) (*OAuthClient, error)
GetClient implements OAuthClientStore.
func (*EmbeddedOAuthClientStore) ListClients ¶ added in v0.3.0
func (s *EmbeddedOAuthClientStore) ListClients(ctx context.Context) ([]*OAuthClient, error)
ListClients implements OAuthClientStore.
func (*EmbeddedOAuthClientStore) UpdateClient ¶ added in v0.3.0
func (s *EmbeddedOAuthClientStore) UpdateClient(ctx context.Context, client *OAuthClient) error
UpdateClient implements OAuthClientStore.
type EmbeddedOAuthProvider ¶ added in v0.3.0
type EmbeddedOAuthProvider struct {
// contains filtered or unexported fields
}
EmbeddedOAuthProvider implements OAuthProvider using Fosite.
func NewEmbeddedOAuthProvider ¶ added in v0.3.0
func NewEmbeddedOAuthProvider(server *Server) *EmbeddedOAuthProvider
NewEmbeddedOAuthProvider creates an OAuthProvider backed by a CoreAuth Server.
func (*EmbeddedOAuthProvider) AcceptConsent ¶ added in v0.3.0
func (p *EmbeddedOAuthProvider) AcceptConsent(ctx context.Context, challenge string, accept *OAuthConsentAccept) (*OAuthConsentResponse, error)
AcceptConsent implements OAuthProvider.
func (*EmbeddedOAuthProvider) AcceptLogin ¶ added in v0.3.0
func (p *EmbeddedOAuthProvider) AcceptLogin(ctx context.Context, challenge string, accept *OAuthLoginAccept) (*OAuthLoginResponse, error)
AcceptLogin implements OAuthProvider.
func (*EmbeddedOAuthProvider) Authorize ¶ added in v0.3.0
func (p *EmbeddedOAuthProvider) Authorize(ctx context.Context, req *OAuthAuthorizeRequest) (*OAuthAuthorizeResponse, error)
Authorize implements OAuthProvider. Note: This is typically handled by the HTTP handler; this method is for programmatic access.
func (*EmbeddedOAuthProvider) GetConsentRequest ¶ added in v0.3.0
func (p *EmbeddedOAuthProvider) GetConsentRequest(ctx context.Context, challenge string) (*OAuthConsentRequest, error)
GetConsentRequest implements OAuthProvider. This is used for the consent flow when separating login/consent UI.
func (*EmbeddedOAuthProvider) GetLoginRequest ¶ added in v0.3.0
func (p *EmbeddedOAuthProvider) GetLoginRequest(ctx context.Context, challenge string) (*OAuthLoginRequest, error)
GetLoginRequest implements OAuthProvider.
func (*EmbeddedOAuthProvider) Introspect ¶ added in v0.3.0
func (p *EmbeddedOAuthProvider) Introspect(ctx context.Context, token string, tokenTypeHint string) (*OAuthIntrospection, error)
Introspect implements OAuthProvider.
func (*EmbeddedOAuthProvider) RejectConsent ¶ added in v0.3.0
func (p *EmbeddedOAuthProvider) RejectConsent(ctx context.Context, challenge string, reject *OAuthConsentReject) (*OAuthConsentResponse, error)
RejectConsent implements OAuthProvider.
func (*EmbeddedOAuthProvider) RejectLogin ¶ added in v0.3.0
func (p *EmbeddedOAuthProvider) RejectLogin(ctx context.Context, challenge string, reject *OAuthLoginReject) (*OAuthLoginResponse, error)
RejectLogin implements OAuthProvider.
func (*EmbeddedOAuthProvider) Revoke ¶ added in v0.3.0
func (p *EmbeddedOAuthProvider) Revoke(ctx context.Context, token string, tokenTypeHint string) error
Revoke implements OAuthProvider.
func (*EmbeddedOAuthProvider) Token ¶ added in v0.3.0
func (p *EmbeddedOAuthProvider) Token(ctx context.Context, req *OAuthTokenRequest) (*OAuthTokenResponse, error)
Token implements OAuthProvider. Note: This is typically handled by the HTTP handler; this method is for programmatic access.
func (*EmbeddedOAuthProvider) UserInfo ¶ added in v0.3.0
func (p *EmbeddedOAuthProvider) UserInfo(ctx context.Context, accessToken string) (*OAuthUserInfo, error)
UserInfo implements OAuthProvider.
type EntStorage ¶
type EntStorage struct {
// contains filtered or unexported fields
}
EntStorage implements Storage using Ent ORM.
func NewEntStorage ¶
func NewEntStorage(db *ent.Client, opts ...EntStorageOption) *EntStorage
NewEntStorage creates a new Ent-backed storage.
func (*EntStorage) ClientAssertionJWTValid ¶
func (s *EntStorage) ClientAssertionJWTValid(ctx context.Context, jti string) error
ClientAssertionJWTValid checks if a JWT ID has been used.
func (*EntStorage) CreateAccessTokenSession ¶
func (s *EntStorage) CreateAccessTokenSession(ctx context.Context, signature string, request fosite.Requester) error
CreateAccessTokenSession stores an access token session.
func (*EntStorage) CreateAuthorizeCodeSession ¶
func (s *EntStorage) CreateAuthorizeCodeSession(ctx context.Context, code string, request fosite.Requester) error
CreateAuthorizeCodeSession stores an authorization code session.
func (*EntStorage) CreateClient ¶
func (s *EntStorage) CreateClient(ctx context.Context, client *Client) error
CreateClient creates a new OAuth client.
func (*EntStorage) CreatePKCERequestSession ¶
func (s *EntStorage) CreatePKCERequestSession(ctx context.Context, signature string, requester fosite.Requester) error
CreatePKCERequestSession creates a PKCE session (stored with auth code).
func (*EntStorage) CreateRefreshTokenSession ¶
func (s *EntStorage) CreateRefreshTokenSession(ctx context.Context, signature string, accessSignature string, request fosite.Requester) error
CreateRefreshTokenSession stores a refresh token session.
func (*EntStorage) CreateUser ¶
func (s *EntStorage) CreateUser(ctx context.Context, user *User) error
CreateUser creates a new user from federation sync.
func (*EntStorage) DeleteAccessTokenSession ¶
func (s *EntStorage) DeleteAccessTokenSession(ctx context.Context, signature string) error
DeleteAccessTokenSession removes an access token session.
func (*EntStorage) DeleteClient ¶
func (s *EntStorage) DeleteClient(ctx context.Context, id string) error
DeleteClient deletes a client.
func (*EntStorage) DeletePKCERequestSession ¶
func (s *EntStorage) DeletePKCERequestSession(ctx context.Context, signature string) error
DeletePKCERequestSession deletes a PKCE session.
func (*EntStorage) DeleteRefreshTokenSession ¶
func (s *EntStorage) DeleteRefreshTokenSession(ctx context.Context, signature string) error
DeleteRefreshTokenSession removes a refresh token session.
func (*EntStorage) DeleteUser ¶
DeleteUser deletes a user.
func (*EntStorage) GetAccessTokenSession ¶
func (s *EntStorage) GetAccessTokenSession(ctx context.Context, signature string, session fosite.Session) (fosite.Requester, error)
GetAccessTokenSession retrieves an access token session.
func (*EntStorage) GetAuthorizeCodeSession ¶
func (s *EntStorage) GetAuthorizeCodeSession(ctx context.Context, code string, session fosite.Session) (fosite.Requester, error)
GetAuthorizeCodeSession retrieves an authorization code session.
func (*EntStorage) GetClientByID ¶
GetClientByID retrieves a client by ID.
func (*EntStorage) GetPKCERequestSession ¶
func (s *EntStorage) GetPKCERequestSession(ctx context.Context, signature string, session fosite.Session) (fosite.Requester, error)
GetPKCERequestSession gets the PKCE session for a code.
func (*EntStorage) GetRefreshTokenSession ¶
func (s *EntStorage) GetRefreshTokenSession(ctx context.Context, signature string, session fosite.Session) (fosite.Requester, error)
GetRefreshTokenSession retrieves a refresh token session.
func (*EntStorage) GetUserByEmail ¶
GetUserByEmail retrieves a user by email.
func (*EntStorage) GetUserByFederationID ¶
func (s *EntStorage) GetUserByFederationID(ctx context.Context, federationID uuid.UUID) (*User, error)
GetUserByFederationID retrieves a user by their federation ID.
func (*EntStorage) GetUserByID ¶
GetUserByID retrieves a user by ID.
func (*EntStorage) InvalidateAuthorizeCodeSession ¶
func (s *EntStorage) InvalidateAuthorizeCodeSession(ctx context.Context, code string) error
InvalidateAuthorizeCodeSession marks an authorization code as used.
func (*EntStorage) ListClients ¶
func (s *EntStorage) ListClients(ctx context.Context) ([]*Client, error)
ListClients returns all clients.
func (*EntStorage) RevokeAccessToken ¶
func (s *EntStorage) RevokeAccessToken(ctx context.Context, requestID string) error
RevokeAccessToken revokes an access token by request ID.
func (*EntStorage) RevokeRefreshToken ¶
func (s *EntStorage) RevokeRefreshToken(ctx context.Context, requestID string) error
RevokeRefreshToken revokes a refresh token by request ID (family).
func (*EntStorage) RotateRefreshToken ¶
func (s *EntStorage) RotateRefreshToken(ctx context.Context, requestID string, refreshTokenSignature string) error
RotateRefreshToken handles refresh token rotation.
func (*EntStorage) SetClientAssertionJWT ¶
SetClientAssertionJWT marks a JWT ID as used.
func (*EntStorage) UpdateClient ¶
func (s *EntStorage) UpdateClient(ctx context.Context, client *Client) error
UpdateClient updates an existing client.
func (*EntStorage) UpdateUser ¶
func (s *EntStorage) UpdateUser(ctx context.Context, user *User) error
UpdateUser updates an existing user.
func (*EntStorage) ValidateSecretArgon2id ¶
func (s *EntStorage) ValidateSecretArgon2id(ctx context.Context, clientID, secret string) error
ValidateSecretArgon2id validates a client secret using Argon2id.
type EntStorageOption ¶
type EntStorageOption func(*EntStorage)
EntStorageOption configures EntStorage.
func WithDefaultOwner ¶
func WithDefaultOwner(ownerID uuid.UUID) EntStorageOption
WithDefaultOwner sets the default owner ID for new clients. This is used when creating clients without an explicit owner context.
type FeatureConfig ¶
type FeatureConfig struct {
// RequirePKCE requires PKCE for all authorization code flows.
// Default: true for public clients, configurable for confidential
RequirePKCE bool `` /* 139-byte string literal not displayed */
// AllowDynamicRegistration enables RFC 7591 dynamic client registration.
AllowDynamicRegistration bool `` /* 172-byte string literal not displayed */
// EnableDeviceFlow enables the device authorization grant (RFC 8628).
EnableDeviceFlow bool `` /* 155-byte string literal not displayed */
// EnableJWTAccessTokens issues JWT access tokens instead of opaque tokens.
EnableJWTAccessTokens bool `` /* 171-byte string literal not displayed */
}
FeatureConfig enables/disables optional features.
type FederationClient ¶
type FederationClient struct {
// contains filtered or unexported fields
}
FederationClient connects a CoreAuth app to CoreControl for SSO.
func NewFederationClient ¶
func NewFederationClient(config *FederationConfig) (*FederationClient, error)
NewFederationClient creates a new federation client.
func (*FederationClient) Config ¶
func (c *FederationClient) Config() *FederationConfig
Config returns the federation configuration.
func (*FederationClient) Discovery ¶
func (c *FederationClient) Discovery() *CoreControlDiscovery
Discovery returns the CoreControl discovery document.
func (*FederationClient) ExchangeCode ¶
func (c *FederationClient) ExchangeCode(ctx context.Context, code, redirectURI string) (*SSOTokenResponse, error)
ExchangeCode exchanges an authorization code from CoreControl for tokens.
func (*FederationClient) GetGlobalIdentity ¶
func (c *FederationClient) GetGlobalIdentity(ctx context.Context, globalID uuid.UUID) (*GlobalIdentity, error)
GetGlobalIdentity retrieves a global identity from CoreControl.
func (*FederationClient) GetIdentityMapping ¶
func (c *FederationClient) GetIdentityMapping(ctx context.Context, globalID uuid.UUID) (*IdentityMapping, error)
GetIdentityMapping retrieves the mapping for a global identity in this app.
func (*FederationClient) GetSSOAuthorizationURL ¶
func (c *FederationClient) GetSSOAuthorizationURL(ctx context.Context, state, redirectURI string) (string, error)
GetSSOAuthorizationURL generates the URL to redirect users to CoreControl for SSO.
func (*FederationClient) Initialize ¶
func (c *FederationClient) Initialize(ctx context.Context) error
Initialize fetches the CoreControl discovery document.
func (*FederationClient) NotifyAppAccess ¶
NotifyAppAccess records that a user accessed this app via SSO.
func (*FederationClient) RegisterWithCoreControl ¶
func (c *FederationClient) RegisterWithCoreControl(ctx context.Context, federationID uuid.UUID, displayName, baseURL string, capabilities []string) error
RegisterWithCoreControl registers this app with a federation.
func (*FederationClient) ValidateSSOSession ¶
func (c *FederationClient) ValidateSSOSession(ctx context.Context, sessionID uuid.UUID) (*SSOSession, error)
ValidateSSOSession validates an SSO session with CoreControl.
type FederationConfig ¶
type FederationConfig struct {
// Enabled enables federation mode.
Enabled bool `json:"enabled" yaml:"enabled" jsonschema:"description=Enable CoreControl federation"`
// CoreControlURL is the CoreControl server URL.
CoreControlURL string `json:"corecontrol_url" yaml:"corecontrol_url" jsonschema:"format=uri,description=CoreControl server URL"`
// AppID is this application's identifier in the federation.
AppID string `json:"app_id" yaml:"app_id" jsonschema:"description=Application ID in the federation"`
// ClientID is the OAuth client ID for CoreControl.
ClientID string `json:"client_id" yaml:"client_id" jsonschema:"description=OAuth client ID for CoreControl"`
// ClientSecret is the OAuth client secret for CoreControl.
// Supports environment variable expansion: ${CORECONTROL_SECRET}
ClientSecret string `json:"client_secret" yaml:"client_secret" jsonschema:"description=OAuth client secret (supports env var expansion)"`
}
FederationConfig configures CoreControl integration.
type FederationEndpoints ¶
type FederationEndpoints struct {
// contains filtered or unexported fields
}
FederationEndpoints provides CoreForge federation contract endpoints.
func NewFederationEndpoints ¶
func NewFederationEndpoints(server *Server, syncHandler IdentitySyncHandler) *FederationEndpoints
NewFederationEndpoints creates federation endpoints for the server.
func (*FederationEndpoints) RegisterRoutes ¶
func (f *FederationEndpoints) RegisterRoutes()
RegisterRoutes registers the federation endpoints on the server's router.
type FederationHealthResponse ¶
type FederationHealthResponse struct {
Status string `json:"status"`
AppID string `json:"app_id"`
Version string `json:"version"`
Capabilities []string `json:"capabilities"`
Details map[string]string `json:"details,omitempty"`
}
FederationHealthResponse is returned by the health endpoint.
type GlobalIdentity ¶
type GlobalIdentity struct {
ID uuid.UUID `json:"id"`
FederationID uuid.UUID `json:"federation_id"`
Email string `json:"email"`
DisplayName string `json:"display_name"`
Status string `json:"status"`
Attributes map[string]interface{} `json:"attributes,omitempty"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
GlobalIdentity represents a user's identity from CoreControl.
type Identity ¶ added in v0.3.0
type Identity struct {
// ID is the unique identifier.
ID uuid.UUID `json:"id"`
// State is the identity state (active, inactive, etc.).
State IdentityState `json:"state"`
// Traits holds identity attributes (email, name, etc.).
// In Kratos, this maps to the identity traits.
Traits IdentityTraits `json:"traits"`
// Metadata holds administrative metadata.
Metadata map[string]any `json:"metadata,omitempty"`
// Credentials holds credential information (password hash, etc.).
// Note: Sensitive data should not be returned in queries.
Credentials []IdentityCredential `json:"credentials,omitempty"`
// CreatedAt is when the identity was created.
CreatedAt time.Time `json:"created_at"`
// UpdatedAt is when the identity was last updated.
UpdatedAt time.Time `json:"updated_at"`
}
Identity represents a user identity. This is a clean abstraction that can map to Kratos identity schema.
type IdentityCredential ¶ added in v0.3.0
type IdentityCredential struct {
Type CredentialType `json:"type"`
Identifiers []string `json:"identifiers,omitempty"`
}
IdentityCredential represents a credential type.
type IdentityFilter ¶ added in v0.3.0
type IdentityFilter struct {
Email string
State IdentityState
PageSize int
Page int
}
IdentityFilter for listing identities.
type IdentityMapping ¶
type IdentityMapping struct {
ID uuid.UUID `json:"id"`
GlobalIdentityID uuid.UUID `json:"global_identity_id"`
AppID string `json:"app_id"`
LocalPrincipalID uuid.UUID `json:"local_principal_id"`
MappedAt time.Time `json:"mapped_at"`
SyncStatus string `json:"sync_status"`
}
IdentityMapping maps a global identity to a local principal.
type IdentityProvider ¶ added in v0.3.0
type IdentityProvider interface {
// CreateIdentity creates a new identity.
CreateIdentity(ctx context.Context, identity *Identity) error
// GetIdentity retrieves an identity by ID.
GetIdentity(ctx context.Context, id uuid.UUID) (*Identity, error)
// GetIdentityByEmail retrieves an identity by email address.
GetIdentityByEmail(ctx context.Context, email string) (*Identity, error)
// UpdateIdentity updates an existing identity.
UpdateIdentity(ctx context.Context, identity *Identity) error
// DeleteIdentity deletes an identity.
DeleteIdentity(ctx context.Context, id uuid.UUID) error
// ListIdentities lists identities with optional filtering.
ListIdentities(ctx context.Context, filter *IdentityFilter) ([]*Identity, error)
}
IdentityProvider manages user identities (CRUD operations). In Ory Kratos, this maps to the identity management API.
type IdentityState ¶ added in v0.3.0
type IdentityState string
IdentityState represents the state of an identity.
const ( IdentityStateActive IdentityState = "active" IdentityStateInactive IdentityState = "inactive" )
type IdentitySyncHandler ¶
type IdentitySyncHandler interface {
// SyncIdentity is called when CoreControl wants to sync an identity to this app.
// The handler should create/update/delete the local principal as appropriate.
SyncIdentity(ctx context.Context, req *IdentitySyncRequest) (*IdentitySyncResponse, error)
}
IdentitySyncHandler handles identity sync requests from CoreControl. Apps must implement this interface to handle identity provisioning.
type IdentitySyncRequest ¶
type IdentitySyncRequest struct {
Action string `json:"action"` // create, update, delete
Identity *GlobalIdentity `json:"identity"`
}
IdentitySyncRequest is received from CoreControl to sync an identity.
type IdentitySyncResponse ¶
type IdentitySyncResponse struct {
LocalPrincipalID uuid.UUID `json:"local_principal_id"`
Status string `json:"status"` // synced, pending, failed
Error string `json:"error,omitempty"`
}
IdentitySyncResponse is returned to CoreControl after syncing.
type IdentityTraits ¶ added in v0.3.0
type IdentityTraits struct {
Email string `json:"email"`
EmailVerified bool `json:"email_verified,omitempty"`
Name string `json:"name,omitempty"`
GivenName string `json:"given_name,omitempty"`
FamilyName string `json:"family_name,omitempty"`
Picture string `json:"picture,omitempty"`
Locale string `json:"locale,omitempty"`
}
IdentityTraits holds identity attributes.
type IntrospectInput ¶
type IntrospectInput struct {
Token string `form:"token" required:"true" doc:"The token to introspect"`
TokenTypeHint string `form:"token_type_hint" enum:"access_token,refresh_token" doc:"Hint about the token type"`
// Client authentication
Authorization string `header:"Authorization" doc:"Basic authentication header (client_id:client_secret)"`
}
IntrospectInput represents the token introspection request.
type IntrospectOutput ¶
type IntrospectOutput struct {
Body IntrospectResponse
}
IntrospectOutput wraps the introspection response.
type IntrospectResponse ¶
type IntrospectResponse struct {
Active bool `json:"active" doc:"Whether the token is active"`
Scope string `json:"scope,omitempty" doc:"Scopes associated with the token"`
ClientID string `json:"client_id,omitempty" doc:"Client that requested the token"`
Username string `json:"username,omitempty" doc:"Resource owner username"`
TokenType string `json:"token_type,omitempty" doc:"Token type"`
Exp int64 `json:"exp,omitempty" doc:"Token expiration timestamp"`
Iat int64 `json:"iat,omitempty" doc:"Token issue timestamp"`
Nbf int64 `json:"nbf,omitempty" doc:"Token not-before timestamp"`
Sub string `json:"sub,omitempty" doc:"Subject (user ID)"`
Aud string `json:"aud,omitempty" doc:"Intended audience"`
Iss string `json:"iss,omitempty" doc:"Token issuer"`
Jti string `json:"jti,omitempty" doc:"JWT ID"`
}
IntrospectResponse represents the token introspection response.
type JWKSOutput ¶
type JWKSOutput struct {
Body jose.JSONWebKeySet
}
JWKSOutput wraps the JWKS response.
type KeyConfig ¶
type KeyConfig struct {
// Algorithm is the signing algorithm: "RS256" (default), "ES256"
Algorithm string `` /* 136-byte string literal not displayed */
// RotationDays is how often to rotate keys (0 = never)
RotationDays int `` /* 138-byte string literal not displayed */
// PrivateKey is an optional pre-configured RSA private key.
// If nil, a key will be generated automatically.
// This field is not serialized - for programmatic use only.
PrivateKey *rsa.PrivateKey `json:"-" yaml:"-" jsonschema:"-"`
}
KeyConfig configures signing key management.
type MemoryStorage ¶
type MemoryStorage struct {
// contains filtered or unexported fields
}
MemoryStorage implements the Storage interface using in-memory maps. This is suitable for embedded mode and testing.
func NewMemoryStorage ¶
func NewMemoryStorage() *MemoryStorage
NewMemoryStorage creates a new in-memory storage.
func (*MemoryStorage) CleanupExpired ¶
func (s *MemoryStorage) CleanupExpired(ctx context.Context) error
CleanupExpired removes all expired entries. Should be called periodically (e.g., every minute).
func (*MemoryStorage) ClientAssertionJWTValid ¶
func (s *MemoryStorage) ClientAssertionJWTValid(ctx context.Context, jti string) error
ClientAssertionJWTValid returns an error if the JTI is known or the DB check failed.
func (*MemoryStorage) CreateAccessTokenSession ¶
func (s *MemoryStorage) CreateAccessTokenSession(ctx context.Context, signature string, request fosite.Requester) error
CreateAccessTokenSession stores an access token session.
func (*MemoryStorage) CreateAuthorizeCodeSession ¶
func (s *MemoryStorage) CreateAuthorizeCodeSession(ctx context.Context, code string, request fosite.Requester) error
CreateAuthorizeCodeSession stores an authorization code session.
func (*MemoryStorage) CreateClient ¶
func (s *MemoryStorage) CreateClient(ctx context.Context, client *Client) error
CreateClient creates a new OAuth client.
func (*MemoryStorage) CreatePKCERequestSession ¶
func (s *MemoryStorage) CreatePKCERequestSession(ctx context.Context, signature string, requester fosite.Requester) error
CreatePKCERequestSession creates a PKCE session.
func (*MemoryStorage) CreateRefreshTokenSession ¶
func (s *MemoryStorage) CreateRefreshTokenSession(ctx context.Context, signature string, accessSignature string, request fosite.Requester) error
CreateRefreshTokenSession stores a refresh token session.
func (*MemoryStorage) CreateUser ¶
func (s *MemoryStorage) CreateUser(ctx context.Context, user *User) error
CreateUser creates a new user.
func (*MemoryStorage) DeleteAccessTokenSession ¶
func (s *MemoryStorage) DeleteAccessTokenSession(ctx context.Context, signature string) error
DeleteAccessTokenSession removes an access token session.
func (*MemoryStorage) DeleteClient ¶
func (s *MemoryStorage) DeleteClient(ctx context.Context, id string) error
DeleteClient deletes a client.
func (*MemoryStorage) DeletePKCERequestSession ¶
func (s *MemoryStorage) DeletePKCERequestSession(ctx context.Context, signature string) error
DeletePKCERequestSession deletes a PKCE session.
func (*MemoryStorage) DeleteRefreshTokenSession ¶
func (s *MemoryStorage) DeleteRefreshTokenSession(ctx context.Context, signature string) error
DeleteRefreshTokenSession removes a refresh token session.
func (*MemoryStorage) DeleteUser ¶
DeleteUser deletes a user.
func (*MemoryStorage) GetAccessTokenSession ¶
func (s *MemoryStorage) GetAccessTokenSession(ctx context.Context, signature string, session fosite.Session) (fosite.Requester, error)
GetAccessTokenSession retrieves an access token session.
func (*MemoryStorage) GetAuthorizeCodeSession ¶
func (s *MemoryStorage) GetAuthorizeCodeSession(ctx context.Context, code string, session fosite.Session) (fosite.Requester, error)
GetAuthorizeCodeSession retrieves an authorization code session.
func (*MemoryStorage) GetClient ¶
GetClient retrieves a client by ID (implements fosite.ClientManager).
func (*MemoryStorage) GetClientByID ¶
GetClientByID retrieves a client by ID.
func (*MemoryStorage) GetPKCERequestSession ¶
func (s *MemoryStorage) GetPKCERequestSession(ctx context.Context, signature string, session fosite.Session) (fosite.Requester, error)
GetPKCERequestSession retrieves a PKCE session.
func (*MemoryStorage) GetRefreshTokenSession ¶
func (s *MemoryStorage) GetRefreshTokenSession(ctx context.Context, signature string, session fosite.Session) (fosite.Requester, error)
GetRefreshTokenSession retrieves a refresh token session.
func (*MemoryStorage) GetUserByEmail ¶
GetUserByEmail retrieves a user by email.
func (*MemoryStorage) GetUserByFederationID ¶
func (s *MemoryStorage) GetUserByFederationID(ctx context.Context, federationID uuid.UUID) (*User, error)
GetUserByFederationID retrieves a user by their federation ID.
func (*MemoryStorage) GetUserByID ¶
GetUserByID retrieves a user by ID.
func (*MemoryStorage) InvalidateAuthorizeCodeSession ¶
func (s *MemoryStorage) InvalidateAuthorizeCodeSession(ctx context.Context, code string) error
InvalidateAuthorizeCodeSession marks an authorization code as used.
func (*MemoryStorage) ListClients ¶
func (s *MemoryStorage) ListClients(ctx context.Context) ([]*Client, error)
ListClients returns all clients.
func (*MemoryStorage) RevokeAccessToken ¶
func (s *MemoryStorage) RevokeAccessToken(ctx context.Context, requestID string) error
RevokeAccessToken revokes all access tokens for a request ID.
func (*MemoryStorage) RevokeRefreshToken ¶
func (s *MemoryStorage) RevokeRefreshToken(ctx context.Context, requestID string) error
RevokeRefreshToken revokes all refresh tokens for a request ID.
func (*MemoryStorage) RotateRefreshToken ¶
func (s *MemoryStorage) RotateRefreshToken(ctx context.Context, requestID string, refreshTokenSignature string) error
RotateRefreshToken rotates a refresh token.
func (*MemoryStorage) SetClientAssertionJWT ¶
SetClientAssertionJWT marks a JTI as used.
func (*MemoryStorage) UpdateClient ¶
func (s *MemoryStorage) UpdateClient(ctx context.Context, client *Client) error
UpdateClient updates an existing client.
func (*MemoryStorage) UpdateUser ¶
func (s *MemoryStorage) UpdateUser(ctx context.Context, user *User) error
UpdateUser updates an existing user.
type OAuthAuthorizeRequest ¶ added in v0.3.0
type OAuthAuthorizeRequest struct {
ClientID string `json:"client_id"`
RedirectURI string `json:"redirect_uri"`
ResponseType string `json:"response_type"`
Scope string `json:"scope"`
State string `json:"state"`
Nonce string `json:"nonce,omitempty"`
CodeChallenge string `json:"code_challenge,omitempty"`
CodeChallengeMethod string `json:"code_challenge_method,omitempty"`
Prompt string `json:"prompt,omitempty"`
MaxAge int `json:"max_age,omitempty"`
UILocales string `json:"ui_locales,omitempty"`
ACRValues string `json:"acr_values,omitempty"`
}
OAuthAuthorizeRequest represents an authorization request.
type OAuthAuthorizeResponse ¶ added in v0.3.0
type OAuthAuthorizeResponse struct {
// Code is the authorization code (for code flow).
Code string `json:"code,omitempty"`
// RedirectTo is the URL to redirect the user to.
RedirectTo string `json:"redirect_to"`
// Error information if authorization failed.
Error string `json:"error,omitempty"`
ErrorDescription string `json:"error_description,omitempty"`
}
OAuthAuthorizeResponse is the authorization response.
type OAuthClient ¶ added in v0.3.0
type OAuthClient struct {
// ClientID is the unique client identifier.
ClientID string `json:"client_id"`
// ClientSecret is the client secret (hashed in storage).
ClientSecret string `json:"client_secret,omitempty"`
// ClientName is the human-readable client name.
ClientName string `json:"client_name,omitempty"`
// RedirectURIs are the allowed redirect URIs.
RedirectURIs []string `json:"redirect_uris"`
// GrantTypes are the allowed grant types.
GrantTypes []string `json:"grant_types"`
// ResponseTypes are the allowed response types.
ResponseTypes []string `json:"response_types"`
// Scope is the allowed scope.
Scope string `json:"scope"`
// Audience are the allowed audiences.
Audience []string `json:"audience,omitempty"`
// TokenEndpointAuthMethod is the authentication method for the token endpoint.
TokenEndpointAuthMethod string `json:"token_endpoint_auth_method,omitempty"`
// Public indicates if this is a public client (no secret).
Public bool `json:"public"`
// Metadata holds custom client metadata.
Metadata map[string]any `json:"metadata,omitempty"`
// CreatedAt is when the client was created.
CreatedAt time.Time `json:"created_at,omitzero"`
// UpdatedAt is when the client was last updated.
UpdatedAt time.Time `json:"updated_at,omitzero"`
}
OAuthClient represents an OAuth 2.0 client.
type OAuthClientStore ¶ added in v0.3.0
type OAuthClientStore interface {
// CreateClient creates a new OAuth client.
CreateClient(ctx context.Context, client *OAuthClient) error
// GetClient retrieves a client by ID.
GetClient(ctx context.Context, clientID string) (*OAuthClient, error)
// UpdateClient updates an existing client.
UpdateClient(ctx context.Context, client *OAuthClient) error
// DeleteClient deletes a client.
DeleteClient(ctx context.Context, clientID string) error
// ListClients lists all clients.
ListClients(ctx context.Context) ([]*OAuthClient, error)
}
OAuthClientStore manages OAuth 2.0 clients. In Ory Hydra, this maps to the admin client API.
type OAuthConsentAccept ¶ added in v0.3.0
type OAuthConsentAccept struct {
GrantScopes []string `json:"grant_scopes"`
Remember bool `json:"remember"`
RememberFor int `json:"remember_for,omitempty"`
Session *ConsentSession `json:"session,omitempty"`
}
OAuthConsentAccept accepts a consent request.
type OAuthConsentReject ¶ added in v0.3.0
type OAuthConsentReject struct {
Error string `json:"error"`
ErrorDescription string `json:"error_description,omitempty"`
}
OAuthConsentReject rejects a consent request.
type OAuthConsentRequest ¶ added in v0.3.0
type OAuthConsentRequest struct {
Challenge string `json:"challenge"`
ClientID string `json:"client_id"`
RequestedScopes []string `json:"requested_scopes"`
Subject string `json:"subject"`
Skip bool `json:"skip"`
}
OAuthConsentRequest is a pending consent request.
type OAuthConsentResponse ¶ added in v0.3.0
type OAuthConsentResponse struct {
RedirectTo string `json:"redirect_to"`
}
OAuthConsentResponse is the consent response.
type OAuthError ¶
type OAuthError struct {
Error string `json:"error" doc:"Error code"`
ErrorDescription string `json:"error_description,omitempty" doc:"Human-readable error description"`
ErrorURI string `json:"error_uri,omitempty" doc:"URI with more information about the error"`
}
OAuthError represents an OAuth 2.0 error response.
type OAuthIntrospection ¶ added in v0.3.0
type OAuthIntrospection struct {
Active bool `json:"active"`
Scope string `json:"scope,omitempty"`
ClientID string `json:"client_id,omitempty"`
Username string `json:"username,omitempty"`
TokenType string `json:"token_type,omitempty"`
Exp int64 `json:"exp,omitempty"`
Iat int64 `json:"iat,omitempty"`
Nbf int64 `json:"nbf,omitempty"`
Sub string `json:"sub,omitempty"`
Aud []string `json:"aud,omitempty"`
Iss string `json:"iss,omitempty"`
Jti string `json:"jti,omitempty"`
}
OAuthIntrospection is the token introspection response.
type OAuthLoginAccept ¶ added in v0.3.0
type OAuthLoginAccept struct {
Subject string `json:"subject"`
Remember bool `json:"remember"`
RememberFor int `json:"remember_for,omitempty"`
ACR string `json:"acr,omitempty"`
Context map[string]any `json:"context,omitempty"`
}
OAuthLoginAccept accepts a login request.
type OAuthLoginReject ¶ added in v0.3.0
type OAuthLoginReject struct {
Error string `json:"error"`
ErrorDescription string `json:"error_description,omitempty"`
}
OAuthLoginReject rejects a login request.
type OAuthLoginRequest ¶ added in v0.3.0
type OAuthLoginRequest struct {
Challenge string `json:"challenge"`
ClientID string `json:"client_id"`
RequestedScopes []string `json:"requested_scopes"`
Skip bool `json:"skip"`
Subject string `json:"subject,omitempty"`
}
OAuthLoginRequest is a pending login request.
type OAuthLoginResponse ¶ added in v0.3.0
type OAuthLoginResponse struct {
RedirectTo string `json:"redirect_to"`
}
OAuthLoginResponse is the login response.
type OAuthProvider ¶ added in v0.3.0
type OAuthProvider interface {
// Authorize handles the authorization request.
// Returns an authorization code or error.
Authorize(ctx context.Context, req *OAuthAuthorizeRequest) (*OAuthAuthorizeResponse, error)
// Token handles token requests (authorization code, refresh, client credentials).
Token(ctx context.Context, req *OAuthTokenRequest) (*OAuthTokenResponse, error)
// Introspect validates and returns information about a token.
Introspect(ctx context.Context, token string, tokenTypeHint string) (*OAuthIntrospection, error)
// Revoke revokes an access or refresh token.
Revoke(ctx context.Context, token string, tokenTypeHint string) error
// UserInfo returns claims about the authenticated user (OIDC).
UserInfo(ctx context.Context, accessToken string) (*OAuthUserInfo, error)
// GetConsentRequest retrieves a pending consent request.
GetConsentRequest(ctx context.Context, challenge string) (*OAuthConsentRequest, error)
// AcceptConsent accepts a consent request.
AcceptConsent(ctx context.Context, challenge string, accept *OAuthConsentAccept) (*OAuthConsentResponse, error)
// RejectConsent rejects a consent request.
RejectConsent(ctx context.Context, challenge string, reject *OAuthConsentReject) (*OAuthConsentResponse, error)
// GetLoginRequest retrieves a pending login request.
GetLoginRequest(ctx context.Context, challenge string) (*OAuthLoginRequest, error)
// AcceptLogin accepts a login request.
AcceptLogin(ctx context.Context, challenge string, accept *OAuthLoginAccept) (*OAuthLoginResponse, error)
// RejectLogin rejects a login request.
RejectLogin(ctx context.Context, challenge string, reject *OAuthLoginReject) (*OAuthLoginResponse, error)
}
OAuthProvider handles OAuth 2.0 / OpenID Connect operations. In Ory Hydra, this maps to the public and admin APIs.
type OAuthTokenRequest ¶ added in v0.3.0
type OAuthTokenRequest struct {
GrantType string `json:"grant_type"`
Code string `json:"code,omitempty"`
RedirectURI string `json:"redirect_uri,omitempty"`
RefreshToken string `json:"refresh_token,omitempty"`
ClientID string `json:"client_id,omitempty"`
ClientSecret string `json:"client_secret,omitempty"`
CodeVerifier string `json:"code_verifier,omitempty"`
Scope string `json:"scope,omitempty"`
}
OAuthTokenRequest represents a token request.
type OAuthTokenResponse ¶ added in v0.3.0
type OAuthTokenResponse struct {
AccessToken string `json:"access_token"`
TokenType string `json:"token_type"`
ExpiresIn int64 `json:"expires_in"`
RefreshToken string `json:"refresh_token,omitempty"`
IDToken string `json:"id_token,omitempty"`
Scope string `json:"scope,omitempty"`
}
OAuthTokenResponse is the token response.
type OAuthUserInfo ¶ added in v0.3.0
type OAuthUserInfo struct {
Sub string `json:"sub"`
Name string `json:"name,omitempty"`
GivenName string `json:"given_name,omitempty"`
FamilyName string `json:"family_name,omitempty"`
Email string `json:"email,omitempty"`
EmailVerified bool `json:"email_verified,omitempty"`
Picture string `json:"picture,omitempty"`
Locale string `json:"locale,omitempty"`
Zoneinfo string `json:"zoneinfo,omitempty"`
}
OAuthUserInfo is the OIDC userinfo response.
type OpenIDConfigInput ¶
type OpenIDConfigInput struct{}
OpenIDConfigInput is the input for the discovery endpoint (no params).
type OpenIDConfigOutput ¶
type OpenIDConfigOutput struct {
Body OpenIDConfiguration
}
OpenIDConfigOutput wraps the OpenID configuration response.
type OpenIDConfiguration ¶
type OpenIDConfiguration struct {
Issuer string `json:"issuer"`
AuthorizationEndpoint string `json:"authorization_endpoint"`
TokenEndpoint string `json:"token_endpoint"`
UserinfoEndpoint string `json:"userinfo_endpoint,omitempty"`
JwksURI string `json:"jwks_uri"`
RegistrationEndpoint string `json:"registration_endpoint,omitempty"`
IntrospectionEndpoint string `json:"introspection_endpoint,omitempty"`
RevocationEndpoint string `json:"revocation_endpoint,omitempty"`
ScopesSupported []string `json:"scopes_supported,omitempty"`
ResponseTypesSupported []string `json:"response_types_supported"`
ResponseModesSupported []string `json:"response_modes_supported,omitempty"`
GrantTypesSupported []string `json:"grant_types_supported,omitempty"`
SubjectTypesSupported []string `json:"subject_types_supported"`
IDTokenSigningAlgValuesSupported []string `json:"id_token_signing_alg_values_supported"`
TokenEndpointAuthMethodsSupported []string `json:"token_endpoint_auth_methods_supported,omitempty"`
ClaimsSupported []string `json:"claims_supported,omitempty"`
CodeChallengeMethodsSupported []string `json:"code_challenge_methods_supported,omitempty"`
}
OpenIDConfiguration represents the OpenID Provider configuration.
type Option ¶
type Option func(*Server)
Option configures a Server.
func WithLogger ¶
WithLogger sets the logger for the server.
func WithObservability ¶ added in v0.3.0
func WithObservability(obs *observability.Observability) Option
WithObservability sets the observability provider for metrics and tracing.
func WithSessionProvider ¶
func WithSessionProvider(provider SessionProvider) Option
WithSessionProvider sets a custom session provider for authentication.
func WithStorage ¶
WithStorage sets a custom storage implementation.
type Providers ¶ added in v0.3.0
type Providers struct {
Identity IdentityProvider
Authentication AuthenticationProvider
OAuth OAuthProvider
OAuthClients OAuthClientStore
}
Providers holds all provider implementations for CoreAuth. This provides a unified way to access identity, authentication, and OAuth services.
func NewProviders ¶ added in v0.3.0
func NewProviders(server *Server, opts ...ProvidersOption) *Providers
NewProviders creates all embedded providers from a CoreAuth Server. This is the simplest way to get all provider implementations.
Example:
server, _ := coreauth.NewEmbedded(cfg) providers := coreauth.NewProviders(server) // Use providers identity, _ := providers.Identity.GetIdentity(ctx, userID) session, _ := providers.Authentication.ValidateSession(ctx, token) userInfo, _ := providers.OAuth.UserInfo(ctx, accessToken)
func NewProvidersFromStorage ¶ added in v0.3.0
func NewProvidersFromStorage(storage Storage, opts ...ProvidersOption) *Providers
NewProvidersFromStorage creates providers directly from storage. Use this when you don't need the full OAuth server functionality.
Example:
storage := coreauth.NewMemoryStorage() providers := coreauth.NewProvidersFromStorage(storage)
type ProvidersOption ¶ added in v0.3.0
type ProvidersOption func(*providersConfig)
ProvidersOption configures the embedded providers.
func WithProviderPasswordVerifier ¶ added in v0.3.0
func WithProviderPasswordVerifier(verifier func(ctx context.Context, identityID uuid.UUID, password string) (bool, error)) ProvidersOption
WithProviderPasswordVerifier sets the password verification function.
func WithProviderSessionDuration ¶ added in v0.3.0
func WithProviderSessionDuration(d time.Duration) ProvidersOption
WithProviderSessionDuration sets the session duration for the auth provider.
type RevokeInput ¶
type RevokeInput struct {
Token string `form:"token" required:"true" doc:"The token to revoke"`
TokenTypeHint string `form:"token_type_hint" enum:"access_token,refresh_token" doc:"Hint about the token type"`
// Client authentication
Authorization string `header:"Authorization" doc:"Basic authentication header (client_id:client_secret)"`
}
RevokeInput represents the token revocation request.
type RevokeOutput ¶
type RevokeOutput struct{}
RevokeOutput represents the token revocation response (empty on success).
type SSOSession ¶
type SSOSession struct {
ID uuid.UUID `json:"id"`
GlobalIdentityID uuid.UUID `json:"global_identity_id"`
AuthTime time.Time `json:"auth_time"`
ExpiresAt time.Time `json:"expires_at"`
AppsAccessed []string `json:"apps_accessed"`
}
SSOSession represents an active SSO session from CoreControl.
type SSOTokenResponse ¶
type SSOTokenResponse struct {
AccessToken string `json:"access_token"`
TokenType string `json:"token_type"`
ExpiresIn int `json:"expires_in"`
RefreshToken string `json:"refresh_token,omitempty"`
IDToken string `json:"id_token,omitempty"`
Scope string `json:"scope,omitempty"`
}
SSOTokenResponse contains tokens from CoreControl SSO.
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server is the CoreAuth OAuth 2.0 / OpenID Connect server.
func NewEmbedded ¶
NewEmbedded creates a CoreAuth server for embedding in applications. This is the simplest way to add OAuth to a CoreForge application.
Example:
auth, err := coreauth.NewEmbedded(coreauth.Config{
Issuer: "https://myapp.example.com",
})
router.Mount("/oauth", auth.Router())
func (*Server) Middleware ¶
Middleware returns HTTP middleware that validates access tokens. Use this to protect your API endpoints.
Example:
router.With(auth.Middleware()).Get("/api/me", meHandler)
func (*Server) OAuth2Provider ¶
func (s *Server) OAuth2Provider() fosite.OAuth2Provider
OAuth2Provider returns the underlying Fosite provider.
func (*Server) OIDCSession ¶
func (s *Server) OIDCSession(subject string, claims map[string]interface{}) *openid.DefaultSession
OIDCSession creates an OpenID Connect session for Fosite.
func (*Server) Observability ¶ added in v0.3.0
func (s *Server) Observability() *observability.Observability
Observability returns the observability provider, or nil if not configured.
func (*Server) RegisterClient ¶
RegisterClient registers a new OAuth client.
func (*Server) RequireScopes ¶
RequireScopes returns middleware that requires specific scopes.
func (*Server) ServeHTTP ¶
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP implements http.Handler.
func (*Server) Session ¶
func (s *Server) Session(subject string) *openid.DefaultSession
Session creates a new OAuth session for a user.
func (*Server) SessionProvider ¶
func (s *Server) SessionProvider() SessionProvider
SessionProvider returns the session provider.
type SessionProvider ¶
type SessionProvider interface {
// GetAuthenticatedUser returns the authenticated user ID from the request.
// Returns empty string if the user is not authenticated.
GetAuthenticatedUser(r *http.Request) string
// RedirectToLogin returns the URL to redirect unauthenticated users to.
// The returnURL is the original authorization request URL to return to after login.
RedirectToLogin(returnURL string) string
// HasConsent checks if the user has already granted consent for the client and scopes.
// Returns true if consent exists and is still valid.
HasConsent(ctx context.Context, userID, clientID string, scopes []string) bool
// RedirectToConsent returns the URL to redirect users for consent approval.
// The returnURL is the original authorization request URL to return to after consent.
RedirectToConsent(returnURL string) string
// SaveConsent records that the user has granted consent for the client and scopes.
SaveConsent(ctx context.Context, userID, clientID string, scopes []string) error
// GetUserClaims returns additional claims to include in the ID token.
// Common claims: name, email, picture, etc.
GetUserClaims(ctx context.Context, userID string, scopes []string) map[string]interface{}
}
SessionProvider handles user authentication and consent for the authorization flow. Implement this interface to integrate with your authentication system.
type Storage ¶
type Storage interface {
// Fosite storage interfaces
fosite.ClientManager
// Authorization code operations
CreateAuthorizeCodeSession(ctx context.Context, code string, request fosite.Requester) error
GetAuthorizeCodeSession(ctx context.Context, code string, session fosite.Session) (fosite.Requester, error)
InvalidateAuthorizeCodeSession(ctx context.Context, code string) error
// Access token operations
CreateAccessTokenSession(ctx context.Context, signature string, request fosite.Requester) error
GetAccessTokenSession(ctx context.Context, signature string, session fosite.Session) (fosite.Requester, error)
DeleteAccessTokenSession(ctx context.Context, signature string) error
// Refresh token operations
CreateRefreshTokenSession(ctx context.Context, signature string, accessSignature string, request fosite.Requester) error
GetRefreshTokenSession(ctx context.Context, signature string, session fosite.Session) (fosite.Requester, error)
DeleteRefreshTokenSession(ctx context.Context, signature string) error
RevokeRefreshToken(ctx context.Context, requestID string) error
RevokeAccessToken(ctx context.Context, requestID string) error
RotateRefreshToken(ctx context.Context, requestID string, refreshTokenSignature string) error
// PKCE operations
CreatePKCERequestSession(ctx context.Context, signature string, requester fosite.Requester) error
GetPKCERequestSession(ctx context.Context, signature string, session fosite.Session) (fosite.Requester, error)
DeletePKCERequestSession(ctx context.Context, signature string) error
// Client assertion JWT tracking
ClientAssertionJWTValid(ctx context.Context, jti string) error
SetClientAssertionJWT(ctx context.Context, jti string, exp time.Time) error
// Client management operations (extended)
CreateClient(ctx context.Context, client *Client) error
GetClientByID(ctx context.Context, id string) (*Client, error)
UpdateClient(ctx context.Context, client *Client) error
DeleteClient(ctx context.Context, id string) error
ListClients(ctx context.Context) ([]*Client, error)
// User management for federation (optional - may return ErrNotImplemented)
CreateUser(ctx context.Context, user *User) error
GetUserByID(ctx context.Context, id uuid.UUID) (*User, error)
GetUserByEmail(ctx context.Context, email string) (*User, error)
GetUserByFederationID(ctx context.Context, federationID uuid.UUID) (*User, error)
UpdateUser(ctx context.Context, user *User) error
DeleteUser(ctx context.Context, id uuid.UUID) error
}
Storage defines the persistence interface for CoreAuth. It extends Fosite's storage requirements with client management.
type StoredRequest ¶
type StoredRequest struct {
ID string
ClientID string
Scopes []string
GrantedScopes []string
Form map[string][]string
Session *StoredSession
RequestedAt time.Time
}
StoredRequest holds the data needed to reconstruct a fosite.Requester.
type StoredSession ¶
type StoredSession struct {
// Subject is the user ID.
Subject string `json:"sub"`
// Username is the human-readable username.
Username string `json:"username,omitempty"`
// Email is the user's email.
Email string `json:"email,omitempty"`
// Claims are additional claims.
Claims map[string]any `json:"claims,omitempty"`
// ExpiresAt maps token types to expiration times (unix timestamps).
ExpiresAt map[string]int64 `json:"expires_at"`
// RequestedAt is when the session was created (unix timestamp).
RequestedAt int64 `json:"requested_at"`
}
StoredSession holds serializable session information.
type TokenConfig ¶
type TokenConfig struct {
// AccessTokenLifetime is how long access tokens are valid.
// Default: 15 minutes
AccessTokenLifetime Duration `` /* 151-byte string literal not displayed */
// RefreshTokenLifetime is how long refresh tokens are valid.
// Default: 7 days
RefreshTokenLifetime Duration `` /* 158-byte string literal not displayed */
// IDTokenLifetime is how long ID tokens are valid.
// Default: 1 hour
IDTokenLifetime Duration `` /* 133-byte string literal not displayed */
// AuthCodeLifetime is how long authorization codes are valid.
// Default: 10 minutes
AuthCodeLifetime Duration `` /* 147-byte string literal not displayed */
}
TokenConfig configures token lifetimes. Durations are specified as strings: "15m", "1h", "7d", etc.
type TokenData ¶
type TokenData struct {
// AccessTokenSignature is the hashed access token.
AccessTokenSignature string
// RefreshTokenSignature is the hashed refresh token.
RefreshTokenSignature string
// ClientID is the client that owns the token.
ClientID string
// Subject is the user ID.
Subject string
// Scopes are the granted scopes.
Scopes []string
// Session holds the session data.
Session *StoredSession
// AccessExpiresAt is when the access token expires.
AccessExpiresAt int64
// RefreshExpiresAt is when the refresh token expires.
RefreshExpiresAt int64
// Revoked indicates the token has been revoked.
Revoked bool
// RequestID is used for token family tracking.
RequestID string
}
TokenData holds access/refresh token storage data.
type TokenInput ¶
type TokenInput struct {
GrantType string `form:"grant_type" required:"true" enum:"authorization_code,refresh_token,client_credentials" doc:"OAuth 2.0 grant type"`
Code string `form:"code" doc:"Authorization code (for authorization_code grant)"`
RedirectURI string `form:"redirect_uri" doc:"Redirect URI (must match authorization request)"`
ClientID string `form:"client_id" doc:"Client identifier (if not using Basic auth)"`
ClientSecret string `form:"client_secret" doc:"Client secret (if not using Basic auth)"`
RefreshToken string `form:"refresh_token" doc:"Refresh token (for refresh_token grant)"`
Scope string `form:"scope" doc:"Requested scopes (for refresh_token or client_credentials)"`
CodeVerifier string `form:"code_verifier" doc:"PKCE code verifier"`
// Basic auth credentials (alternative to form-based client auth)
Authorization string `header:"Authorization" doc:"Basic authentication header (client_id:client_secret)"`
}
TokenInput represents the OAuth 2.0 token request parameters. Field names follow OAuth 2.0 specification (RFC 6749).
type TokenOutput ¶
type TokenOutput struct {
Body TokenResponse
}
TokenOutput wraps the token response.
type TokenResponse ¶
type TokenResponse struct {
AccessToken string `json:"access_token" doc:"The access token"`
TokenType string `json:"token_type" doc:"Token type (typically 'Bearer')"`
ExpiresIn int `json:"expires_in,omitempty" doc:"Token lifetime in seconds"`
RefreshToken string `json:"refresh_token,omitempty" doc:"Refresh token for obtaining new access tokens"`
Scope string `json:"scope,omitempty" doc:"Granted scopes (may differ from requested)"`
IDToken string `json:"id_token,omitempty" doc:"OpenID Connect ID token"`
}
TokenResponse represents the OAuth 2.0 token response. Field names follow OAuth 2.0 specification (RFC 6749).
type User ¶
type User struct {
ID uuid.UUID `json:"id"`
Email string `json:"email"`
EmailVerified bool `json:"email_verified,omitempty"`
Name string `json:"name"`
GivenName string `json:"given_name,omitempty"`
FamilyName string `json:"family_name,omitempty"`
Picture string `json:"picture,omitempty"`
Locale string `json:"locale,omitempty"`
Active bool `json:"active"`
Federated bool `json:"federated"`
FederationID *uuid.UUID `json:"federation_id,omitempty"`
Metadata map[string]any `json:"metadata,omitempty"`
CreatedAt time.Time `json:"created_at,omitzero"`
UpdatedAt time.Time `json:"updated_at,omitzero"`
}
User represents a local user identity.