goidc

package
v0.6.1 Latest Latest
Warning

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

Go to latest
Published: Dec 16, 2024 License: MIT Imports: 12 Imported by: 2

Documentation

Overview

Package goidc contains structs and functions which serve as the base to set up and interact with an OpenID Provider.

Index

Constants

View Source
const (
	ClaimTokenID             string = "jti"
	ClaimIssuer              string = "iss"
	ClaimSubject             string = "sub"
	ClaimAudience            string = "aud"
	ClaimClientID            string = "client_id"
	ClaimExpiry              string = "exp"
	ClaimIssuedAt            string = "iat"
	ClaimNotBefore           string = "nbf"
	ClaimScope               string = "scope"
	ClaimNonce               string = "nonce"
	ClaimAuthTime            string = "auth_time"
	ClaimAMR                 string = "amr"
	ClaimACR                 string = "acr"
	ClaimProfile             string = "profile"
	ClaimEmail               string = "email"
	ClaimEmailVerified       string = "email_verified"
	ClaimPhoneNumber         string = "phone_number"
	ClaimPhoneNumberVerified string = "phone_number_verified"
	ClaimAddress             string = "address"
	ClaimName                string = "name"
	ClaimWebsite             string = "website"
	ClaimZoneInfo            string = "zoneinfo"
	ClaimBirthdate           string = "birthdate"
	ClaimGender              string = "gender"
	ClaimPreferredUsername   string = "preferred_username"
	ClaimGivenName           string = "given_name"
	ClaimMiddleName          string = "middle_name"
	ClaimLocale              string = "locale"
	ClaimPicture             string = "picture"
	ClaimUpdatedAt           string = "updated_at"
	ClaimNickname            string = "nickname"
	ClaimFamilyName          string = "family_name"
	ClaimAuthDetails         string = "authorization_details"
	ClaimAccessTokenHash     string = "at_hash"
	ClaimAuthzCodeHash       string = "c_hash"
	ClaimStateHash           string = "s_hash"
	ClaimRefreshTokenHash    string = "urn:openid:params:jwt:claim:rt_hash"
	ClaimAuthReqID           string = "urn:openid:params:jwt:claim:auth_req_id"
)
View Source
const DefaultOpaqueTokenLength int = 50
View Source
const (
	HeaderDPoP string = "DPoP"
)
View Source
const RefreshTokenLength int = 99

RefreshTokenLength has an unusual value so to avoid refresh tokens and opaque access token to be confused. This happens since a refresh token is identified by its length during introspection.

Variables

View Source
var (
	ScopeOpenID        = NewScope("openid")
	ScopeProfile       = NewScope("profile")
	ScopeEmail         = NewScope("email")
	ScopePhone         = NewScope("phone")
	ScopeAddress       = NewScope("address")
	ScopeOfflineAccess = NewScope("offline_access")
)

Functions

func CacheControlMiddleware added in v0.1.1

func CacheControlMiddleware(next http.Handler) http.Handler

Types

type ACR

type ACR string

ACR defines a type for authentication context references.

const (
	ACRNoAssuranceLevel      ACR = "0"
	ACRMaceIncommonIAPSilver ACR = "urn:mace:incommon:iap:silver"
	ACRMaceIncommonIAPBronze ACR = "urn:mace:incommon:iap:bronze"
)

type AMR

type AMR string

AMR defines a type for authentication method references.

const (
	AMRFacialRecognition            AMR = "face"
	AMRFingerPrint                  AMR = "fpt"
	AMRGeolocation                  AMR = "geo"
	AMRHardwareSecuredKey           AMR = "hwk"
	AMRIrisScan                     AMR = "iris"
	AMRMultipleFactor               AMR = "mfa"
	AMROneTimePassoword             AMR = "otp"
	AMRPassword                     AMR = "pwd"
	AMRPersonalIDentificationNumber AMR = "pin"
	AMRRiskBased                    AMR = "rba"
	AMRSMS                          AMR = "sms"
	AMRSoftwareSecuredKey           AMR = "swk"
)

type ApplicationType added in v0.5.0

type ApplicationType string
const (
	ApplicationTypeWeb    ApplicationType = "web"
	ApplicationTypeNative ApplicationType = "native"
)

type AuthnFunc

AuthnFunc executes the user authentication logic.

If it returns StatusSuccess, the flow will end successfully and the client will be granted the accesses the user consented.

If it returns StatusFailure or an error the flow will end with failure and the client will be denied access.

If it return StatusInProgress, the flow will be suspended so an interaction with the user via the user agent can happen, e.g. an HTML page is rendered to to gather user credentials. The flow can be resumed at the callback endpoint with the session callback ID.

type AuthnPolicy

type AuthnPolicy struct {
	ID           string
	SetUp        SetUpAuthnFunc
	Authenticate AuthnFunc
}

AuthnPolicy holds information on how to set up an authentication session and authenticate users.

func NewPolicy

func NewPolicy(
	id string,
	setUpFunc SetUpAuthnFunc,
	authnFunc AuthnFunc,
) AuthnPolicy

NewPolicy creates a policy that will be selected based on setUpFunc and that authenticates users with authnFunc.

type AuthnSession

type AuthnSession struct {
	ID string `json:"id"`
	// Subject is the user identifier.
	//
	// This value must be informed during the authentication flow.
	Subject  string `json:"sub"`
	ClientID string `json:"client_id"`
	// PushedAuthReqID is the id generated during /par used to fetch the session
	// during calls to /authorize.
	//
	// This value will be returned as the request_uri of the /par response.
	PushedAuthReqID string `json:"pushed_auth_req_id,omitempty"`
	// CallbackID is the id used to fetch the authentication session after user
	// interaction during calls to the callback endpoint.
	CallbackID string `json:"callback_id,omitempty"`
	CIBAAuthID string `json:"ciba_auth_req_id,omitempty"`
	AuthCode   string `json:"auth_code,omitempty"`
	// PolicyID is the id of the autentication policy used to authenticate
	// the user.
	PolicyID string `json:"policy_id,omitempty"`

	// GrantedScopes is the scopes the client will be granted access once the
	// access token is generated.
	GrantedScopes string `json:"granted_scopes,omitempty"`
	// GrantedAuthDetails is the authorization details the client will be granted
	// access once the access token is generated.
	GrantedAuthDetails []AuthorizationDetail `json:"granted_authorization_details,omitempty"`
	GrantedResources   Resources             `json:"granted_resources,omitempty"`

	JWKThumbprint string `json:"jwk_thumbprint,omitempty"`
	// ClientCertThumbprint contains the thumbprint of the certificate used by
	// the client to generate the token.
	ClientCertThumbprint string `json:"client_cert_thumbprint,omitempty"`

	// Storage allows storing additional information between interactions.
	Storage                  map[string]any `json:"store,omitempty"`
	AdditionalTokenClaims    map[string]any `json:"additional_token_claims,omitempty"`
	AdditionalIDTokenClaims  map[string]any `json:"additional_id_token_claims,omitempty"`
	AdditionalUserInfoClaims map[string]any `json:"additional_user_info_claims,omitempty"`
	ExpiresAtTimestamp       int            `json:"expires_at"`
	CreatedAtTimestamp       int            `json:"created_at"`
	IDTokenHintClaims        map[string]any `json:"id_token_hint_claims,omitempty"`
	AuthorizationParameters
}

AuthnSession is a short lived session that holds information about authorization requests. It can be interacted with so to implement more sophisticated user authentication flows.

func (*AuthnSession) GrantAuthorizationDetails

func (s *AuthnSession) GrantAuthorizationDetails(authDetails []AuthorizationDetail)

GrantAuthorizationDetails sets the authorization details the client will have permissions to use. This will only have effect if support for authorization details is enabled.

func (*AuthnSession) GrantResources added in v0.0.2

func (s *AuthnSession) GrantResources(resources []string)

func (*AuthnSession) GrantScopes

func (s *AuthnSession) GrantScopes(scopes string)

GrantScopes sets the scopes the client will have access to.

func (*AuthnSession) IsExpired

func (s *AuthnSession) IsExpired() bool

func (*AuthnSession) SetIDTokenClaim

func (s *AuthnSession) SetIDTokenClaim(claim string, value any)

SetIDTokenClaim sets a claim that will be accessible in the ID token.

func (*AuthnSession) SetIDTokenClaimACR

func (s *AuthnSession) SetIDTokenClaimACR(acr ACR)

func (*AuthnSession) SetIDTokenClaimAMR

func (s *AuthnSession) SetIDTokenClaimAMR(amrs ...AMR)

func (*AuthnSession) SetIDTokenClaimAuthTime

func (s *AuthnSession) SetIDTokenClaimAuthTime(authTime int)

func (*AuthnSession) SetTokenClaim

func (s *AuthnSession) SetTokenClaim(claim string, value any)

func (*AuthnSession) SetUserID

func (s *AuthnSession) SetUserID(userID string)

SetUserID sets the subject in the authentication session.

func (*AuthnSession) SetUserInfoClaim

func (s *AuthnSession) SetUserInfoClaim(claim string, value any)

SetUserInfoClaim sets a claim that will be accessible via the user info endpoint.

func (*AuthnSession) SetUserInfoClaimACR

func (s *AuthnSession) SetUserInfoClaimACR(acr ACR)

func (*AuthnSession) SetUserInfoClaimAMR

func (s *AuthnSession) SetUserInfoClaimAMR(amrs ...AMR)

func (*AuthnSession) SetUserInfoClaimAuthTime

func (s *AuthnSession) SetUserInfoClaimAuthTime(authTime int)

func (*AuthnSession) StoreParameter

func (s *AuthnSession) StoreParameter(key string, value any)

func (*AuthnSession) StoredParameter added in v0.5.0

func (s *AuthnSession) StoredParameter(key string) any

type AuthnSessionManager

type AuthnSessionManager interface {
	Save(ctx context.Context, session *AuthnSession) error
	SessionByCallbackID(ctx context.Context, callbackID string) (*AuthnSession, error)
	// SessionByAuthCode fetches an authn session by the code created during the
	// authorization code flow.
	// If authorization code is not enabled, this function can be left empty.
	SessionByAuthCode(ctx context.Context, authorizationCode string) (*AuthnSession, error)
	// SessionByPushedAuthReqID fetches an authn session by the request URI created
	// during PAR.
	// If PAR is not enabled, this function can be left empty.
	SessionByPushedAuthReqID(ctx context.Context, id string) (*AuthnSession, error)
	// SessionByCIBAAuthID fetches an authn session by the auth request ID created
	// during CIBA.
	// If CIBA is not enabled, this function can be left empty.
	SessionByCIBAAuthID(ctx context.Context, id string) (*AuthnSession, error)
	Delete(ctx context.Context, id string) error
}

AuthnSessionManager contains all the logic needed to manage authentication sessions.

type AuthnStatus

type AuthnStatus string
const (
	StatusSuccess    AuthnStatus = "success"
	StatusInProgress AuthnStatus = "in_progress"
	StatusFailure    AuthnStatus = "failure"
)

type AuthorizationDetail

type AuthorizationDetail map[string]any

AuthorizationDetail represents an authorization details as a map. It is a map instead of a struct, because its fields vary a lot depending on the use case.

func (AuthorizationDetail) Actions

func (d AuthorizationDetail) Actions() []string

func (AuthorizationDetail) DataTypes

func (d AuthorizationDetail) DataTypes() []string

func (AuthorizationDetail) Identifier

func (d AuthorizationDetail) Identifier() string

func (AuthorizationDetail) Locations

func (d AuthorizationDetail) Locations() []string

func (AuthorizationDetail) Type

func (d AuthorizationDetail) Type() string

type AuthorizationParameters

type AuthorizationParameters struct {
	RequestURI              string                `json:"request_uri,omitempty"`
	RequestObject           string                `json:"request,omitempty"`
	RedirectURI             string                `json:"redirect_uri,omitempty"`
	ResponseMode            ResponseMode          `json:"response_mode,omitempty"`
	ResponseType            ResponseType          `json:"response_type,omitempty"`
	Scopes                  string                `json:"scope,omitempty"`
	State                   string                `json:"state,omitempty"`
	Nonce                   string                `json:"nonce,omitempty"`
	CodeChallenge           string                `json:"code_challenge,omitempty"`
	CodeChallengeMethod     CodeChallengeMethod   `json:"code_challenge_method,omitempty"`
	Prompt                  PromptType            `json:"prompt,omitempty"`
	MaxAuthnAgeSecs         *int                  `json:"max_age,omitempty"`
	Display                 DisplayValue          `json:"display,omitempty"`
	ACRValues               string                `json:"acr_values,omitempty"`
	Claims                  *ClaimsObject         `json:"claims,omitempty"`
	AuthDetails             []AuthorizationDetail `json:"authorization_details,omitempty"`
	Resources               Resources             `json:"resource,omitempty"`
	DPoPJKT                 string                `json:"dpop_jkt,omitempty"`
	LoginHint               string                `json:"login_hint,omitempty"`
	LoginTokenHint          string                `json:"login_hint_token,omitempty"`
	IDTokenHint             string                `json:"id_token_hint,omitempty"`
	ClientNotificationToken string                `json:"client_notification_token,omitempty"`
	BindingMessage          string                `json:"binding_message,omitempty"`
	UserCode                string                `json:"user_code,omitempty"`
	RequestedExpiry         *int                  `json:"requested_expiry,omitempty"`
}

type CIBATokenDeliveryMode added in v0.5.0

type CIBATokenDeliveryMode string
const (
	CIBATokenDeliveryModePoll CIBATokenDeliveryMode = "poll"
	CIBATokenDeliveryModePing CIBATokenDeliveryMode = "ping"
	CIBATokenDeliveryModePush CIBATokenDeliveryMode = "push"
)

func (CIBATokenDeliveryMode) IsNotificationMode added in v0.5.0

func (mode CIBATokenDeliveryMode) IsNotificationMode() bool

func (CIBATokenDeliveryMode) IsPollableMode added in v0.5.0

func (mode CIBATokenDeliveryMode) IsPollableMode() bool

type CheckJTIFunc added in v0.3.0

type CheckJTIFunc func(context.Context, string) error

CheckJTIFunc defines a function to verify when a JTI is safe to use.

type ClaimObjectInfo

type ClaimObjectInfo struct {
	IsEssential bool     `json:"essential"`
	Value       string   `json:"value"`
	Values      []string `json:"values"`
}

type ClaimType

type ClaimType string
const (
	ClaimTypeNormal      ClaimType = "normal"
	ClaimTypeAggregated  ClaimType = "aggregated"
	ClaimTypeDistributed ClaimType = "distributed"
)

type ClaimsObject

type ClaimsObject struct {
	UserInfo map[string]ClaimObjectInfo `json:"userinfo"`
	IDToken  map[string]ClaimObjectInfo `json:"id_token"`
}

func (ClaimsObject) IDTokenClaim

func (claims ClaimsObject) IDTokenClaim(claimName string) (ClaimObjectInfo, bool)

IDTokenClaim returns the claim object info if present.

func (ClaimsObject) IDTokenEssentials

func (claims ClaimsObject) IDTokenEssentials() []string

IDTokenEssentials returns all the essentials claims requested by the client to be returned in the ID token.

func (ClaimsObject) UserInfoClaim

func (claims ClaimsObject) UserInfoClaim(claimName string) (ClaimObjectInfo, bool)

UserInfoClaim returns the claim object info if present.

func (ClaimsObject) UserInfoEssentials

func (claims ClaimsObject) UserInfoEssentials() []string

UserInfoEssentials returns all the essentials claims requested by the client to be returned in the userinfo endpoint.

type Client

type Client struct {
	ID string `json:"client_id"`
	// Secret is used when the client authenticates with client_secret_jwt,
	// since the key used to sign the assertion is the same used to verify it.
	Secret string `json:"client_secret,omitempty"`
	// HashedSecret is the hash of the client secret for the client_secret_basic
	// and client_secret_post authentication methods.
	HashedSecret string `json:"hashed_secret,omitempty"`
	// HashedRegistrationAccessToken is the hash of the registration access token
	// generated during dynamic client registration.
	HashedRegistrationAccessToken string `json:"hashed_registration_access_token"`
	ClientMetaInfo
}

Client contains all information about an OAuth client.

func (*Client) FetchPublicJWKS

func (c *Client) FetchPublicJWKS(httpClient *http.Client) (JSONWebKeySet, error)

FetchPublicJWKS fetches the client public JWKS either directly from the jwks attribute or using jwks_uri.

This function also caches the keys if they are fetched from jwks_uri.

func (*Client) IsPublic added in v0.3.0

func (c *Client) IsPublic() bool

type ClientAssertionType

type ClientAssertionType string
const (
	AssertionTypeJWTBearer ClientAssertionType = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"
)

type ClientAuthnType

type ClientAuthnType string
const (
	ClientAuthnNone          ClientAuthnType = "none"
	ClientAuthnSecretBasic   ClientAuthnType = "client_secret_basic"
	ClientAuthnSecretPost    ClientAuthnType = "client_secret_post"
	ClientAuthnSecretJWT     ClientAuthnType = "client_secret_jwt"
	ClientAuthnPrivateKeyJWT ClientAuthnType = "private_key_jwt"
	ClientAuthnTLS           ClientAuthnType = "tls_client_auth"
	ClientAuthnSelfSignedTLS ClientAuthnType = "self_signed_tls_client_auth"
)

type ClientCertFunc

type ClientCertFunc func(*http.Request) (*x509.Certificate, error)

type ClientManager

type ClientManager interface {
	Save(ctx context.Context, client *Client) error
	Client(ctx context.Context, id string) (*Client, error)
	Delete(ctx context.Context, id string) error
}

ClientManager gathers all the logic needed to manage clients.

type ClientMetaInfo

type ClientMetaInfo struct {
	Name              string          `json:"client_name,omitempty"`
	ApplicationType   ApplicationType `json:"application_type,omitempty"`
	LogoURI           string          `json:"logo_uri,omitempty"`
	Contacts          []string        `json:"contacts,omitempty"`
	PolicyURI         string          `json:"policy_uri,omitempty"`
	TermsOfServiceURI string          `json:"tos_uri,omitempty"`
	RedirectURIs      []string        `json:"redirect_uris,omitempty"`
	RequestURIs       []string        `json:"request_uris,omitempty"`
	GrantTypes        []GrantType     `json:"grant_types"`
	ResponseTypes     []ResponseType  `json:"response_types"`
	PublicJWKSURI     string          `json:"jwks_uri,omitempty"`
	PublicJWKS        json.RawMessage `json:"jwks,omitempty"`
	// ScopeIDs contains the scopes available to the client separeted by spaces.
	ScopeIDs              string                     `json:"scope,omitempty"`
	SubIdentifierType     SubIdentifierType          `json:"subject_type,omitempty"`
	SectorIdentifierURI   string                     `json:"sector_identifier_uri,omitempty"`
	IDTokenSigAlg         SignatureAlgorithm         `json:"id_token_signed_response_alg,omitempty"`
	IDTokenKeyEncAlg      KeyEncryptionAlgorithm     `json:"id_token_encrypted_response_alg,omitempty"`
	IDTokenContentEncAlg  ContentEncryptionAlgorithm `json:"id_token_encrypted_response_enc,omitempty"`
	UserInfoSigAlg        SignatureAlgorithm         `json:"userinfo_signed_response_alg,omitempty"`
	UserInfoKeyEncAlg     KeyEncryptionAlgorithm     `json:"userinfo_encrypted_response_alg,omitempty"`
	UserInfoContentEncAlg ContentEncryptionAlgorithm `json:"userinfo_encrypted_response_enc,omitempty"`
	JARIsRequired         bool                       `json:"require_signed_request_object,omitempty"`
	// TODO: Is JAR required if this is informed?
	JARSigAlg                     SignatureAlgorithm         `json:"request_object_signing_alg,omitempty"`
	JARKeyEncAlg                  KeyEncryptionAlgorithm     `json:"request_object_encryption_alg,omitempty"`
	JARContentEncAlg              ContentEncryptionAlgorithm `json:"request_object_encryption_enc,omitempty"`
	JARMSigAlg                    SignatureAlgorithm         `json:"authorization_signed_response_alg,omitempty"`
	JARMKeyEncAlg                 KeyEncryptionAlgorithm     `json:"authorization_encrypted_response_alg,omitempty"`
	JARMContentEncAlg             ContentEncryptionAlgorithm `json:"authorization_encrypted_response_enc,omitempty"`
	TokenAuthnMethod              ClientAuthnType            `json:"token_endpoint_auth_method"`
	TokenAuthnSigAlg              SignatureAlgorithm         `json:"token_endpoint_auth_signing_alg,omitempty"`
	TokenIntrospectionAuthnMethod ClientAuthnType            `json:"introspection_endpoint_auth_method,omitempty"`
	TokenIntrospectionAuthnSigAlg SignatureAlgorithm         `json:"introspection_endpoint_auth_signing_alg,omitempty"`
	TokenRevocationAuthnMethod    ClientAuthnType            `json:"revocation_endpoint_auth_method,omitempty"`
	TokenRevocationAuthnSigAlg    SignatureAlgorithm         `json:"revocation_endpoint_auth_signing_alg,omitempty"`
	DPoPTokenBindingIsRequired    bool                       `json:"dpop_bound_access_tokens,omitempty"`
	TLSSubDistinguishedName       string                     `json:"tls_client_auth_subject_dn,omitempty"`
	// TLSSubAlternativeName represents a DNS name.
	TLSSubAlternativeName     string                `json:"tls_client_auth_san_dns,omitempty"`
	TLSSubAlternativeNameIp   string                `json:"tls_client_auth_san_ip,omitempty"`
	TLSTokenBindingIsRequired bool                  `json:"tls_client_certificate_bound_access_tokens,omitempty"`
	AuthDetailTypes           []string              `json:"authorization_data_types,omitempty"`
	DefaultMaxAgeSecs         *int                  `json:"default_max_age,omitempty"`
	DefaultACRValues          string                `json:"default_acr_values,omitempty"`
	PARIsRequired             bool                  `json:"require_pushed_authorization_requests,omitempty"`
	CIBATokenDeliveryMode     CIBATokenDeliveryMode `json:"backchannel_token_delivery_mode,omitempty"`
	CIBANotificationEndpoint  string                `json:"backchannel_client_notification_endpoint,omitempty"`
	CIBAJARSigAlg             SignatureAlgorithm    `json:"backchannel_authentication_request_signing_alg,omitempty"`
	CIBAUserCodeIsEnabled     bool                  `json:"backchannel_user_code_parameter,omitempty"`
	// CustomAttributes holds any additional dynamic attributes a client may
	// provide during registration.
	// These attributes allow clients to extend their metadata beyond the
	// predefined fields (e.g., client_name, logo_uri).
	// During DCR, any attributes that are not explicitly defined in the struct
	// will be captured here.
	// These additional fields are **flattened** in the DCR response, meaning
	// they are merged directly into the JSON response alongside standard fields.
	CustomAttributes map[string]any `json:"custom_attributes,omitempty"`
}

func (*ClientMetaInfo) Attribute added in v0.3.0

func (c *ClientMetaInfo) Attribute(key string) any

func (*ClientMetaInfo) SetAttribute added in v0.3.0

func (c *ClientMetaInfo) SetAttribute(key string, value any)

type CodeChallengeMethod

type CodeChallengeMethod string
const (
	CodeChallengeMethodSHA256 CodeChallengeMethod = "S256"
	CodeChallengeMethodPlain  CodeChallengeMethod = "plain"
)

type CompareAuthDetailsFunc added in v0.4.0

type CompareAuthDetailsFunc func(granted, requested []AuthorizationDetail) error

CompareAuthDetailsFunc defines a function used in authorization_code and refresh_token grant types to validate that the requested authorization details are consistent with the granted ones.

type ContentEncryptionAlgorithm added in v0.6.0

type ContentEncryptionAlgorithm = jose.ContentEncryption
const (
	A128CBC_HS256 ContentEncryptionAlgorithm = jose.A128CBC_HS256
	A192CBC_HS384 ContentEncryptionAlgorithm = jose.A192CBC_HS384
	A256CBC_HS512 ContentEncryptionAlgorithm = jose.A256CBC_HS512
	A128GCM       ContentEncryptionAlgorithm = jose.A128GCM
	A192GCM       ContentEncryptionAlgorithm = jose.A192GCM
	A256GCM       ContentEncryptionAlgorithm = jose.A256GCM
)

type DecrypterFunc added in v0.6.0

type DecrypterFunc func(ctx context.Context, kid string, alg KeyEncryptionAlgorithm) (crypto.Decrypter, error)

type DisplayValue

type DisplayValue string
const (
	DisplayValuePage  DisplayValue = "page"
	DisplayValuePopUp DisplayValue = "popup"
	DisplayValueTouch DisplayValue = "touch"
	DisplayValueWAP   DisplayValue = "wap"
)

type Error added in v0.1.1

type Error struct {
	Code        ErrorCode `json:"error,omitempty"`
	Description string    `json:"error_description,omitempty"`
	URI         string    `json:"error_uri,omitempty"`
	// contains filtered or unexported fields
}

func NewError added in v0.1.1

func NewError(code ErrorCode, desc string) Error

func WrapError added in v0.5.0

func WrapError(code ErrorCode, desc string, err error) Error

func (Error) Error added in v0.1.1

func (err Error) Error() string

func (Error) StatusCode added in v0.5.0

func (err Error) StatusCode() int

func (Error) Unwrap added in v0.1.1

func (err Error) Unwrap() error

func (Error) WithStatusCode added in v0.6.0

func (err Error) WithStatusCode(status int) Error

func (Error) WithURI added in v0.6.0

func (err Error) WithURI(uri string) Error

type ErrorCode added in v0.1.1

type ErrorCode string
const (
	ErrorCodeAccessDenied           ErrorCode = "access_denied"
	ErrorCodeInvalidClient          ErrorCode = "invalid_client"
	ErrorCodeInvalidGrant           ErrorCode = "invalid_grant"
	ErrorCodeInvalidRequest         ErrorCode = "invalid_request"
	ErrorCodeUnauthorizedClient     ErrorCode = "unauthorized_client"
	ErrorCodeInvalidScope           ErrorCode = "invalid_scope"
	ErrorCodeInvalidAuthDetails     ErrorCode = "invalid_authorization_details"
	ErrorCodeUnsupportedGrantType   ErrorCode = "unsupported_grant_type"
	ErrorCodeInvalidResquestObject  ErrorCode = "invalid_request_object"
	ErrorCodeInvalidToken           ErrorCode = "invalid_token"
	ErrorCodeInternalError          ErrorCode = "internal_error"
	ErrorCodeInvalidTarget          ErrorCode = "invalid_target"
	ErrorCodeInvalidRedirectURI     ErrorCode = "invalid_redirect_uri"
	ErrorCodeInvalidClientMetadata  ErrorCode = "invalid_client_metadata"
	ErrorCodeRequestURINotSupported ErrorCode = "request_uri_not_supported"
	ErrorCodeLoginRequired          ErrorCode = "login_required"
	ErrorCodeAuthPending            ErrorCode = "authorization_pending"
	ErrorCodeSlowDown               ErrorCode = "slow_down"
	ErrorCodeExpiredToken           ErrorCode = "expired_token"
	ErrorCodeMissingUserCode        ErrorCode = "missing_user_code"
	ErrorCodeInvalidUserCode        ErrorCode = "invalid_user_code"
	ErrorCodeInvalidBindingMessage  ErrorCode = "invalid_binding_message"
	ErrorCodeUnknownUserID          ErrorCode = "unknown_user_id"
	ErrorCodeTransactionFailed      ErrorCode = "transaction_failed"
	ErrorCodeExpiredLoginHintToken  ErrorCode = "expired_login_hint_token"
)

func (ErrorCode) StatusCode added in v0.1.1

func (c ErrorCode) StatusCode() int

type GeneratePairwiseSubIDFunc added in v0.5.0

type GeneratePairwiseSubIDFunc func(ctx context.Context, sub string, client *Client) string

type GrantInfo added in v0.0.2

type GrantInfo struct {
	GrantType GrantType `json:"grant_type"`
	// Subject is the ID of the user or client associated with the grant.
	Subject  string `json:"sub"`
	ClientID string `json:"client_id"`

	// ActiveScopes represents the subset of GrantedScopes that are active
	// for the current access token.
	// Typically, ActiveScopes are equals to GrantedScopes, unless the token
	// request asks fewer scopes than initially granted.
	ActiveScopes string `json:"active_scopes"`
	// GrantedScopes lists all scopes the client has permission to access.
	GrantedScopes string `json:"granted_scopes"`
	// ActiveAuthDetails contains the subset of GrantedAuthDetails currently
	// active for this access token.
	ActiveAuthDetails []AuthorizationDetail `json:"active_auth_details,omitempty"`
	// GrantedAuthDetails holds all authorization details assigned to the client.
	GrantedAuthDetails []AuthorizationDetail `json:"granted_auth_details,omitempty"`
	// ActiveResources are the specific resources the current token can be used
	// with.
	ActiveResources Resources `json:"active_resources,omitempty"`
	// GrantedResources lists all resources the client was authorized to interact.
	GrantedResources Resources `json:"granted_resources,omitempty"`

	AdditionalIDTokenClaims  map[string]any `json:"additional_id_token_claims,omitempty"`
	AdditionalUserInfoClaims map[string]any `json:"additional_user_info_claims,omitempty"`
	AdditionalTokenClaims    map[string]any `json:"additional_token_claims,omitempty"`

	// JWKThumbprint stores the thumbprint of the JWK provided via DPoP.
	JWKThumbprint string `json:"jwk_thumbprint,omitempty"`
	// ClientCertThumbprint contains the thumbprint of the certificate used by
	// the client to generate the token.
	ClientCertThumbprint string `json:"client_cert_thumbprint,omitempty"`

	// Store allows storing custom data within the grant session.
	Store map[string]any `json:"store,omitempty"`
}

GrantInfo contains the information assigned during token issuance.

  • For authorization_code, implicit, refresh_token, and ciba grant types: Granted information represents what the user authorized. Active information is either the subset requested by the client during the token request or the full granted information if no specific subset was requested.

  • For client_credentials and jwt_bearer grant types: Both granted and active information reflect exactly what the client requested in the token request.

Additional validations can be performed using a HandleGrantFunc.

type GrantSession

type GrantSession struct {
	ID string `json:"id"`
	// TokenID is the id of the token issued for this grant.
	TokenID      string `json:"token_id"`
	RefreshToken string `json:"refresh_token,omitempty"`
	// LastTokenExpiresAtTimestamp indicates the timestamp when the last issued
	// token for this grant will expire.
	LastTokenExpiresAtTimestamp int `json:"last_token_expires_at"`
	CreatedAtTimestamp          int `json:"created_at"`
	// ExpiresAtTimestamp is the timestamp for when the overall grant session
	// will expire.
	// If a refresh token is issued with the access token, ExpiresAtTimestamp
	// will be later than LastTokenExpiresAtTimestamp.
	// Otherwise, ExpiresAtTimestamp and LastTokenExpiresAtTimestamp will match.
	ExpiresAtTimestamp int `json:"expires_at"`
	// AuthorizationCode is the authorization code used to generate this grant
	// session in case of authorization code grant type.
	AuthorizationCode string `json:"authorization_code,omitempty"`
	GrantInfo
}

GrantSession represents the granted access an entity (a user or the client itself) gave to a client. It holds information about the token issued to a client and about the user who granted access.

func (*GrantSession) HasLastTokenExpired

func (g *GrantSession) HasLastTokenExpired() bool

HasLastTokenExpired returns whether the last token issued for the grant session is expired or not.

func (*GrantSession) IsExpired

func (g *GrantSession) IsExpired() bool

type GrantSessionManager

type GrantSessionManager interface {
	Save(context.Context, *GrantSession) error
	SessionByTokenID(context.Context, string) (*GrantSession, error)
	SessionByRefreshToken(context.Context, string) (*GrantSession, error)
	Delete(ctx context.Context, id string) error
	// DeleteByAuthorizationCode deletes a grant session associated with the
	// provided authorization code. This function is a security measure to prevent
	// the reuse of authorization codes, mitigating potential replay attacks.
	// It is an optional, but recommended, behavior to enhance security.
	DeleteByAuthorizationCode(context.Context, string) error
}

GrantSessionManager contains all the logic needed to manage grant sessions.

type GrantType

type GrantType string
const (
	GrantClientCredentials GrantType = "client_credentials"
	GrantAuthorizationCode GrantType = "authorization_code"
	GrantRefreshToken      GrantType = "refresh_token"
	GrantImplicit          GrantType = "implicit"
	GrantJWTBearer         GrantType = "urn:ietf:params:oauth:grant-type:jwt-bearer"
	GrantCIBA              GrantType = "urn:openid:params:grant-type:ciba"
)

type HTTPClientFunc added in v0.1.1

type HTTPClientFunc func(ctx context.Context) *http.Client

HTTPClientFunc defines a function that generates an HTTP client for performing requests. Note: Make sure to not enable automatic redirect-following, as some profiles require this behavior is disabled.

type HandleDynamicClientFunc

type HandleDynamicClientFunc func(*http.Request, *ClientMetaInfo) error

HandleDynamicClientFunc defines a function that will be executed during DCR and DCM. It can be used to modify the client and perform custom validations.

type HandleGrantFunc added in v0.0.2

type HandleGrantFunc func(*http.Request, *GrantInfo) error

type HandleJWTBearerGrantAssertionFunc added in v0.4.0

type HandleJWTBearerGrantAssertionFunc func(
	r *http.Request,
	assertion string,
) (
	JWTBearerGrantInfo,
	error,
)

type InitBackAuthFunc added in v0.5.0

type InitBackAuthFunc func(context.Context, *AuthnSession) error

InitBackAuthFunc allows modifying the authn session when initializing the CIBA process. If an error is returned, the authentication flow will not be initiated.

type IsClientAllowedFunc added in v0.4.0

type IsClientAllowedFunc func(*Client) bool

type JSONWebKey added in v0.6.0

type JSONWebKey = jose.JSONWebKey

type JSONWebKeySet added in v0.6.0

type JSONWebKeySet struct {
	Keys []JSONWebKey `json:"keys"`
}

func (JSONWebKeySet) Key added in v0.6.0

func (jwks JSONWebKeySet) Key(kid string) (JSONWebKey, error)

type JWKSFunc added in v0.5.0

type JWKSFunc func(context.Context) (JSONWebKeySet, error)

type JWTBearerGrantInfo added in v0.4.0

type JWTBearerGrantInfo struct {
	Subject string
	Store   map[string]any
}

type KeyEncryptionAlgorithm added in v0.6.0

type KeyEncryptionAlgorithm = jose.KeyAlgorithm
const (
	RSA1_5       KeyEncryptionAlgorithm = jose.RSA1_5
	RSA_OAEP     KeyEncryptionAlgorithm = jose.RSA_OAEP
	RSA_OAEP_256 KeyEncryptionAlgorithm = jose.RSA_OAEP_256
)

type KeyUsage

type KeyUsage string
const (
	KeyUsageSignature  KeyUsage = "sig"
	KeyUsageEncryption KeyUsage = "enc"
)

type MatchScopeFunc

type MatchScopeFunc func(requestedScope string) bool

MatchScopeFunc defines a function executed to verify whether a requested scope is a match or not.

type MiddlewareFunc

type MiddlewareFunc func(next http.Handler) http.Handler

type NotifyErrorFunc added in v0.4.0

type NotifyErrorFunc func(context.Context, error)

type Profile

type Profile string
const (
	ProfileOpenID Profile = "openid"
	ProfileFAPI2  Profile = "fapi2"
	ProfileFAPI1  Profile = "fapi1"
)

func (Profile) IsFAPI added in v0.6.0

func (p Profile) IsFAPI() bool

type PromptType

type PromptType string
const (
	PromptTypeNone          PromptType = "none"
	PromptTypeLogin         PromptType = "login"
	PromptTypeConsent       PromptType = "consent"
	PromptTypeSelectAccount PromptType = "select_account"
)

type RenderErrorFunc

type RenderErrorFunc func(http.ResponseWriter, *http.Request, error) error

RenderErrorFunc defines a function that will be called when errors during the authorization request cannot be handled.

type Resources

type Resources []string

func (Resources) MarshalJSON

func (resources Resources) MarshalJSON() ([]byte, error)

func (*Resources) UnmarshalJSON

func (r *Resources) UnmarshalJSON(data []byte) error

type ResponseMode

type ResponseMode string
const (
	ResponseModeQuery       ResponseMode = "query"
	ResponseModeFragment    ResponseMode = "fragment"
	ResponseModeFormPost    ResponseMode = "form_post"
	ResponseModeQueryJWT    ResponseMode = "query.jwt"
	ResponseModeFragmentJWT ResponseMode = "fragment.jwt"
	ResponseModeFormPostJWT ResponseMode = "form_post.jwt"
	ResponseModeJWT         ResponseMode = "jwt"
)

func (ResponseMode) IsJARM

func (rm ResponseMode) IsJARM() bool

func (ResponseMode) IsPlain

func (rm ResponseMode) IsPlain() bool

func (ResponseMode) IsQuery

func (rm ResponseMode) IsQuery() bool

type ResponseType

type ResponseType string
const (
	ResponseTypeCode                   ResponseType = "code"
	ResponseTypeIDToken                ResponseType = "id_token"
	ResponseTypeToken                  ResponseType = "token"
	ResponseTypeCodeAndIDToken         ResponseType = "code id_token"
	ResponseTypeCodeAndToken           ResponseType = "code token"
	ResponseTypeIDTokenAndToken        ResponseType = "id_token token"
	ResponseTypeCodeAndIDTokenAndToken ResponseType = "code id_token token"
)

func (ResponseType) Contains

func (rt ResponseType) Contains(responseType ResponseType) bool

func (ResponseType) IsImplicit

func (rt ResponseType) IsImplicit() bool

type Scope

type Scope struct {
	// ID is the string representation of the scope.
	// Its value will be published as is in the well known endpoint.
	ID string
	// Matches validates if a requested scope matches the current scope.
	Matches MatchScopeFunc
}

func NewDynamicScope

func NewDynamicScope(
	scope string,
	matchingFunc MatchScopeFunc,
) Scope

NewDynamicScope creates a scope with custom logic that will be used to validate the scopes requested by the client.

dynamicScope := NewDynamicScope(
	"payment",
	func(requestedScope string) bool {
		return strings.HasPrefix(requestedScope, "payment:")
	},
)

// This results in true.
dynamicScope.Matches("payment:30")

func NewScope

func NewScope(scope string) Scope

NewScope creates a scope where the validation logic is simple string comparison.

type SetUpAuthnFunc

type SetUpAuthnFunc func(*http.Request, *Client, *AuthnSession) bool

SetUpAuthnFunc is responsible for initiating the authentication session. It returns true when the policy is ready to executed and false for when the policy should be skipped.

type ShouldIssueRefreshTokenFunc added in v0.1.1

type ShouldIssueRefreshTokenFunc func(*Client, GrantInfo) bool

type SignatureAlgorithm added in v0.6.0

type SignatureAlgorithm = jose.SignatureAlgorithm
const (
	None  SignatureAlgorithm = "none"
	HS256 SignatureAlgorithm = jose.HS256
	HS384 SignatureAlgorithm = jose.HS384
	HS512 SignatureAlgorithm = jose.HS512
	RS256 SignatureAlgorithm = jose.RS256
	RS384 SignatureAlgorithm = jose.RS384
	RS512 SignatureAlgorithm = jose.RS512
	ES256 SignatureAlgorithm = jose.ES256
	ES384 SignatureAlgorithm = jose.ES384
	ES512 SignatureAlgorithm = jose.ES512
	PS256 SignatureAlgorithm = jose.PS256
	PS384 SignatureAlgorithm = jose.PS384
	PS512 SignatureAlgorithm = jose.PS512
)

type SignerFunc added in v0.6.0

type SignerFunc func(ctx context.Context, alg SignatureAlgorithm) (keyID string, signer crypto.Signer, err error)

type SubIdentifierType added in v0.5.0

type SubIdentifierType string

SubIdentifierType defines how the auth server provides subject identifiers to its clients. For more information, see: https://openid.net/specs/openid-connect-core-1_0.html#SubjectIDTypes

const (
	// SubIdentifierPublic makes the server provide the same subject
	// identifier to all clients.
	SubIdentifierPublic   SubIdentifierType = "public"
	SubIdentifierPairwise SubIdentifierType = "pairwise"
)

type TokenConfirmation

type TokenConfirmation struct {
	JWKThumbprint        string `json:"jkt,omitempty"`
	ClientCertThumbprint string `json:"x5t#S256,omitempty"`
}

type TokenFormat

type TokenFormat string
const (
	TokenFormatJWT    TokenFormat = "jwt"
	TokenFormatOpaque TokenFormat = "opaque"
)

type TokenInfo

type TokenInfo struct {
	// GrantID is the ID of the grant session associated to token.
	GrantID               string                `json:"-"`
	IsActive              bool                  `json:"active"`
	Type                  TokenTypeHint         `json:"token_type,omitempty"`
	Scopes                string                `json:"scope,omitempty"`
	AuthorizationDetails  []AuthorizationDetail `json:"authorization_details,omitempty"`
	ResourceAudiences     Resources             `json:"aud,omitempty"`
	ClientID              string                `json:"client_id,omitempty"`
	Subject               string                `json:"sub,omitempty"`
	ExpiresAtTimestamp    int                   `json:"exp,omitempty"`
	Confirmation          *TokenConfirmation    `json:"cnf,omitempty"`
	AdditionalTokenClaims map[string]any        `json:"-"`
}

func (TokenInfo) MarshalJSON

func (ti TokenInfo) MarshalJSON() ([]byte, error)

type TokenOptions

type TokenOptions struct {
	Format       TokenFormat
	LifetimeSecs int
	JWTSigAlg    SignatureAlgorithm
	OpaqueLength int
}

TokenOptions defines a template for generating access tokens.

func NewJWTTokenOptions

func NewJWTTokenOptions(
	alg SignatureAlgorithm,
	lifetimeSecs int,
) TokenOptions

func NewOpaqueTokenOptions

func NewOpaqueTokenOptions(
	tokenLength int,
	lifetimeSecs int,
) TokenOptions

type TokenOptionsFunc

type TokenOptionsFunc func(GrantInfo, *Client) TokenOptions

TokenOptionsFunc defines a function that returns token configuration and is executed when issuing access tokens.

type TokenType

type TokenType string
const (
	TokenTypeBearer TokenType = "Bearer"
	TokenTypeDPoP   TokenType = "DPoP"
)

type TokenTypeHint

type TokenTypeHint string
const (
	TokenHintAccess  TokenTypeHint = "access_token"
	TokenHintRefresh TokenTypeHint = "refresh_token"
)

type ValidateBackAuthFunc added in v0.5.0

type ValidateBackAuthFunc func(context.Context, *AuthnSession) error

ValidateBackAuthFunc validates a CIBA session during a client's polling request to the token endpoint. If an error other than ErrorCodeAuthPending or ErrorCodeSlowDown is returned, the session will be terminated.

type ValidateInitialAccessTokenFunc added in v0.4.0

type ValidateInitialAccessTokenFunc func(*http.Request, string) error

Jump to

Keyboard shortcuts

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