oidc

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Nov 30, 2022 License: Apache-2.0 Imports: 17 Imported by: 10

README

oidc-go GoDoc

Oidc-go is a Go package to provide common helpers to interface with OpenID Connect servers.

Installation

go get github.com/libregraph/oidc-go

Documentation

Index

Constants

View Source
const (
	// ApplicationTypeWeb is the string value for the OpenID Connect client
	// application_type web.
	ApplicationTypeWeb = "web"

	// ApplicationTypeNative is the string value for the OpenID Connect client
	// application_type web.
	ApplicationTypeNative = "native"
)
View Source
const (
	AuthMethodClientSecretPost  = "client_secret_post"
	AuthMethodClientSecretBasic = "client_secret_basic"
	AuthMethodClientSecretJWT   = "client_secret_jwt"
	AuthMethodPrivateKeyJWT     = "private_key_jwt"
	AuthMethodNone              = "none"
)

Auth method string values as defined by OpenID Connect Core 1.0.

View Source
const (
	IssuerIdentifierClaim  = "iss"
	SubjectIdentifierClaim = "sub"
	AudienceClaim          = "aud"
	ExpirationClaim        = "exp"
	IssuedAtClaim          = "iat"
)

Standard claims as used in JSON Web Tokens.

View Source
const (
	NameClaim              = "name"
	FamilyNameClaim        = "family_name"
	GivenNameClaim         = "given_name"
	MiddleNameClaim        = "middle_name"
	NicknameClaim          = "nickname"
	PreferredUsernameClaim = "preferred_username"
	ProfileClaim           = "profile"
	PictureClaim           = "picture"
	WebsiteClaim           = "website"
	GenderClaim            = "gender"
	BirthdateClaim         = "birthdate"
	ZoneinfoClaim          = "zoneinfo"
	LocaleClaim            = "locale"
	UpdatedAtClaim         = "updated_at"

	EmailClaim         = "email"
	EmailVerifiedClaim = "email_verified"

	AuthTimeClaim = "auth_time"
)

Additional claims as defined by OIDC.

View Source
const (
	PlainCodeChallengeMethod = "plain"
	S256CodeChallengeMethod  = "S256"
)

Code challenge methods implemented by Konnect. See https://tools.ietf.org/html/rfc7636.

View Source
const (
	ErrorCodeOAuth2UnsupportedResponseType = "unsupported_response_type"
	ErrorCodeOAuth2InvalidRequest          = "invalid_request"
	ErrorCodeOAuth2InvalidToken            = "invalid_token"
	ErrorCodeOAuth2InsufficientScope       = "insufficient_scope"
	ErrorCodeOAuth2InvalidGrant            = "invalid_grant"
	ErrorCodeOAuth2UnsupportedGrantType    = "unsupported_grant_type"
	ErrorCodeOAuth2AccessDenied            = "access_denied"
	ErrorCodeOAuth2ServerError             = "server_error"
	ErrorCodeOAuth2TemporarilyUnavailable  = "temporarily_unavailable"
)

OAuth2 error codes.

View Source
const (
	ErrorCodeOIDCInteractionRequired = "interaction_required"
	ErrorCodeOIDCLoginRequired       = "login_required"
	ErrorCodeOIDCConsentRequired     = "consent_required"

	ErrorCodeOIDCRequestNotSupported      = "request_not_supported"
	ErrorCodeOIDCInvalidRequestObject     = "invalid_request_object"
	ErrorCodeOIDCRequestURINotSupported   = "request_uri_not_supported"
	ErrorCodeOIDCRegistrationNotSupported = "registration_not_supported"

	ErrorCodeOIDCInvalidRedirectURI    = "invalid_redirect_uri"
	ErrorCodeOIDCInvalidClientMetadata = "invalid_client_metadata"
)

OIDC error codes.

View Source
const (
	ResponseTypeCode             = "code"                // OIDC code flow
	ResponseTypeIDTokenToken     = "id_token token"      // OIDC implicit flow
	ResponseTypeIDToken          = "id_token"            // OIDC implicit flow
	ResponseTypeCodeIDToken      = "code id_token"       // OIDC hybrid flow
	ResponseTypeCodeToken        = "code token"          // OIDC hybrid flow
	ResponseTypeCodeIDTokenToken = "code id_token token" // OIDC hybrid flow
	ResponseTypeToken            = "token"               // OAuth2

	ResponseModeFragment = "fragment"
	ResponseModeQuery    = "query"

	FlowCode     = "code"
	FlowImplicit = "implicit"
	FlowHybrid   = "hybrid"
)

OIDC response types and flows.

View Source
const (
	// GrantTypeAuthorizationCode is the string value for the
	// OAuth2 authroization code token request grant type.
	GrantTypeAuthorizationCode = "authorization_code"

	// GrantTypeImplicit is the string value for the OAuth2 id_token, token
	// id_token token request grant type.
	GrantTypeImplicit = "implicit"

	// GrantTypeRefreshToken is the string value for the OAuth2 refresh_token
	// token request grant_type.
	GrantTypeRefreshToken = "refresh_token"
)
View Source
const (
	PromptNone          = "none"
	PromptLogin         = "login"
	PromptConsent       = "consent"
	PromptSelectAccount = "select_account"
)

OIDC prompt values. See http://openid.net/specs/openid-connect-core-1_0.html#AuthRequest

View Source
const (
	// ScopeOpenID is the string value of the base OIDC scope.
	ScopeOpenID = "openid"
	// ScopeProfile is the string value of the OIDC profile scope.
	ScopeProfile = "profile"
	// ScopeEmail is the string value of the OIDC email scope.
	ScopeEmail = "email"
	// ScopeOfflineAccess is the string value of the OIDC offline_access scope.
	ScopeOfflineAccess = "offline_access"
)
View Source
const (
	JWTHeaderKeyID = "kid"
	JWTHeaderAlg   = "alg"
)

Token header as used in JSON web tokens.

View Source
const (
	SessionIDClaim = "sid"
)

Additional claims as defined by OIDC extensions.

View Source
const (
	// SubjectIDPublic is the the string value of the Subject Identifier Type
	// as defined in https://openid.net/specs/openid-connect-core-1_0.html#SubjectIDTypes
	SubjectIDPublic = "public"
)
View Source
const TokenTypeBearer = "Bearer"

TokenTypeBearer is required for OIDC as defined in http://openid.net/specs/openid-connect-core-1_0.html.

Variables

View Source
var (
	DefaultHTTPClient       *http.Client
	DefaultHTTPHeader       http.Header
	DefaultMaxJSONFetchSize int64 = 5 * 1024 * 1024 // 5 MiB
	DefaultJSONFetchExpiry        = time.Minute * 1
	DefaultJSONFetchRetry         = time.Second * 3
)

Basic HTTP related global settings.

View Source
var (
	ErrAllreadyInitialized = errors.New("already initialized")
	ErrNotInitialized      = errors.New("not initialized")
	ErrWrongInitialization = errors.New("wrong initialization")
	ErrIssuerMismatch      = errors.New("issuer mismatch")
)

These are the errors that can be returned in ProviderError.Err.

View Source
var DefaultLogger logger = &noopLogger{}

DefaultLogger is the logger used by this library if no other is explicitly specified.

View Source
var DefaultProviderConfig = &ProviderConfig{}

DefaultProviderConfig is the Provider configuration uses when none was explicitly specified.

Functions

func HashFromSigningMethod

func HashFromSigningMethod(alg string) (hash crypto.Hash, err error)

HashFromSigningMethod returns the matching crypto.Hash for the provided signing alg.

func MakeCodeChallenge

func MakeCodeChallenge(method string, verifier string) (string, error)

MakeCodeChallenge creates a code challenge using the provided method and verifier for https://tools.ietf.org/html/rfc7636#section-4.6 verification.

func ValidateCodeChallenge

func ValidateCodeChallenge(challenge string, method string, verifier string) error

ValidateCodeChallenge implements https://tools.ietf.org/html/rfc7636#section-4.6 code challenge verification.

Types

type LeftmostHashBytes

type LeftmostHashBytes []byte

LeftmostHashBytes defines []bytes with Base64URL encoder via String().

func LeftmostHash

func LeftmostHash(data []byte, hash crypto.Hash) LeftmostHashBytes

LeftmostHash hashes the provided data with the provided hash function and returns the left-most half the hashed bytes.

func (LeftmostHashBytes) String

func (lmhb LeftmostHashBytes) String() string

String returns the Base64URL encoded string of the accociated bytes.

type Provider

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

Provider represents an OpenID Connect server's configuration.

func NewProvider

func NewProvider(issuer *url.URL, config *ProviderConfig) (*Provider, error)

NewProvider uses OpenID Connect discovery to create a Provider.

func (*Provider) Initialize

func (p *Provider) Initialize(ctx context.Context, updates chan *ProviderDefinition, errors chan error) error

Initialize initializes the associated Provider with the provided Context. If updates and/or errors channels apre provided, those channels receive any update or update error from the tasks resulting from the initialization. Any of thes channels can be nil, disabling the corresponding events being sent.

func (*Provider) Ready

func (p *Provider) Ready() <-chan struct{}

Ready returns a channel that's closed when the associated Provider is ready.

func (*Provider) Shutdown

func (p *Provider) Shutdown() error

Shutdown stops the associated Provider and waits for it to do so.

type ProviderConfig

type ProviderConfig struct {
	HTTPClient   *http.Client
	HTTPHeader   http.Header
	WellKnownURI *url.URL
	Logger       logger
}

ProviderConfig bundles configuration for a Provider.

type ProviderDefinition

type ProviderDefinition struct {
	WellKnown *WellKnown
	JWKS      *jose.JSONWebKeySet
}

ProviderDefinition holds immutable provider information.

type ProviderError

type ProviderError struct {
	Err error // The actual error
}

A ProviderError is returned for OIDC Provider errors.

func (*ProviderError) Error

func (e *ProviderError) Error() string

type WellKnown

type WellKnown struct {
	Issuer                 string   `json:"issuer"`
	AuthorizationEndpoint  string   `json:"authorization_endpoint"`
	TokenEndpoint          string   `json:"token_endpoint"`
	UserInfoEndpoint       string   `json:"userinfo_endpoint"`
	EndSessionEndpoint     string   `json:"end_session_endpoint"`
	RegistrationEndpoint   string   `json:"registration_endpoint,omitempty"`
	CheckSessionIframe     string   `json:"check_session_iframe,omitempty"`
	JwksURI                string   `json:"jwks_uri"`
	ScopesSupported        []string `json:"scopes_supported"`
	ResponseTypesSupported []string `json:"response_types_supported"`
	SubjectTypesSupported  []string `json:"subject_types_supported"`

	IDTokenSigningAlgValuesSupported           []string `json:"id_token_signing_alg_values_supported"`
	UserInfoSigningAlgValuesSupported          []string `json:"userinfo_signing_alg_values_supported"`
	RequestObjectSigningAlgValuesSupported     []string `json:"request_object_signing_alg_values_supported"`
	TokenEndpointAuthMethodsSupported          []string `json:"token_endpoint_auth_methods_supported"`
	TokenEndpointAuthSigningAlgValuesSupported []string `json:"token_endpoint_auth_signing_alg_values_supported"`

	ClaimsParameterSupported bool     `json:"claims_parameter_supported"`
	ClaimsSupported          []string `json:"claims_supported"`

	RequestParameterSupported    bool `json:"request_parameter_supported"`
	RequestURIParameterSupported bool `json:"request_uri_parameter_supported"`
}

WellKnown defines the OpenID Connect 1.0 discovery provider meta data as specified at https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata

Jump to

Keyboard shortcuts

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