fosite

package module
v1.4.0 Latest Latest
Warning

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

Go to latest
Published: Oct 10, 2026 License: Apache-2.0 Imports: 39 Imported by: 0

README


Pocket ID Fosite

The OAuth 2.0 and OpenID Connect framework behind Pocket ID.

This repository is a fork of Ory Fosite. Ory no longer develops the standalone repository and maintains Fosite in ory/hydra instead. This fork ports those upstream changes and adds the features Pocket ID needs. It is maintained for Pocket ID, so its API follows Pocket ID's requirements and can change between releases.

Specifications

Usage

go get github.com/pocket-id/fosite

See the releases for the available versions.

Development

go test ./...  # run the tests
make format    # fix license headers, Go imports and Markdown formatting
make gen       # regenerate the mocks in internal/

Ory's copyright stays on files inherited from upstream. make format marks inherited files that the fork changes and adds the Pocket ID copyright to new files.

License

Apache 2.0, see LICENSE. Fosite was originally created by Ory.

Documentation

Index

Constants

View Source
const (
	ResponseModeDefault  = ResponseModeType("")
	ResponseModeFormPost = ResponseModeType("form_post")
	ResponseModeQuery    = ResponseModeType("query")
	ResponseModeFragment = ResponseModeType("fragment")
)
View Source
const (
	DefaultCIMDMaxSize              = 5 * 1024 // 5 KiB (draft recommendation)
	DefaultCIMDFetchTimeout         = 15 * time.Second
	DefaultCIMDMaxCacheTTL          = 24 * time.Hour
	DefaultCIMDCacheTTL             = 1 * time.Hour
	DefaultCIMDReferencedURLMaxSize = 1 * 1024 * 1024
)

Default limits for fetching Client ID Metadata Documents. They follow the recommendations in draft-ietf-oauth-client-id-metadata-document.

View Source
const (
	RequestContextKey           = ContextKey("request")
	AccessRequestContextKey     = ContextKey("accessRequest")
	AccessResponseContextKey    = ContextKey("accessResponse")
	AuthorizeRequestContextKey  = ContextKey("authorizeRequest")
	AuthorizeResponseContextKey = ContextKey("authorizeResponse")
	// PushedAuthorizeResponseContextKey is the response context
	PushedAuthorizeResponseContextKey = ContextKey("pushedAuthorizeResponse")
)
View Source
const (
	// User code is active
	UserCodeUnused = UserCodeState(0)
	// User code has been accepted
	UserCodeAccepted = UserCodeState(1)
	// User code has been rejected
	UserCodeRejected = UserCodeState(2)
)
View Source
const (
	AccessToken   TokenType = "access_token"
	RefreshToken  TokenType = "refresh_token"
	AuthorizeCode TokenType = "authorize_code"
	IDToken       TokenType = "id_token"
	UserCode      TokenType = "user_code"
	DeviceCode    TokenType = "device_code"
	// PushedAuthorizeRequestContext represents the PAR context object
	PushedAuthorizeRequestContext TokenType = "par_context"

	GrantTypeImplicit          GrantType = "implicit"
	GrantTypeRefreshToken      GrantType = "refresh_token"
	GrantTypeAuthorizationCode GrantType = "authorization_code"
	GrantTypePassword          GrantType = "password"
	GrantTypeClientCredentials GrantType = "client_credentials"
	GrantTypeJWTBearer         GrantType = "urn:ietf:params:oauth:grant-type:jwt-bearer"  //nolint:gosec // this is not a hardcoded credential
	GrantTypeDeviceCode        GrantType = "urn:ietf:params:oauth:grant-type:device_code" //nolint:gosec // this is not a hardcoded credential

	BearerAccessToken string = "bearer"
)
View Source
const (
	ErrorPARNotSupported           = "The OAuth 2.0 provider does not support Pushed Authorization Requests"
	DebugPARStorageInvalid         = "'PARStorage' not implemented"
	DebugPARConfigMissing          = "'PushedAuthorizeRequestConfigProvider' not implemented"
	DebugPARRequestsHandlerMissing = "'PushedAuthorizeRequestHandlersProvider' not implemented"
)
View Source
const DefaultBCryptWorkFactor = 12
View Source
const MinParameterEntropy = 8

Variables

View Source
var (
	// ErrInvalidatedAuthorizeCode is an error indicating that an authorization code has been
	// used previously.
	ErrInvalidatedAuthorizeCode = stderr.New("Authorization code has been invalidated") //lint:ignore ST1005 Uppercase message OK here
	// ErrInvalidatedDeviceCode is an error indicating that a device code has been used previously.
	ErrInvalidatedDeviceCode = stderr.New("Device code has been invalidated") //lint:ignore ST1005 Uppercase message OK here
	// ErrExistingUserCodeSignature is an error indicating that a row already exists with the provided user_code signature.
	ErrExistingUserCodeSignature = stderr.New("User code signature already exists in the database") //lint:ignore ST1005 Uppercase message OK here
	// ErrSerializationFailure is an error indicating that the transactional capable storage could not guarantee
	// consistency of Update & Delete operations on the same rows between multiple sessions.
	ErrSerializationFailure = &RFC6749Error{
		ErrorField:       errUnknownErrorName,
		DescriptionField: "The request could not be completed because another request is competing for the same resource.",
		CodeField:        http.StatusConflict,
	}
	ErrUnknownRequest = &RFC6749Error{
		ErrorField:       errUnknownErrorName,
		DescriptionField: "The handler is not responsible for this request.",
		CodeField:        http.StatusBadRequest,
	}
	ErrRequestForbidden = &RFC6749Error{
		ErrorField:       errRequestForbidden,
		DescriptionField: "The request is not allowed.",
		HintField:        "You are not allowed to perform this action.",
		CodeField:        http.StatusForbidden,
	}
	ErrInvalidRequest = &RFC6749Error{
		ErrorField:       errInvalidRequestName,
		DescriptionField: "The request is missing a required parameter, includes an invalid parameter value, includes a parameter more than once, or is otherwise malformed.",
		HintField:        "Make sure that the various parameters are correct, be aware of case sensitivity and trim your parameters. Make sure that the client you are using has exactly whitelisted the redirect_uri you specified.",
		CodeField:        http.StatusBadRequest,
	}
	ErrUnauthorizedClient = &RFC6749Error{
		ErrorField:       errUnauthorizedClientName,
		DescriptionField: "The client is not authorized to request a token using this method.",
		HintField:        "Make sure that client id and secret are correctly specified and that the client exists.",
		CodeField:        http.StatusBadRequest,
	}
	ErrAccessDenied = &RFC6749Error{
		ErrorField:       errAccessDeniedName,
		DescriptionField: "The resource owner or authorization server denied the request.",
		HintField:        "Make sure that the request you are making is valid. Maybe the credential or request parameters you are using are limited in scope or otherwise restricted.",
		CodeField:        http.StatusForbidden,
	}
	ErrUnsupportedResponseType = &RFC6749Error{
		ErrorField:       errUnsupportedResponseTypeName,
		DescriptionField: "The authorization server does not support obtaining a token using this method.",
		CodeField:        http.StatusBadRequest,
	}
	ErrUnsupportedResponseMode = &RFC6749Error{
		ErrorField:       errUnsupportedResponseModeName,
		DescriptionField: "The authorization server does not support obtaining a response using this response mode.",
		CodeField:        http.StatusBadRequest,
	}
	ErrInvalidScope = &RFC6749Error{
		ErrorField:       errInvalidScopeName,
		DescriptionField: "The requested scope is invalid, unknown, or malformed.",
		CodeField:        http.StatusBadRequest,
	}
	ErrInvalidTarget = &RFC6749Error{
		ErrorField:       errInvalidTargetName,
		DescriptionField: "The requested resource is invalid, missing, unknown, or malformed.",
		HintField:        "Make sure that the requested resource is correct and available to this client.",
		CodeField:        http.StatusBadRequest,
	}
	ErrServerError = &RFC6749Error{
		ErrorField:       errServerErrorName,
		DescriptionField: "The authorization server encountered an unexpected condition that prevented it from fulfilling the request.",
		CodeField:        http.StatusInternalServerError,
	}
	ErrTemporarilyUnavailable = &RFC6749Error{
		ErrorField:       errTemporarilyUnavailableName,
		DescriptionField: "The authorization server is currently unable to handle the request due to a temporary overloading or maintenance of the server.",
		CodeField:        http.StatusServiceUnavailable,
	}
	ErrUnsupportedGrantType = &RFC6749Error{
		ErrorField:       errUnsupportedGrantTypeName,
		DescriptionField: "The authorization grant type is not supported by the authorization server.",
		CodeField:        http.StatusBadRequest,
	}
	ErrInvalidGrant = &RFC6749Error{
		ErrorField:       errInvalidGrantName,
		DescriptionField: "The provided authorization grant (e.g., authorization code, resource owner credentials) or refresh token is invalid, expired, revoked, does not match the redirection URI used in the authorization request, or was issued to another client.",
		CodeField:        http.StatusBadRequest,
	}
	ErrInvalidClient = &RFC6749Error{
		ErrorField:       errInvalidClientName,
		DescriptionField: "Client authentication failed (e.g., unknown client, no client authentication included, or unsupported authentication method).",
		CodeField:        http.StatusUnauthorized,
	}
	ErrInvalidState = &RFC6749Error{
		ErrorField:       errInvalidStateName,
		DescriptionField: "The state is missing or does not have enough characters and is therefore considered too weak.",
		CodeField:        http.StatusBadRequest,
	}
	ErrMisconfiguration = &RFC6749Error{
		ErrorField:       errMisconfigurationName,
		DescriptionField: "The request failed because of an internal error that is probably caused by misconfiguration.",
		CodeField:        http.StatusInternalServerError,
	}
	ErrInsufficientEntropy = &RFC6749Error{
		ErrorField:       errInsufficientEntropyName,
		DescriptionField: "The request used a security parameter (e.g., anti-replay, anti-csrf) with insufficient entropy.",
		CodeField:        http.StatusBadRequest,
	}
	ErrNotFound = &RFC6749Error{
		ErrorField:       errNotFoundName,
		DescriptionField: "Could not find the requested resource(s).",
		CodeField:        http.StatusNotFound,
	}
	ErrRequestUnauthorized = &RFC6749Error{
		ErrorField:       errRequestUnauthorizedName,
		DescriptionField: "The request could not be authorized.",
		HintField:        "Check that you provided valid credentials in the right format.",
		CodeField:        http.StatusUnauthorized,
	}
	ErrTokenSignatureMismatch = &RFC6749Error{
		ErrorField:       errTokenSignatureMismatchName,
		DescriptionField: "Token signature mismatch.",
		HintField:        "Check that you provided  a valid token in the right format.",
		CodeField:        http.StatusBadRequest,
	}
	ErrInvalidTokenFormat = &RFC6749Error{
		ErrorField:       errInvalidTokenFormatName,
		DescriptionField: "Invalid token format.",
		HintField:        "Check that you provided a valid token in the right format.",
		CodeField:        http.StatusBadRequest,
	}
	ErrTokenExpired = &RFC6749Error{
		ErrorField:       errTokenExpiredName,
		DescriptionField: "Token expired.",
		HintField:        "The token expired.",
		CodeField:        http.StatusUnauthorized,
	}
	ErrScopeNotGranted = &RFC6749Error{
		ErrorField:       errScopeNotGrantedName,
		DescriptionField: "The token was not granted the requested scope.",
		HintField:        "The resource owner did not grant the requested scope.",
		CodeField:        http.StatusForbidden,
	}
	ErrTokenClaim = &RFC6749Error{
		ErrorField:       errTokenClaimName,
		DescriptionField: "The token failed validation due to a claim mismatch.",
		HintField:        "One or more token claims failed validation.",
		CodeField:        http.StatusUnauthorized,
	}
	ErrInactiveToken = &RFC6749Error{
		ErrorField:       errTokenInactiveName,
		DescriptionField: "Token is inactive because it is malformed, expired or otherwise invalid.",
		HintField:        "Token validation failed.",
		CodeField:        http.StatusUnauthorized,
	}
	ErrLoginRequired = &RFC6749Error{
		ErrorField:       errLoginRequired,
		DescriptionField: "The Authorization Server requires End-User authentication.",
		CodeField:        http.StatusBadRequest,
	}
	ErrInteractionRequired = &RFC6749Error{
		DescriptionField: "The Authorization Server requires End-User interaction of some form to proceed.",
		ErrorField:       errInteractionRequired,
		CodeField:        http.StatusBadRequest,
	}
	ErrConsentRequired = &RFC6749Error{
		DescriptionField: "The Authorization Server requires End-User consent.",
		ErrorField:       errConsentRequired,
		CodeField:        http.StatusBadRequest,
	}
	ErrRequestNotSupported = &RFC6749Error{
		DescriptionField: "The OP does not support use of the request parameter.",
		ErrorField:       errRequestNotSupportedName,
		CodeField:        http.StatusBadRequest,
	}
	ErrRequestURINotSupported = &RFC6749Error{
		DescriptionField: "The OP does not support use of the request_uri parameter.",
		ErrorField:       errRequestURINotSupportedName,
		CodeField:        http.StatusBadRequest,
	}
	ErrRegistrationNotSupported = &RFC6749Error{
		DescriptionField: "The OP does not support use of the registration parameter.",
		ErrorField:       errRegistrationNotSupportedName,
		CodeField:        http.StatusBadRequest,
	}
	ErrInvalidRequestURI = &RFC6749Error{
		DescriptionField: "The request_uri in the Authorization Request returns an error or contains invalid data.",
		ErrorField:       errInvalidRequestURI,
		CodeField:        http.StatusBadRequest,
	}
	ErrInvalidRequestObject = &RFC6749Error{
		DescriptionField: "The request parameter contains an invalid Request Object.",
		ErrorField:       errInvalidRequestObject,
		CodeField:        http.StatusBadRequest,
	}
	ErrJTIKnown = &RFC6749Error{
		DescriptionField: "The jti was already used.",
		ErrorField:       errJTIKnownName,
		CodeField:        http.StatusBadRequest,
	}
	ErrAuthorizationPending = &RFC6749Error{
		DescriptionField: "The authorization request is still pending as the end user hasn't yet completed the user-interaction steps.",
		ErrorField:       errAuthorizationPending,
		CodeField:        http.StatusBadRequest,
	}
	ErrSlowDown = &RFC6749Error{
		DescriptionField: "The authorization request was rate-limited to prevent system overload.",
		HintField:        "Ensure that you don't call the token endpoint sooner than the polling interval",
		ErrorField:       errSlowDown,
		CodeField:        http.StatusBadRequest,
	}
	ErrDeviceExpiredToken = &RFC6749Error{
		DescriptionField: "The device_code has expired, and the device authorization session has concluded.",
		ErrorField:       errDeviceExpiredToken,
		CodeField:        http.StatusBadRequest,
	}
)
View Source
var DefaultFormPostTemplate = template.Must(template.New("form_post").Parse(`<html>
   <head>
      <title>Submit This Form</title>
   </head>
   <body onload="javascript:document.forms[0].submit()">
      <form method="post" action="{{ .RedirURL }}">
         {{ range $key,$value := .Parameters }}
            {{ range $parameter:= $value}}
		      <input type="hidden" name="{{$key}}" value="{{$parameter}}"/>
            {{end}}
         {{ end }}
      </form>
   </body>
</html>`))

Functions

func AccessTokenFromRequest

func AccessTokenFromRequest(req *http.Request) string

func AddLocalizerToErr

func AddLocalizerToErr(catalog i18n.MessageCatalog, err error, requester Requester) error

AddLocalizerToErr augments the error object with the localizer based on the language set in the requester object. This is primarily required for response writers like introspection that do not take in the requester in the Write* function that produces the translated message. See - WriteIntrospectionError, for example.

func AddLocalizerToErrWithLang

func AddLocalizerToErrWithLang(catalog i18n.MessageCatalog, lang language.Tag, err error) error

AddLocalizerToErrWithLang augments the error object with the localizer based on the language passed in. This is primarily required for response writers like introspection that do not take in the requester in the Write* function that produces the translated message. See - WriteIntrospectionError, for example.

func DefaultAudienceMatchingStrategy

func DefaultAudienceMatchingStrategy(haystack []string, needle []string) error

func EscapeJSONString

func EscapeJSONString(str string) string

EscapeJSONString does a poor man's JSON encoding. Useful when we do not want to use full JSON encoding because we just had an error doing the JSON encoding. The characters that MUST be escaped: quotation mark, reverse solidus, and the control characters (U+0000 through U+001F). See: https://tools.ietf.org/html/std90#section-7

func ExactAudienceMatchingStrategy

func ExactAudienceMatchingStrategy(haystack []string, needle []string) error

ExactAudienceMatchingStrategy does not assume that audiences are URIs, but compares strings as-is and does matching with exact string comparison. It requires that all strings in "needle" are present in "haystack". Use this strategy when your audience values are not URIs (e.g., you use client IDs for audience and they are UUIDs or random strings).

func ExactScopeStrategy

func ExactScopeStrategy(haystack []string, needle string) bool

func GetEffectiveLifespan

func GetEffectiveLifespan(c Client, gt GrantType, tt TokenType, fallback time.Duration) time.Duration

GetEffectiveLifespan either maps GrantType x TokenType to the client's configured lifespan, or returns the fallback value.

func GetPostFormHTMLTemplate

func GetPostFormHTMLTemplate(ctx context.Context, f *Fosite) *template.Template

func GetResourceIndicator

func GetResourceIndicator(form url.Values) (string, error)

GetResourceIndicator extracts a single RFC 8707 resource value from a form.

func HierarchicScopeStrategy

func HierarchicScopeStrategy(haystack []string, needle string) bool

func IsLocalhost

func IsLocalhost(redirectURI *url.URL) bool

func IsRedirectURISecure

func IsRedirectURISecure(ctx context.Context, redirectURI *url.URL) bool

func IsRedirectURISecureStrict

func IsRedirectURISecureStrict(ctx context.Context, redirectURI *url.URL) bool

IsRedirectURISecureStrict is stricter than IsRedirectURISecure and it does not allow custom-scheme URLs because they can be hijacked for native apps. Use claimed HTTPS redirects instead. See discussion in https://github.com/ory/fosite/pull/489.

func IsValidRedirectURI

func IsValidRedirectURI(redirectURI *url.URL) bool

IsValidRedirectURI validates a redirect_uri as specified in:

* https://tools.ietf.org/html/rfc6749#section-3.1.2

func IsValidResourceIndicatorURI

func IsValidResourceIndicatorURI(raw string) bool

IsValidResourceIndicatorURI reports whether raw is an absolute RFC 8707 resource URI without a fragment component.

func IsValidScopeToken

func IsValidScopeToken(scope string) bool

IsValidScopeToken reports whether scope is a valid RFC 6749 scope-token.

func JKWKSFetcherWithDefaultTTL

func JKWKSFetcherWithDefaultTTL(ttl time.Duration) func(*DefaultJWKSFetcherStrategy)

JKWKSFetcherWithDefaultTTL sets the default TTL for the cache.

func JWKSFetcherWithCache

func JWKSFetcherWithCache(cache *ristretto.Cache[string, *jose.JSONWebKeySet]) func(*DefaultJWKSFetcherStrategy)

JWKSFetcherWithCache sets the cache to use.

func JWKSFetcherWithHTTPClient

func JWKSFetcherWithHTTPClient(client *retryablehttp.Client) func(*DefaultJWKSFetcherStrategy)

JWKSFetcherWithHTTPClient sets the HTTP client to use.

func JWKSFetcherWithHTTPClientSource

func JWKSFetcherWithHTTPClientSource(clientSourceFunc func(ctx context.Context) *retryablehttp.Client) func(*DefaultJWKSFetcherStrategy)

JWKSFetcherWithHTTPClientSource sets the HTTP client source function to use.

func LooksLikeCIMDURL

func LooksLikeCIMDURL(clientID string) bool

LooksLikeCIMDURL reports whether clientID is a candidate Client Identifier URL.

A URL-shaped identifier is not necessarily backed by a Client ID Metadata Document. Callers must give pre-registered clients precedence before attempting metadata discovery.

func MatchRedirectURIWithClientRedirectURIs

func MatchRedirectURIWithClientRedirectURIs(rawurl string, client Client) (*url.URL, error)

MatchRedirectURIWithClientRedirectURIs if the given uri is a registered redirect uri. Does not perform uri validation.

Considered specifications

  • https://tools.ietf.org/html/rfc6749#section-3.1.2.3 If multiple redirection URIs have been registered, if only part of the redirection URI has been registered, or if no redirection URI has been registered, the client MUST include a redirection URI with the authorization request using the "redirect_uri" request parameter.

    When a redirection URI is included in an authorization request, the authorization server MUST compare and match the value received against at least one of the registered redirection URIs (or URI components) as defined in [RFC3986] Section 6, if any redirection URIs were registered. If the client registration included the full redirection URI, the authorization server MUST compare the two URIs using simple string comparison as defined in [RFC3986] Section 6.2.1.

* https://tools.ietf.org/html/rfc6819#section-4.4.1.7

  • The authorization server may also enforce the usage and validation of pre-registered redirect URIs (see Section 5.2.3.5). This will allow for early recognition of authorization "code" disclosure to counterfeit clients.
  • The attacker will need to use another redirect URI for its authorization process rather than the target web site because it needs to intercept the flow. So, if the authorization server associates the authorization "code" with the redirect URI of a particular end-user authorization and validates this redirect URI with the redirect URI passed to the token's endpoint, such an attack is detected (see Section 5.2.4.5).

func NewContext

func NewContext() context.Context

func ParseCIMDURL

func ParseCIMDURL(clientID string) (*url.URL, error)

ParseCIMDURL parses and validates a Client Identifier URL.

func RemoveEmpty

func RemoveEmpty(args []string) (ret []string)

func StringInSlice

func StringInSlice(needle string, haystack []string) bool

StringInSlice returns true if needle exists in haystack

func URLSetFragment deprecated

func URLSetFragment(source *url.URL, fragment url.Values)

Deprecated: Do not use.

func ValidateCIMDURL

func ValidateCIMDURL(u *url.URL) error

ValidateCIMDURL enforces the Client Identifier URL requirements from draft-ietf-oauth-client-id-metadata-document-02 section 3.

func ValidateResourceIndicator

func ValidateResourceIndicator(form url.Values) (string, error)

ValidateResourceIndicator validates and returns the single RFC 8707 resource value from a form.

func WildcardScopeStrategy

func WildcardScopeStrategy(matchers []string, needle string) bool

func WriteAuthorizeFormPostResponse

func WriteAuthorizeFormPostResponse(redirectURL string, parameters url.Values, template *template.Template, rw io.Writer)

Types

type AccessRequest

type AccessRequest struct {
	GrantTypes       Arguments `json:"grantTypes" gorethink:"grantTypes"`
	HandledGrantType Arguments `json:"handledGrantType" gorethink:"handledGrantType"`

	Request
}

func NewAccessRequest

func NewAccessRequest(session Session) *AccessRequest

func (*AccessRequest) GetGrantTypes

func (a *AccessRequest) GetGrantTypes() Arguments

type AccessRequester

type AccessRequester interface {
	// GetGrantTypes returns the requests grant type.
	GetGrantTypes() (grantTypes Arguments)

	Requester
}

AccessRequester is a token endpoint's request context.

type AccessResponder

type AccessResponder interface {
	// SetExtra sets a key value pair for the access response.
	SetExtra(key string, value interface{})

	// GetExtra returns a key's value.
	GetExtra(key string) interface{}

	SetExpiresIn(time.Duration)

	SetScopes(scopes Arguments)

	// SetAccessToken sets the responses mandatory access token.
	SetAccessToken(token string)

	// SetTokenType set's the responses mandatory token type
	SetTokenType(tokenType string)

	// GetAccessToken returns the responses access token.
	GetAccessToken() (token string)

	// GetTokenType returns the responses token type.
	GetTokenType() (token string)

	// ToMap converts the response to a map.
	ToMap() map[string]interface{}
}

AccessResponder is a token endpoint's response.

type AccessResponse

type AccessResponse struct {
	Extra       map[string]interface{}
	AccessToken string
	TokenType   string
}

func NewAccessResponse

func NewAccessResponse() *AccessResponse

func (*AccessResponse) GetAccessToken

func (a *AccessResponse) GetAccessToken() string

func (*AccessResponse) GetExtra

func (a *AccessResponse) GetExtra(key string) interface{}

func (*AccessResponse) GetTokenType

func (a *AccessResponse) GetTokenType() string

func (*AccessResponse) SetAccessToken

func (a *AccessResponse) SetAccessToken(token string)

func (*AccessResponse) SetExpiresIn

func (a *AccessResponse) SetExpiresIn(expiresIn time.Duration)

func (*AccessResponse) SetExtra

func (a *AccessResponse) SetExtra(key string, value interface{})

func (*AccessResponse) SetScopes

func (a *AccessResponse) SetScopes(scopes Arguments)

func (*AccessResponse) SetTokenType

func (a *AccessResponse) SetTokenType(name string)

func (*AccessResponse) ToMap

func (a *AccessResponse) ToMap() map[string]interface{}

type AccessTokenIssuerProvider

type AccessTokenIssuerProvider interface {
	// GetAccessTokenIssuer returns the access token issuer.
	GetAccessTokenIssuer(ctx context.Context) string
}

AccessTokenIssuerProvider returns the provider for configuring the JWT issuer.

type AccessTokenLifespanProvider

type AccessTokenLifespanProvider interface {
	// GetAccessTokenLifespan returns the access token lifespan.
	GetAccessTokenLifespan(ctx context.Context) time.Duration
}

AccessTokenLifespanProvider returns the provider for configuring the access token lifespan.

type AllowedPromptValuesProvider

type AllowedPromptValuesProvider interface {
	// GetAllowedPromptValues returns the allowed prompt values.
	GetAllowedPromptValues(ctx context.Context) int
}

AllowedPromptValuesProvider returns the provider for configuring the allowed prompt values.

type AllowedPromptsProvider

type AllowedPromptsProvider interface {
	// GetAllowedPrompts returns the allowed prompts.
	GetAllowedPrompts(ctx context.Context) []string
}

AllowedPromptsProvider returns the provider for configuring the allowed prompts.

type Arguments

type Arguments []string

func FilterRequestedScopes

func FilterRequestedScopes(strategy ScopeStrategy, client Client, requested Arguments, ignoreUnknown bool) (Arguments, error)

FilterRequestedScopes validates the requested scopes against the client's registered scopes using the given strategy. If ignoreUnknown is true, scope values the client is not allowed to request are removed from the returned list, as recommended by OpenID Connect Core 1.0 Section 3.1.2.1 for scope values that are not understood; otherwise the first such scope value fails with ErrInvalidScope.

func (Arguments) Exact deprecated

func (r Arguments) Exact(name string) bool

Deprecated: Use ExactOne, Matches or MatchesExact

func (Arguments) ExactOne

func (r Arguments) ExactOne(name string) bool

ExactOne checks, by string case, that a single argument equals the provided string.

func (Arguments) Has

func (r Arguments) Has(items ...string) bool

Has checks, in a case-insensitive manner, that all of the items provided exists in arguments.

func (Arguments) HasOneOf

func (r Arguments) HasOneOf(items ...string) bool

HasOneOf checks, in a case-insensitive manner, that one of the items provided exists in arguments.

func (Arguments) Matches

func (r Arguments) Matches(items ...string) bool

Matches performs an case-insensitive, out-of-order check that the items provided exist and equal all of the args in arguments. Note:

  • Providing a list that includes duplicate string-case items will return not matched.

func (Arguments) MatchesExact

func (r Arguments) MatchesExact(items ...string) bool

MatchesExact checks, by order and string case, that the items provided equal those in arguments.

type AudienceMatchingStrategy

type AudienceMatchingStrategy func(haystack []string, needle []string) error

type AudienceStrategyProvider

type AudienceStrategyProvider interface {
	// GetAudienceStrategy returns the audience strategy.
	GetAudienceStrategy(ctx context.Context) AudienceMatchingStrategy
}

AudienceStrategyProvider returns the provider for configuring the audience strategy.

type AuthorizationResponseIssuerProvider

type AuthorizationResponseIssuerProvider interface {
	// GetAuthorizationResponseIssuer returns the issuer included in authorization responses.
	GetAuthorizationResponseIssuer(ctx context.Context) string
}

AuthorizationResponseIssuerProvider returns the provider for configuring the RFC 9207 issuer in authorization responses.

type AuthorizeCodeLifespanProvider

type AuthorizeCodeLifespanProvider interface {
	// GetAuthorizeCodeLifespan returns the authorization code lifespan.
	GetAuthorizeCodeLifespan(ctx context.Context) time.Duration
}

AuthorizeCodeLifespanProvider returns the provider for configuring the authorization code lifespan.

type AuthorizeEndpointHandler

type AuthorizeEndpointHandler interface {
	// HandleAuthorizeRequest handles an authorize endpoint request. To extend the handler's capabilities, the http request
	// is passed along, if further information retrieval is required. If the handler feels that he is not responsible for
	// the authorize request, he must return nil and NOT modify session nor responder neither requester.
	//
	// The following spec is a good example of what HandleAuthorizeRequest should do.
	// * https://tools.ietf.org/html/rfc6749#section-3.1.1
	//   response_type REQUIRED.
	//   The value MUST be one of "code" for requesting an
	//   authorization code as described by Section 4.1.1, "token" for
	//   requesting an access token (implicit grant) as described by
	//   Section 4.2.1, or a registered extension value as described by Section 8.4.
	HandleAuthorizeEndpointRequest(ctx context.Context, requester AuthorizeRequester, responder AuthorizeResponder) error
}

type AuthorizeEndpointHandlers

type AuthorizeEndpointHandlers []AuthorizeEndpointHandler

AuthorizeEndpointHandlers is a list of AuthorizeEndpointHandler

func (*AuthorizeEndpointHandlers) Append

Append adds an AuthorizeEndpointHandler to this list. Ignores duplicates based on reflect.TypeOf.

type AuthorizeEndpointHandlersProvider

type AuthorizeEndpointHandlersProvider interface {
	// GetAuthorizeEndpointHandlers returns the authorize endpoint handlers.
	GetAuthorizeEndpointHandlers(ctx context.Context) AuthorizeEndpointHandlers
}

AuthorizeEndpointHandlersProvider returns the provider for configuring the authorize endpoint handlers.

type AuthorizeRequest

type AuthorizeRequest struct {
	ResponseTypes        Arguments          `json:"responseTypes" gorethink:"responseTypes"`
	RedirectURI          *url.URL           `json:"redirectUri" gorethink:"redirectUri"`
	State                string             `json:"state" gorethink:"state"`
	HandledResponseTypes Arguments          `json:"handledResponseTypes" gorethink:"handledResponseTypes"`
	ResponseMode         ResponseModeType   `json:"ResponseModes" gorethink:"ResponseModes"`
	DefaultResponseMode  ResponseModeType   `json:"DefaultResponseMode" gorethink:"DefaultResponseMode"`
	RedirectURIMatcher   RedirectURIMatcher `json:"-" gorethink:"-"`

	Request
}

AuthorizeRequest is an implementation of AuthorizeRequester

func NewAuthorizeRequest

func NewAuthorizeRequest() *AuthorizeRequest

func (*AuthorizeRequest) DidHandleAllResponseTypes

func (d *AuthorizeRequest) DidHandleAllResponseTypes() bool

func (*AuthorizeRequest) GetDefaultResponseMode

func (d *AuthorizeRequest) GetDefaultResponseMode() ResponseModeType

func (*AuthorizeRequest) GetRedirectURI

func (d *AuthorizeRequest) GetRedirectURI() *url.URL

func (*AuthorizeRequest) GetResponseMode

func (d *AuthorizeRequest) GetResponseMode() ResponseModeType

func (*AuthorizeRequest) GetResponseTypes

func (d *AuthorizeRequest) GetResponseTypes() Arguments

func (*AuthorizeRequest) GetState

func (d *AuthorizeRequest) GetState() string

func (*AuthorizeRequest) IsRedirectURIValid

func (d *AuthorizeRequest) IsRedirectURIValid() bool

func (*AuthorizeRequest) SetDefaultResponseMode

func (d *AuthorizeRequest) SetDefaultResponseMode(defaultResponseMode ResponseModeType)

func (*AuthorizeRequest) SetResponseTypeHandled

func (d *AuthorizeRequest) SetResponseTypeHandled(name string)

type AuthorizeRequester

type AuthorizeRequester interface {
	// GetResponseTypes returns the requested response types
	GetResponseTypes() (responseTypes Arguments)

	// SetResponseTypeHandled marks a response_type (e.g. token or code) as handled indicating that the response type
	// is supported.
	SetResponseTypeHandled(responseType string)

	// DidHandleAllResponseTypes returns if all requested response types have been handled correctly
	DidHandleAllResponseTypes() (didHandle bool)

	// GetRedirectURI returns the requested redirect URI
	GetRedirectURI() (redirectURL *url.URL)

	// IsRedirectURIValid returns false if the redirect is not rfc-conform (i.e. missing client, not on white list,
	// or malformed)
	IsRedirectURIValid() (isValid bool)

	// GetState returns the request's state.
	GetState() (state string)

	// GetResponseMode returns response_mode of the authorization request
	GetResponseMode() ResponseModeType

	// SetDefaultResponseMode sets default response mode for a response type in a flow
	SetDefaultResponseMode(responseMode ResponseModeType)

	// GetDefaultResponseMode gets default response mode for a response type in a flow
	GetDefaultResponseMode() ResponseModeType

	Requester
}

AuthorizeRequester is an authorize endpoint's request context.

type AuthorizeResponder

type AuthorizeResponder interface {
	// GetCode returns the response's authorize code if set.
	GetCode() string

	// GetHeader returns the response's header
	GetHeader() (header http.Header)

	// AddHeader adds a header key value pair to the response
	AddHeader(key, value string)

	// GetParameters returns the response's parameters
	GetParameters() (query url.Values)

	// AddParameter adds key value pair to the response
	AddParameter(key, value string)
}

AuthorizeResponder is an authorization endpoint's response.

type AuthorizeResponse

type AuthorizeResponse struct {
	Header     http.Header
	Parameters url.Values
	// contains filtered or unexported fields
}

AuthorizeResponse is an implementation of AuthorizeResponder

func NewAuthorizeResponse

func NewAuthorizeResponse() *AuthorizeResponse

func (*AuthorizeResponse) AddHeader

func (a *AuthorizeResponse) AddHeader(key, value string)

func (*AuthorizeResponse) AddParameter

func (a *AuthorizeResponse) AddParameter(key, value string)

func (*AuthorizeResponse) GetCode

func (a *AuthorizeResponse) GetCode() string

func (*AuthorizeResponse) GetHeader

func (a *AuthorizeResponse) GetHeader() http.Header

func (*AuthorizeResponse) GetParameters

func (a *AuthorizeResponse) GetParameters() url.Values

type BCrypt

type BCrypt struct {
	Config interface {
		BCryptCostProvider
	}
}

BCrypt implements the Hasher interface by using BCrypt.

func (*BCrypt) Compare

func (b *BCrypt) Compare(ctx context.Context, hash, data []byte) error

func (*BCrypt) Hash

func (b *BCrypt) Hash(ctx context.Context, data []byte) ([]byte, error)

type BCryptCostProvider

type BCryptCostProvider interface {
	// GetBCryptCost returns the BCrypt  hash cost.
	GetBCryptCost(ctx context.Context) int
}

BCryptCostProvider returns the provider for configuring the BCrypt hash cost.

type CIMDCachePolicy

type CIMDCachePolicy struct {
	TTL   time.Duration
	Store bool
}

CIMDCachePolicy contains the response cache semantics needed by the resolver.

type CIMDCachedClient

type CIMDCachedClient struct {
	Client    Client
	ExpiresAt time.Time
}

CIMDCachedClient contains a materialized metadata client and its HTTP cache policy.

type CIMDClient

type CIMDClient struct {
	*DefaultOpenIDConnectClient
	Document *ClientMetadataDocument
	// contains filtered or unexported fields
}

CIMDClient is the standard Fosite projection of a Client ID Metadata Document.

func NewCIMDClient

func NewCIMDClient(doc *ClientMetadataDocument) (*CIMDClient, error)

NewCIMDClient projects protocol-defined client metadata into Fosite's standard client interfaces.

Authorization-server policy may wrap or transform the returned client to restrict grants, scopes, audiences, or other locally controlled behavior.

func (*CIMDClient) FetchCIMDReferencedURL

func (c *CIMDClient) FetchCIMDReferencedURL(ctx context.Context, rawURL string) (*http.Response, error)

FetchCIMDReferencedURL dereferences a URL taken from the client's metadata document through the SSRF-guarded transport, after re-validating it against the special-use ranges.

func (*CIMDClient) GetClientMetadataDocument

func (c *CIMDClient) GetClientMetadataDocument() *ClientMetadataDocument

GetClientMetadataDocument returns the metadata used to materialize the client.

func (*CIMDClient) ResolveCIMDJSONWebKeys

func (c *CIMDClient) ResolveCIMDJSONWebKeys(ctx context.Context, ignoreCache bool) (*jose.JSONWebKeySet, error)

ResolveCIMDJSONWebKeys resolves the client's remote keys through the SSRF-guarded CIMD transport.

type CIMDClientCache

type CIMDClientCache interface {
	LoadCIMDClient(context.Context, string) (CIMDCachedClient, bool, error)
	StoreCIMDClient(context.Context, Client, *ClientMetadataDocument, time.Time) (Client, error)
}

CIMDClientCache persists materialized metadata clients while their metadata is fresh.

type CIMDClientCacheEvictor

type CIMDClientCacheEvictor interface {
	EvictCIMDClient(context.Context, string) error
}

CIMDClientCacheEvictor removes a cached metadata client when a response forbids storage.

type CIMDClientMaterializer

type CIMDClientMaterializer interface {
	MaterializeCIMDClient(context.Context, *ClientMetadataDocument) (Client, error)
}

CIMDClientMaterializer projects a validated metadata document into a provider client.

type CIMDClientMaterializerFunc

type CIMDClientMaterializerFunc func(context.Context, *ClientMetadataDocument) (Client, error)

CIMDClientMaterializerFunc implements CIMDClientMaterializer for a function.

func (CIMDClientMaterializerFunc) MaterializeCIMDClient

func (f CIMDClientMaterializerFunc) MaterializeCIMDClient(ctx context.Context, document *ClientMetadataDocument) (Client, error)

MaterializeCIMDClient calls f.

type CIMDClientPolicy

type CIMDClientPolicy interface {
	AllowCIMDClient(context.Context, string) error
	ValidateCIMDClient(context.Context, *ClientMetadataDocument) error
}

CIMDClientPolicy applies authorization-server policy before and after discovery.

type CIMDClientPolicyFuncs

type CIMDClientPolicyFuncs struct {
	Allow    func(context.Context, string) error
	Validate func(context.Context, *ClientMetadataDocument) error
}

CIMDClientPolicyFuncs implements CIMDClientPolicy with optional functions.

func (CIMDClientPolicyFuncs) AllowCIMDClient

func (p CIMDClientPolicyFuncs) AllowCIMDClient(ctx context.Context, clientID string) error

AllowCIMDClient applies the identifier policy when configured.

func (CIMDClientPolicyFuncs) ValidateCIMDClient

func (p CIMDClientPolicyFuncs) ValidateCIMDClient(ctx context.Context, document *ClientMetadataDocument) error

ValidateCIMDClient applies the document policy when configured.

type CIMDFetcher

type CIMDFetcher interface {
	// Fetch retrieves the metadata document at clientID (an https URL), validates
	// it, and returns a parsed document along with the response's cache policy.
	Fetch(ctx context.Context, clientID string) (doc *ClientMetadataDocument, cachePolicy CIMDCachePolicy, err error)
}

CIMDFetcher retrieves and validates the Client ID Metadata Document located at a client_id URL.

type CIMDFetcherOption

type CIMDFetcherOption func(*DefaultCIMDFetcher)

CIMDFetcherOption configures a DefaultCIMDFetcher.

func WithCIMDAllowPrivateIPs

func WithCIMDAllowPrivateIPs(allow bool) CIMDFetcherOption

WithCIMDAllowPrivateIPs disables SSRF protection, allowing documents to be fetched from private, loopback, or link-local addresses.

func WithCIMDCacheTTLBounds

func WithCIMDCacheTTLBounds(maxTTL, defaultTTL time.Duration) CIMDFetcherOption

WithCIMDCacheTTLBounds sets the maximum and default cache lifetimes without extending an explicit origin lifetime.

func WithCIMDExtraPrivateRanges

func WithCIMDExtraPrivateRanges(ranges []*net.IPNet) CIMDFetcherOption

WithCIMDExtraPrivateRanges adds CIDR ranges that are treated as private.

func WithCIMDMaxSize

func WithCIMDMaxSize(n int64) CIMDFetcherOption

WithCIMDMaxSize sets the maximum accepted response size in bytes, applied to the body and to the response headers separately.

func WithCIMDResolver

func WithCIMDResolver(r *net.Resolver) CIMDFetcherOption

WithCIMDResolver sets the resolver used for resolution-time SSRF checks.

func WithCIMDTransport

func WithCIMDTransport(rt http.RoundTripper) CIMDFetcherOption

WithCIMDTransport sets the base transport used by the fetcher.

A custom non-*http.Transport is a trusted escape hatch for tests and controlled integrations because Fosite cannot install its dial-time SSRF guard around it.

func WithCIMDTransportDecorator

func WithCIMDTransportDecorator(decorate func(http.RoundTripper) http.RoundTripper) CIMDFetcherOption

WithCIMDTransportDecorator wraps the guarded transport without hiding its dialer from the fetcher.

This is the preferred option for tracing, metrics, and other middleware, and decorators must call the supplied transport rather than replace it.

func WithCIMDUserAgent

func WithCIMDUserAgent(ua string) CIMDFetcherOption

WithCIMDUserAgent sets the User-Agent header sent when fetching.

type CIMDJWKSResolver

type CIMDJWKSResolver interface {
	ResolveCIMDJSONWebKeys(context.Context, bool) (*jose.JSONWebKeySet, error)
}

CIMDJWKSResolver resolves keys referenced by a metadata client through its guarded fetcher.

type CIMDResolver

type CIMDResolver struct {
	Fetcher                  CIMDFetcher
	Cache                    CIMDClientCache
	Materializer             CIMDClientMaterializer
	Policy                   CIMDClientPolicy
	Now                      func() time.Time
	MaxConcurrentDiscoveries int
	// contains filtered or unexported fields
}

CIMDResolver resolves unregistered Client Identifier URLs while preserving pre-registered-client precedence.

func (*CIMDResolver) RefreshClient

func (r *CIMDResolver) RefreshClient(ctx context.Context, clientID string) (Client, error)

RefreshClient re-fetches a previously associated metadata client regardless of its freshness.

func (*CIMDResolver) ResolveClient

func (r *CIMDResolver) ResolveClient(ctx context.Context, clientID string, next ClientLookupFunc) (Client, error)

ResolveClient returns a fresh cached metadata client, a pre-registered client, or a newly discovered metadata client.

type CIMDSecureFetcher

type CIMDSecureFetcher interface {
	FetchCIMDReferencedURL(ctx context.Context, rawURL string) (*http.Response, error)
}

CIMDSecureFetcher is implemented by clients whose document-supplied URLs must be dereferenced through the SSRF-guarded transport rather than the authorization server's general HTTP client.

type CIMDSecureHTTPClientProvider

type CIMDSecureHTTPClientProvider interface {
	ValidateFetchURL(context.Context, string) error
	CIMDHTTPClient() *http.Client
}

CIMDSecureHTTPClientProvider exposes the guarded client for fetching URLs referenced by a metadata document.

type Client

type Client interface {
	// GetID returns the client ID.
	GetID() string

	// GetHashedSecret returns the hashed secret as it is stored in the store.
	GetHashedSecret() []byte

	// GetRedirectURIs returns the client's allowed redirect URIs.
	GetRedirectURIs() []string

	// GetGrantTypes returns the client's allowed grant types.
	GetGrantTypes() Arguments

	// GetResponseTypes returns the client's allowed response types.
	// All allowed combinations of response types have to be listed, each combination having
	// response types of the combination separated by a space.
	GetResponseTypes() Arguments

	// GetScopes returns the scopes this client is allowed to request.
	GetScopes() Arguments

	// IsPublic returns true, if this client is marked as public.
	IsPublic() bool

	// GetAudience returns the allowed audience(s) for this client.
	GetAudience() Arguments
}

Client represents a client or an app.

type ClientAuthenticationStrategy

type ClientAuthenticationStrategy func(context.Context, *http.Request, url.Values) (Client, error)

ClientAuthenticationStrategy provides a method signature for authenticating a client request

type ClientAuthenticationStrategyProvider

type ClientAuthenticationStrategyProvider interface {
	// GetClientAuthenticationStrategy returns the client authentication strategy.
	GetClientAuthenticationStrategy(ctx context.Context) ClientAuthenticationStrategy
}

ClientAuthenticationStrategyProvider returns the provider for configuring the client authentication strategy.

type ClientLifespanConfig

type ClientLifespanConfig struct {
	AuthorizationCodeGrantAccessTokenLifespan  *time.Duration `json:"authorization_code_grant_access_token_lifespan"`
	AuthorizationCodeGrantIDTokenLifespan      *time.Duration `json:"authorization_code_grant_id_token_lifespan"`
	AuthorizationCodeGrantRefreshTokenLifespan *time.Duration `json:"authorization_code_grant_refresh_token_lifespan"`
	ClientCredentialsGrantAccessTokenLifespan  *time.Duration `json:"client_credentials_grant_access_token_lifespan"`
	ImplicitGrantAccessTokenLifespan           *time.Duration `json:"implicit_grant_access_token_lifespan"`
	ImplicitGrantIDTokenLifespan               *time.Duration `json:"implicit_grant_id_token_lifespan"`
	JwtBearerGrantAccessTokenLifespan          *time.Duration `json:"jwt_bearer_grant_access_token_lifespan"`
	PasswordGrantAccessTokenLifespan           *time.Duration `json:"password_grant_access_token_lifespan"`
	PasswordGrantRefreshTokenLifespan          *time.Duration `json:"password_grant_refresh_token_lifespan"`
	RefreshTokenGrantIDTokenLifespan           *time.Duration `json:"refresh_token_grant_id_token_lifespan"`
	RefreshTokenGrantAccessTokenLifespan       *time.Duration `json:"refresh_token_grant_access_token_lifespan"`
	RefreshTokenGrantRefreshTokenLifespan      *time.Duration `json:"refresh_token_grant_refresh_token_lifespan"`
}

ClientLifespanConfig holds default lifespan configuration for the different token types that may be issued for the client. This configuration takes precedence over fosite's instance-wide default lifespan, but it may be overridden by a session's expires_at claim.

The OIDC Hybrid grant type inherits token lifespan configuration from the implicit grant.

type ClientLookupFunc

type ClientLookupFunc func(context.Context, string) (Client, error)

ClientLookupFunc resolves a client from its identifier.

type ClientManager

type ClientManager interface {
	// GetClient loads the client by its ID or returns an error
	// if the client does not exist or another error occurred.
	GetClient(ctx context.Context, id string) (Client, error)
	// ClientAssertionJWTValid returns an error if the JTI is
	// known or the DB check failed and nil if the JTI is not known.
	ClientAssertionJWTValid(ctx context.Context, jti string) error
	// SetClientAssertionJWT marks a JTI as known for the given
	// expiry time. Before inserting the new JTI, it will clean
	// up any existing JTIs that have expired as those tokens can
	// not be replayed due to the expiry.
	SetClientAssertionJWT(ctx context.Context, jti string, exp time.Time) error
}

ClientManager defines the (persistent) manager interface for clients.

type ClientMetadataDocument

type ClientMetadataDocument struct {
	ClientID                      string                     `json:"client_id"`
	RedirectURIs                  []string                   `json:"redirect_uris"`
	TokenEndpointAuthMethod       string                     `json:"token_endpoint_auth_method"`
	GrantTypes                    []string                   `json:"grant_types"`
	ResponseTypes                 []string                   `json:"response_types"`
	ClientName                    string                     `json:"client_name"`
	ClientURI                     string                     `json:"client_uri"`
	LogoURI                       string                     `json:"logo_uri"`
	Scope                         string                     `json:"scope"`
	Contacts                      []string                   `json:"contacts"`
	TOSURI                        string                     `json:"tos_uri"`
	PolicyURI                     string                     `json:"policy_uri"`
	JWKSURI                       string                     `json:"jwks_uri"`
	JWKS                          *jose.JSONWebKeySet        `json:"jwks"`
	SoftwareID                    string                     `json:"software_id"`
	SoftwareVersion               string                     `json:"software_version"`
	SoftwareStatement             string                     `json:"software_statement"`
	RequestURIs                   []string                   `json:"request_uris"`
	RequestObjectSigningAlgorithm string                     `json:"request_object_signing_alg"`
	TokenEndpointAuthSigningAlg   string                     `json:"token_endpoint_auth_signing_alg"`
	PostLogoutRedirectURIs        []string                   `json:"post_logout_redirect_uris"`
	AdditionalMetadata            map[string]json.RawMessage `json:"-"`

	// Presence of these values is forbidden by the CIMD credential restrictions.
	ClientSecret          *string `json:"client_secret"`
	ClientSecretExpiresAt *int64  `json:"client_secret_expires_at"`
}

ClientMetadataDocument contains registered OAuth client metadata published at a Client Identifier URL.

AdditionalMetadata preserves registered extensions and future metadata members that this version of Fosite does not interpret.

func (*ClientMetadataDocument) UnmarshalJSON

func (d *ClientMetadataDocument) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes known metadata and retains unrecognized members for provider policy and change detection.

func (*ClientMetadataDocument) Validate

func (d *ClientMetadataDocument) Validate(clientID string) error

Validate checks the protocol-level CIMD invariants against the URL used to retrieve the document.

type ClientResolver

type ClientResolver interface {
	ResolveClient(context.Context, string, ClientLookupFunc) (Client, error)
}

ClientResolver decorates the authorization server's registered-client lookup.

type ClientResolverFunc

type ClientResolverFunc func(context.Context, string, ClientLookupFunc) (Client, error)

ClientResolverFunc implements ClientResolver for a function.

func (ClientResolverFunc) ResolveClient

func (f ClientResolverFunc) ResolveClient(ctx context.Context, clientID string, next ClientLookupFunc) (Client, error)

ResolveClient implements ClientResolver for a function.

type ClientResolverProvider

type ClientResolverProvider interface {
	GetClientResolver(context.Context) ClientResolver
}

ClientResolverProvider optionally provides a client resolver without extending Configurator.

type ClientWithCustomTokenLifespans

type ClientWithCustomTokenLifespans interface {
	// GetEffectiveLifespan either maps GrantType x TokenType to the client's configured lifespan, or returns the fallback value.
	GetEffectiveLifespan(gt GrantType, tt TokenType, fallback time.Duration) time.Duration
}

type ClientWithSecretRotation

type ClientWithSecretRotation interface {
	Client
	// GetRotatedHashes returns a slice of hashed secrets used for secrets rotation.
	GetRotatedHashes() [][]byte
}

ClientWithSecretRotation extends Client interface by a method providing a slice of rotated secrets.

type Config

type Config struct {
	// AccessTokenLifespan sets how long an access token is going to be valid. Defaults to one hour.
	AccessTokenLifespan time.Duration

	// VerifiableCredentialsNonceLifespan sets how long a verifiable credentials nonce is going to be valid. Defaults to one hour.
	VerifiableCredentialsNonceLifespan time.Duration

	// RefreshTokenLifespan sets how long a refresh token is going to be valid. Defaults to 30 days. Set to -1 for
	// refresh tokens that never expire.
	RefreshTokenLifespan time.Duration

	// AuthorizeCodeLifespan sets how long an authorize code is going to be valid. Defaults to fifteen minutes.
	AuthorizeCodeLifespan time.Duration

	// IDTokenLifespan sets the default id token lifetime. Defaults to one hour.
	IDTokenLifespan time.Duration

	// IDTokenIssuer sets the default issuer of the ID Token.
	IDTokenIssuer string

	// AuthorizationResponseIssuer sets the RFC 9207 issuer included in successful and error authorization responses. If empty, the issuer is omitted.
	AuthorizationResponseIssuer string

	// Sets how long a device user/device code pair is valid for
	DeviceAndUserCodeLifespan time.Duration

	// DeviceAuthTokenPollingInterval sets the interval that clients should check for device code grants
	DeviceAuthTokenPollingInterval time.Duration

	// DeviceVerificationURL is the URL of the device verification endpoint, this is is included with the device code request responses
	DeviceVerificationURL string

	// HashCost sets the cost of the password hashing cost. Defaults to 12.
	HashCost int

	// DisableRefreshTokenValidation sets the introspection endpoint to disable refresh token validation.
	DisableRefreshTokenValidation bool

	// SendDebugMessagesToClients if set to true, includes error debug messages in response payloads. Be aware that sensitive
	// data may be exposed, depending on your implementation of Fosite. Such sensitive data might include database error
	// codes or other information. Proceed with caution!
	SendDebugMessagesToClients bool

	// ScopeStrategy sets the scope strategy that should be supported, for example fosite.WildcardScopeStrategy.
	ScopeStrategy ScopeStrategy

	// IgnoreUnknownScopes, if set to true, causes requested scopes that are not covered by the client's registered
	// scopes to be silently dropped from authorization requests (including PAR) and device authorization requests
	// instead of failing them with an invalid_scope error, as recommended by OpenID Connect Core 1.0
	// Section 3.1.2.1 for scope values that are not understood. The effectively granted scopes are reported back
	// to the client via the "scope" response parameter (RFC 6749 Section 5.1). Note that dropping "openid" this
	// way degrades the request to a plain OAuth 2.0 request. Token endpoint grants that request scopes directly
	// (client_credentials, password, RFC 7523 jwt-bearer) and the refresh flow keep strict validation: a machine
	// client requesting a scope it was never granted is an error (RFC 6749 Section 5.2), and scopes that were
	// granted but have since been removed from the client still invalidate the refresh flow. Defaults to false.
	IgnoreUnknownScopes bool

	// SupportedRequestObjectSigningAlgorithms sets the JWS "alg" values accepted for OpenID Connect request
	// objects (the "request" and "request_uri" authorization request parameters), mirroring the
	// "request_object_signing_alg_values_supported" discovery metadata. Request objects using any other
	// algorithm are rejected with an invalid_request_object error. A client's registered
	// request_object_signing_alg is enforced in addition to this list. An empty list accepts every
	// algorithm supported by the implementation ("none" and the RS/ES/PS families).
	SupportedRequestObjectSigningAlgorithms []string

	// AudienceMatchingStrategy sets the audience matching strategy that should be supported, defaults to fosite.DefaultsAudienceMatchingStrategy.
	AudienceMatchingStrategy AudienceMatchingStrategy

	// EnforcePKCE, if set to true, requires clients to perform authorize code flows with PKCE. Defaults to false.
	EnforcePKCE bool

	// EnforcePKCEForPublicClients requires only public clients to use PKCE with the authorize code flow. Defaults to false.
	EnforcePKCEForPublicClients bool

	// EnablePKCEPlainChallengeMethod sets whether or not to allow the plain challenge method (S256 should be used whenever possible, plain is really discouraged). Defaults to false.
	EnablePKCEPlainChallengeMethod bool

	// AllowedPromptValues sets which OpenID Connect prompt values the server supports. Defaults to []string{"login", "none", "consent", "select_account"}.
	AllowedPromptValues []string

	// TokenURL is the the URL of the Authorization Server's Token Endpoint. If the authorization server is intended
	// to be compatible with the private_key_jwt client authentication method (see http://openid.net/specs/openid-connect-core-1_0.html#CodeFlowAuth),
	// this value MUST be set.
	TokenURL string

	// JWKSFetcherStrategy is responsible for fetching JSON Web Keys from remote URLs. This is required when the private_key_jwt
	// client authentication method is used. Defaults to fosite.DefaultJWKSFetcherStrategy.
	JWKSFetcherStrategy JWKSFetcherStrategy

	// TokenEntropy indicates the entropy of the random string, used as the "message" part of the HMAC token.
	// Defaults to 32.
	TokenEntropy int

	// RedirectSecureChecker is a function that returns true if the provided URL can be securely used as a redirect URL.
	RedirectSecureChecker func(context.Context, *url.URL) bool

	// RedirectURIMatcher resolves a requested redirect URI against the client's registered redirect URIs.
	// Defaults to MatchRedirectURIWithClientRedirectURIs.
	RedirectURIMatcher RedirectURIMatcher

	// RefreshTokenScopes defines which OAuth scopes will be given refresh tokens during the authorization code grant exchange. This defaults to "offline" and "offline_access". When set to an empty array, all exchanges will be given refresh tokens.
	RefreshTokenScopes []string

	// MinParameterEntropy controls the minimum size of state and nonce parameters. Defaults to fosite.MinParameterEntropy.
	MinParameterEntropy int

	// UseLegacyErrorFormat controls whether the legacy error format (with `error_debug`, `error_hint`, ...)
	// should be used or not.
	UseLegacyErrorFormat bool

	// GrantTypeJWTBearerCanSkipClientAuth indicates, if client authentication can be skipped, when using jwt as assertion.
	GrantTypeJWTBearerCanSkipClientAuth bool

	// GrantTypeJWTBearerIDOptional indicates, if jti (JWT ID) claim required or not in JWT.
	GrantTypeJWTBearerIDOptional bool

	// GrantTypeJWTBearerIssuedDateOptional indicates, if "iat" (issued at) claim required or not in JWT.
	GrantTypeJWTBearerIssuedDateOptional bool

	// GrantTypeJWTBearerOmitAssertionAudience indicates whether the audience from the assertion JWT should be
	// omitted from the resulting access token. The zero value (false) copies the assertion audience into the
	// access token; the Ory Hydra configuration default is true (omit), see driver/config.
	GrantTypeJWTBearerOmitAssertionAudience bool

	// GrantTypeJWTBearerMaxDuration sets the maximum time after JWT issued date, during which the JWT is considered valid.
	GrantTypeJWTBearerMaxDuration time.Duration

	// ClientAuthenticationStrategy indicates the Strategy to authenticate client requests
	ClientAuthenticationStrategy ClientAuthenticationStrategy

	// ClientResolver optionally resolves clients before the registered-client store lookup completes
	ClientResolver ClientResolver

	// ResponseModeHandlerExtension provides a handler for custom response modes
	ResponseModeHandlerExtension ResponseModeHandler

	// MessageCatalog is the message bundle used for i18n
	MessageCatalog i18n.MessageCatalog

	// FormPostHTMLTemplate sets html template for rendering the authorization response when the request has response_mode=form_post.
	FormPostHTMLTemplate *template.Template

	// OmitRedirectScopeParam indicates whether the "scope" parameter should be omitted from the redirect URL.
	OmitRedirectScopeParam bool

	// SanitationWhiteList is a whitelist of form values that are required by the token endpoint. These values
	// are safe for storage in a database (cleartext).
	SanitationWhiteList []string

	// JWTScopeClaimKey defines the claim key to be used to set the scope in. Valid fields are "scope" or "scp" or both.
	JWTScopeClaimKey jwt.JWTScopeFieldEnum

	// AccessTokenIssuer is the issuer to be used when generating access tokens.
	AccessTokenIssuer string

	// ClientSecretsHasher is the hasher used to hash OAuth2 Client Secrets.
	ClientSecretsHasher Hasher

	// HTTPClient is the HTTP client to use for requests.
	HTTPClient *retryablehttp.Client

	// AuthorizeEndpointHandlers is a list of handlers that are called before the authorization endpoint is served.
	AuthorizeEndpointHandlers AuthorizeEndpointHandlers

	// TokenEndpointHandlers is a list of handlers that are called before the token endpoint is served.
	TokenEndpointHandlers TokenEndpointHandlers

	// TokenIntrospectionHandlers is a list of handlers that are called before the token introspection endpoint is served.
	TokenIntrospectionHandlers TokenIntrospectionHandlers

	// RevocationHandlers is a list of handlers that are called before the revocation endpoint is served.
	RevocationHandlers RevocationHandlers

	// PushedAuthorizeEndpointHandlers is a list of handlers that are called before the PAR endpoint is served.
	PushedAuthorizeEndpointHandlers PushedAuthorizeEndpointHandlers

	// GlobalSecret is the global secret used to sign and verify signatures.
	GlobalSecret []byte

	// RotatedGlobalSecrets is a list of global secrets that are used to verify signatures.
	RotatedGlobalSecrets [][]byte

	// HMACHasher is the hasher used to generate HMAC signatures.
	HMACHasher func() hash.Hash

	// PushedAuthorizeRequestURIPrefix is the URI prefix for the PAR request_uri.
	// This is defaulted to 'urn:ietf:params:oauth:request_uri:'.
	PushedAuthorizeRequestURIPrefix string

	// PushedAuthorizeContextLifespan is the lifespan of the PAR context
	PushedAuthorizeContextLifespan time.Duration

	// DeviceEndpointHandlers is a list of handlers that are called before the device endpoint is served.
	DeviceEndpointHandlers DeviceEndpointHandlers

	// IsPushedAuthorizeEnforced enforces pushed authorization request for /authorize
	IsPushedAuthorizeEnforced bool

	// UserCodeLength defines the length of the user_code
	UserCodeLength int

	// UserCodeSymbols defines the symbols that will be used to construct the user_code
	UserCodeSymbols []rune
}

func (*Config) EnforcePushedAuthorize

func (c *Config) EnforcePushedAuthorize(ctx context.Context) bool

EnforcePushedAuthorize indicates if PAR is enforced. In this mode, a client cannot pass authorize parameters at the 'authorize' endpoint. The 'authorize' endpoint must contain the PAR request_uri.

func (*Config) GetAccessTokenIssuer

func (c *Config) GetAccessTokenIssuer(ctx context.Context) string

func (*Config) GetAccessTokenLifespan

func (c *Config) GetAccessTokenLifespan(_ context.Context) time.Duration

GetAccessTokenLifespan returns how long an access token should be valid. Defaults to one hour.

func (*Config) GetAllowedPrompts

func (c *Config) GetAllowedPrompts(_ context.Context) []string

func (*Config) GetAudienceStrategy

func (c *Config) GetAudienceStrategy(_ context.Context) AudienceMatchingStrategy

GetAudienceStrategy returns the scope strategy to be used. Defaults to glob scope strategy.

func (*Config) GetAuthorizationResponseIssuer

func (c *Config) GetAuthorizationResponseIssuer(ctx context.Context) string

func (*Config) GetAuthorizeCodeLifespan

func (c *Config) GetAuthorizeCodeLifespan(_ context.Context) time.Duration

GetAuthorizeCodeLifespan returns how long an authorize code should be valid. Defaults to one fifteen minutes.

func (*Config) GetAuthorizeEndpointHandlers

func (c *Config) GetAuthorizeEndpointHandlers(ctx context.Context) AuthorizeEndpointHandlers

func (*Config) GetBCryptCost

func (c *Config) GetBCryptCost(_ context.Context) int

GetBCryptCost returns the bcrypt cost factor. Defaults to 12.

func (*Config) GetClientAuthenticationStrategy

func (c *Config) GetClientAuthenticationStrategy(_ context.Context) ClientAuthenticationStrategy

GetClientAuthenticationStrategy returns the configured client authentication strategy. Defaults to nil. Note that on a nil strategy `fosite.Fosite` fallbacks to its default client authentication strategy `fosite.Fosite.DefaultClientAuthenticationStrategy`

func (*Config) GetClientResolver

func (c *Config) GetClientResolver(_ context.Context) ClientResolver

GetClientResolver returns the configured client resolver.

func (*Config) GetDeviceAndUserCodeLifespan

func (c *Config) GetDeviceAndUserCodeLifespan(_ context.Context) time.Duration

GetDeviceAndUserCodeLifespan returns how long the device and user codes should be valid. Defaults to 10 minutes

func (*Config) GetDeviceAuthTokenPollingInterval

func (c *Config) GetDeviceAuthTokenPollingInterval(ctx context.Context) time.Duration

GetDeviceAuthTokenPollingInterval returns configured device token endpoint polling interval

func (*Config) GetDeviceEndpointHandlers

func (c *Config) GetDeviceEndpointHandlers(ctx context.Context) DeviceEndpointHandlers

GetDeviceEndpointHandlers return the Device Endpoint Handlers

func (*Config) GetDeviceVerificationURL

func (c *Config) GetDeviceVerificationURL(ctx context.Context) string

GetDeviceVerificationURL returns the device verification URL

func (*Config) GetDisableRefreshTokenValidation

func (c *Config) GetDisableRefreshTokenValidation(_ context.Context) bool

GetDisableRefreshTokenValidation returns whether to disable the validation of the refresh token.

func (*Config) GetEnablePKCEPlainChallengeMethod

func (c *Config) GetEnablePKCEPlainChallengeMethod(ctx context.Context) bool

GetEnablePKCEPlainChallengeMethod returns whether or not to allow the plain challenge method (S256 should be used whenever possible, plain is really discouraged).

func (*Config) GetEnforcePKCE

func (c *Config) GetEnforcePKCE(ctx context.Context) bool

GetEnforcePKCE If set to true, public clients must use PKCE.

func (*Config) GetEnforcePKCEForPublicClients

func (c *Config) GetEnforcePKCEForPublicClients(ctx context.Context) bool

GetEnforcePKCEForPublicClients returns the value of EnforcePKCEForPublicClients.

func (*Config) GetFormPostHTMLTemplate

func (c *Config) GetFormPostHTMLTemplate(ctx context.Context) *template.Template

func (*Config) GetGlobalSecret

func (c *Config) GetGlobalSecret(ctx context.Context) ([]byte, error)

func (*Config) GetGrantTypeJWTBearerCanSkipClientAuth

func (c *Config) GetGrantTypeJWTBearerCanSkipClientAuth(ctx context.Context) bool

GetGrantTypeJWTBearerCanSkipClientAuth returns the GrantTypeJWTBearerCanSkipClientAuth field.

func (*Config) GetGrantTypeJWTBearerIDOptional

func (c *Config) GetGrantTypeJWTBearerIDOptional(ctx context.Context) bool

GetGrantTypeJWTBearerIDOptional returns the GrantTypeJWTBearerIDOptional field.

func (*Config) GetGrantTypeJWTBearerIssuedDateOptional

func (c *Config) GetGrantTypeJWTBearerIssuedDateOptional(ctx context.Context) bool

GetGrantTypeJWTBearerIssuedDateOptional returns the GrantTypeJWTBearerIssuedDateOptional field.

func (*Config) GetGrantTypeJWTBearerOmitAssertionAudience

func (c *Config) GetGrantTypeJWTBearerOmitAssertionAudience(ctx context.Context) bool

GetGrantTypeJWTBearerOmitAssertionAudience returns GrantTypeJWTBearerOmitAssertionAudience.

func (*Config) GetHMACHasher

func (c *Config) GetHMACHasher(ctx context.Context) func() hash.Hash

func (*Config) GetHTTPClient

func (c *Config) GetHTTPClient(ctx context.Context) *retryablehttp.Client

func (*Config) GetIDTokenIssuer

func (c *Config) GetIDTokenIssuer(ctx context.Context) string

func (*Config) GetIDTokenLifespan

func (c *Config) GetIDTokenLifespan(_ context.Context) time.Duration

GetIDTokenLifespan returns how long an id token should be valid. Defaults to one hour.

func (*Config) GetIgnoreUnknownScopes

func (c *Config) GetIgnoreUnknownScopes(_ context.Context) bool

GetIgnoreUnknownScopes returns true if requested scopes that are not covered by the client's registered scopes should be silently dropped from the request instead of failing it with an invalid_scope error. Defaults to false.

func (*Config) GetJWKSFetcherStrategy

func (c *Config) GetJWKSFetcherStrategy(_ context.Context) JWKSFetcherStrategy

GetJWKSFetcherStrategy returns the JWKSFetcherStrategy.

func (*Config) GetJWTMaxDuration

func (c *Config) GetJWTMaxDuration(_ context.Context) time.Duration

GetJWTMaxDuration specified the maximum amount of allowed `exp` time for a JWT. It compares the time with the JWT's `exp` time if the JWT time is larger, will cause the JWT to be invalid.

Defaults to a day.

func (*Config) GetJWTScopeField

func (c *Config) GetJWTScopeField(ctx context.Context) jwt.JWTScopeFieldEnum

func (*Config) GetMessageCatalog

func (c *Config) GetMessageCatalog(ctx context.Context) i18n.MessageCatalog

func (*Config) GetMinParameterEntropy

func (c *Config) GetMinParameterEntropy(_ context.Context) int

GetMinParameterEntropy returns MinParameterEntropy if set. Defaults to fosite.MinParameterEntropy.

func (*Config) GetOmitRedirectScopeParam

func (c *Config) GetOmitRedirectScopeParam(ctx context.Context) bool

func (*Config) GetPushedAuthorizeContextLifespan

func (c *Config) GetPushedAuthorizeContextLifespan(ctx context.Context) time.Duration

GetPushedAuthorizeContextLifespan is the lifespan of the short-lived PAR context.

func (*Config) GetPushedAuthorizeEndpointHandlers

func (c *Config) GetPushedAuthorizeEndpointHandlers(ctx context.Context) PushedAuthorizeEndpointHandlers

GetPushedAuthorizeEndpointHandlers returns the handlers.

func (*Config) GetPushedAuthorizeRequestURIPrefix

func (c *Config) GetPushedAuthorizeRequestURIPrefix(ctx context.Context) string

GetPushedAuthorizeRequestURIPrefix is the request URI prefix. This is usually 'urn:ietf:params:oauth:request_uri:'.

func (*Config) GetRedirectSecureChecker

func (c *Config) GetRedirectSecureChecker(_ context.Context) func(context.Context, *url.URL) bool

GetRedirectSecureChecker returns the checker to check if redirect URI is secure. Defaults to fosite.IsRedirectURISecure.

func (*Config) GetRedirectURIMatcher

func (c *Config) GetRedirectURIMatcher(_ context.Context) RedirectURIMatcher

GetRedirectURIMatcher returns the matcher used to resolve redirect URIs. Defaults to fosite.MatchRedirectURIWithClientRedirectURIs.

func (*Config) GetRefreshTokenLifespan

func (c *Config) GetRefreshTokenLifespan(_ context.Context) time.Duration

GetRefreshTokenLifespan sets how long a refresh token is going to be valid. Defaults to 30 days. Set to -1 for refresh tokens that never expire.

func (*Config) GetRefreshTokenScopes

func (c *Config) GetRefreshTokenScopes(_ context.Context) []string

GetRefreshTokenScopes returns which scopes will provide refresh tokens.

func (*Config) GetResponseModeHandlerExtension

func (c *Config) GetResponseModeHandlerExtension(ctx context.Context) ResponseModeHandler

func (*Config) GetRevocationHandlers

func (c *Config) GetRevocationHandlers(ctx context.Context) RevocationHandlers

func (*Config) GetRotatedGlobalSecrets

func (c *Config) GetRotatedGlobalSecrets(ctx context.Context) ([][]byte, error)

func (*Config) GetSanitationWhiteList

func (c *Config) GetSanitationWhiteList(ctx context.Context) []string

GetSanitationWhiteList returns a list of allowed form values that are required by the token endpoint. These values are safe for storage in a database (cleartext).

func (*Config) GetScopeStrategy

func (c *Config) GetScopeStrategy(_ context.Context) ScopeStrategy

GetScopeStrategy returns the scope strategy to be used. Defaults to glob scope strategy.

func (*Config) GetSecretsHasher

func (c *Config) GetSecretsHasher(ctx context.Context) Hasher

func (*Config) GetSendDebugMessagesToClients

func (c *Config) GetSendDebugMessagesToClients(ctx context.Context) bool

func (*Config) GetSupportedRequestObjectSigningAlgorithms

func (c *Config) GetSupportedRequestObjectSigningAlgorithms(_ context.Context) []string

GetSupportedRequestObjectSigningAlgorithms returns the JWS "alg" values accepted for OpenID Connect request objects. An empty list accepts every algorithm supported by the implementation.

func (*Config) GetTokenEndpointHandlers

func (c *Config) GetTokenEndpointHandlers(ctx context.Context) TokenEndpointHandlers

func (*Config) GetTokenEntropy

func (c *Config) GetTokenEntropy(_ context.Context) int

GetTokenEntropy returns the entropy of the "message" part of a HMAC Token. Defaults to 32.

func (*Config) GetTokenIntrospectionHandlers

func (c *Config) GetTokenIntrospectionHandlers(ctx context.Context) TokenIntrospectionHandlers

func (*Config) GetTokenURLs

func (c *Config) GetTokenURLs(ctx context.Context) []string

func (*Config) GetUseLegacyErrorFormat

func (c *Config) GetUseLegacyErrorFormat(ctx context.Context) bool

func (*Config) GetUserCodeLength

func (c *Config) GetUserCodeLength(ctx context.Context) int

GetUserCodeLength returns configured user_code length

func (*Config) GetUserCodeSymbols

func (c *Config) GetUserCodeSymbols(ctx context.Context) []rune

GetDeviceAuthTokenPollingInterval returns configured user_code allowed symbols

func (*Config) GetVerifiableCredentialsNonceLifespan

func (c *Config) GetVerifiableCredentialsNonceLifespan(_ context.Context) time.Duration

GetNonceLifespan returns how long a nonce should be valid. Defaults to one hour.

type Configurator

type Configurator interface {
	IDTokenIssuerProvider
	AuthorizationResponseIssuerProvider
	IDTokenLifespanProvider
	AllowedPromptsProvider
	EnforcePKCEProvider
	EnforcePKCEForPublicClientsProvider
	EnablePKCEPlainChallengeMethodProvider
	GrantTypeJWTBearerCanSkipClientAuthProvider
	GrantTypeJWTBearerIDOptionalProvider
	GrantTypeJWTBearerIssuedDateOptionalProvider
	GetJWTMaxDurationProvider
	AudienceStrategyProvider
	ScopeStrategyProvider
	IgnoreUnknownScopesProvider
	SupportedRequestObjectSigningAlgorithmsProvider
	RedirectSecureCheckerProvider
	RedirectURIMatcherProvider
	OmitRedirectScopeParamProvider
	SanitationAllowedProvider
	JWTScopeFieldProvider
	AccessTokenIssuerProvider
	DisableRefreshTokenValidationProvider
	RefreshTokenScopesProvider
	AccessTokenLifespanProvider
	RefreshTokenLifespanProvider
	VerifiableCredentialsNonceLifespanProvider
	AuthorizeCodeLifespanProvider
	DeviceAndUserCodeLifespanProvider
	TokenEntropyProvider
	RotatedGlobalSecretsProvider
	GlobalSecretProvider
	JWKSFetcherStrategyProvider
	HTTPClientProvider
	ScopeStrategyProvider
	AudienceStrategyProvider
	MinParameterEntropyProvider
	HMACHashingProvider
	ClientAuthenticationStrategyProvider
	ResponseModeHandlerExtensionProvider
	SendDebugMessagesToClientsProvider
	JWKSFetcherStrategyProvider
	ClientAuthenticationStrategyProvider
	ResponseModeHandlerExtensionProvider
	MessageCatalogProvider
	FormPostHTMLTemplateProvider
	TokenURLProvider
	GetSecretsHashingProvider
	AuthorizeEndpointHandlersProvider
	TokenEndpointHandlersProvider
	TokenIntrospectionHandlersProvider
	RevocationHandlersProvider
	UseLegacyErrorFormatProvider
	DeviceEndpointHandlersProvider
	UserCodeProvider
	DeviceProvider
}

type ContextKey

type ContextKey string

type DefaultCIMDFetcher

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

DefaultCIMDFetcher is the default CIMDFetcher. It blocks requests to private IP addresses (SSRF), refuses redirects, caps the response body size, and requires a 200 response.

func NewDefaultCIMDFetcher

func NewDefaultCIMDFetcher(opts ...CIMDFetcherOption) *DefaultCIMDFetcher

NewDefaultCIMDFetcher returns a DefaultCIMDFetcher configured with the given options and package defaults.

func (*DefaultCIMDFetcher) CIMDHTTPClient

func (f *DefaultCIMDFetcher) CIMDHTTPClient() *http.Client

CIMDHTTPClient returns a copy of the guarded HTTP client for fetching referenced metadata URLs.

func (*DefaultCIMDFetcher) Fetch

func (*DefaultCIMDFetcher) ValidateFetchURL

func (f *DefaultCIMDFetcher) ValidateFetchURL(ctx context.Context, rawURL string) error

ValidateFetchURL checks whether an HTTP URL referenced by a metadata document is safe to fetch.

type DefaultClient

type DefaultClient struct {
	ID             string   `json:"id"`
	Secret         []byte   `json:"client_secret,omitempty"`
	RotatedSecrets [][]byte `json:"rotated_secrets,omitempty"`
	RedirectURIs   []string `json:"redirect_uris"`
	GrantTypes     []string `json:"grant_types"`
	ResponseTypes  []string `json:"response_types"`
	Scopes         []string `json:"scopes"`
	Audience       []string `json:"audience"`
	Public         bool     `json:"public"`
}

DefaultClient is a simple default implementation of the Client interface.

func (*DefaultClient) GetAudience

func (c *DefaultClient) GetAudience() Arguments

func (*DefaultClient) GetGrantTypes

func (c *DefaultClient) GetGrantTypes() Arguments

func (*DefaultClient) GetHashedSecret

func (c *DefaultClient) GetHashedSecret() []byte

func (*DefaultClient) GetID

func (c *DefaultClient) GetID() string

func (*DefaultClient) GetRedirectURIs

func (c *DefaultClient) GetRedirectURIs() []string

func (*DefaultClient) GetResponseTypes

func (c *DefaultClient) GetResponseTypes() Arguments

func (*DefaultClient) GetRotatedHashes

func (c *DefaultClient) GetRotatedHashes() [][]byte

func (*DefaultClient) GetScopes

func (c *DefaultClient) GetScopes() Arguments

func (*DefaultClient) IsPublic

func (c *DefaultClient) IsPublic() bool

type DefaultClientWithCustomTokenLifespans

type DefaultClientWithCustomTokenLifespans struct {
	*DefaultClient
	TokenLifespans *ClientLifespanConfig `json:"token_lifespans"`
}

func (*DefaultClientWithCustomTokenLifespans) GetEffectiveLifespan

func (c *DefaultClientWithCustomTokenLifespans) GetEffectiveLifespan(gt GrantType, tt TokenType, fallback time.Duration) time.Duration

GetEffectiveLifespan either maps GrantType x TokenType to the client's configured lifespan, or returns the fallback value.

func (*DefaultClientWithCustomTokenLifespans) GetTokenLifespans

func (*DefaultClientWithCustomTokenLifespans) SetTokenLifespans

func (c *DefaultClientWithCustomTokenLifespans) SetTokenLifespans(lifespans *ClientLifespanConfig)

type DefaultJWKSFetcherStrategy

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

DefaultJWKSFetcherStrategy is a default implementation of the JWKSFetcherStrategy interface.

func (*DefaultJWKSFetcherStrategy) Resolve

func (s *DefaultJWKSFetcherStrategy) Resolve(ctx context.Context, location string, ignoreCache bool) (_ *jose.JSONWebKeySet, err error)

Resolve returns the JSON Web Key Set, or an error if something went wrong. The forceRefresh, if true, forces the strategy to fetch the key from the remote. If forceRefresh is false, the strategy may use a caching strategy to fetch the key.

func (*DefaultJWKSFetcherStrategy) WaitForCache

func (s *DefaultJWKSFetcherStrategy) WaitForCache()

type DefaultOpenIDConnectClient

type DefaultOpenIDConnectClient struct {
	*DefaultClient
	JSONWebKeysURI                    string              `json:"jwks_uri"`
	JSONWebKeys                       *jose.JSONWebKeySet `json:"jwks"`
	TokenEndpointAuthMethod           string              `json:"token_endpoint_auth_method"`
	RequestURIs                       []string            `json:"request_uris"`
	RequestObjectSigningAlgorithm     string              `json:"request_object_signing_alg"`
	TokenEndpointAuthSigningAlgorithm string              `json:"token_endpoint_auth_signing_alg"`
}

func (*DefaultOpenIDConnectClient) GetJSONWebKeys

func (c *DefaultOpenIDConnectClient) GetJSONWebKeys() *jose.JSONWebKeySet

func (*DefaultOpenIDConnectClient) GetJSONWebKeysURI

func (c *DefaultOpenIDConnectClient) GetJSONWebKeysURI() string

func (*DefaultOpenIDConnectClient) GetRequestObjectSigningAlgorithm

func (c *DefaultOpenIDConnectClient) GetRequestObjectSigningAlgorithm() string

func (*DefaultOpenIDConnectClient) GetRequestURIs

func (c *DefaultOpenIDConnectClient) GetRequestURIs() []string

func (*DefaultOpenIDConnectClient) GetTokenEndpointAuthMethod

func (c *DefaultOpenIDConnectClient) GetTokenEndpointAuthMethod() string

func (*DefaultOpenIDConnectClient) GetTokenEndpointAuthSigningAlgorithm

func (c *DefaultOpenIDConnectClient) GetTokenEndpointAuthSigningAlgorithm() string

type DefaultResponseModeClient

type DefaultResponseModeClient struct {
	*DefaultClient
	ResponseModes []ResponseModeType `json:"response_modes"`
}

func (*DefaultResponseModeClient) GetResponseModes

func (c *DefaultResponseModeClient) GetResponseModes() []ResponseModeType

type DefaultResponseModeHandler

type DefaultResponseModeHandler struct{}

func NewDefaultResponseModeHandler

func NewDefaultResponseModeHandler() *DefaultResponseModeHandler

func (*DefaultResponseModeHandler) ResponseModes

func (d *DefaultResponseModeHandler) ResponseModes() ResponseModeTypes

func (*DefaultResponseModeHandler) WriteAuthorizeError

func (d *DefaultResponseModeHandler) WriteAuthorizeError(ctx context.Context, rw http.ResponseWriter, ar AuthorizeRequester, err error)

func (*DefaultResponseModeHandler) WriteAuthorizeResponse

type DefaultSession

type DefaultSession struct {
	ExpiresAt map[TokenType]time.Time `json:"expires_at"`
	Username  string                  `json:"username"`
	Subject   string                  `json:"subject"`
	Extra     map[string]interface{}  `json:"extra"`
}

DefaultSession is a default implementation of the session interface.

func (*DefaultSession) Clone

func (s *DefaultSession) Clone() Session

func (*DefaultSession) GetExpiresAt

func (s *DefaultSession) GetExpiresAt(key TokenType) time.Time

func (*DefaultSession) GetExtraClaims

func (s *DefaultSession) GetExtraClaims() map[string]interface{}

GetExtraClaims implements ExtraClaimsSession for DefaultSession. The returned value can be modified in-place.

func (*DefaultSession) GetSubject

func (s *DefaultSession) GetSubject() string

func (*DefaultSession) GetUsername

func (s *DefaultSession) GetUsername() string

func (*DefaultSession) SetExpiresAt

func (s *DefaultSession) SetExpiresAt(key TokenType, exp time.Time)

func (*DefaultSession) SetSubject

func (s *DefaultSession) SetSubject(subject string)

type DeviceAndUserCodeLifespanProvider

type DeviceAndUserCodeLifespanProvider interface {
	GetDeviceAndUserCodeLifespan(ctx context.Context) time.Duration
}

DeviceAndUserCodeLifespanProvider returns the provider for configuring the device and user code lifespan

type DeviceEndpointHandler

type DeviceEndpointHandler interface {
	// HandleDeviceEndpointRequest handles a device authorize endpoint request. To extend the handler's capabilities, the http request
	// is passed along, if further information retrieval is required. If the handler feels that he is not responsible for
	// the device authorize request, he must return nil and NOT modify session nor responder neither requester.
	//
	// The following spec is a good example of what HandleDeviceEndpointRequest should do.
	// * https://tools.ietf.org/html/rfc8628#section-3.2
	HandleDeviceEndpointRequest(ctx context.Context, requester DeviceRequester, responder DeviceResponder) error
}

DeviceEndpointHandler is the interface that handles https://tools.ietf.org/html/rfc8628

type DeviceEndpointHandlers

type DeviceEndpointHandlers []DeviceEndpointHandler

DeviceEndpointHandlers is a list of DeviceEndpointHandler

func (*DeviceEndpointHandlers) Append

Append adds an DeviceEndpointHandlers to this list. Ignores duplicates based on reflect.TypeOf.

type DeviceEndpointHandlersProvider

type DeviceEndpointHandlersProvider interface {
	// GetDeviceEndpointHandlers returns the handlers.
	GetDeviceEndpointHandlers(ctx context.Context) DeviceEndpointHandlers
}

DeviceEndpointHandlersProvider returns the provider for setting up the Device handlers.

type DeviceProvider

type DeviceProvider interface {
	GetDeviceVerificationURL(ctx context.Context) string
	GetDeviceAuthTokenPollingInterval(ctx context.Context) time.Duration
}

DeviceProvider returns the provider for configuring the device flow

type DeviceRequest

type DeviceRequest struct {
	UserCodeState UserCodeState
	Request
}

DeviceRequest is an implementation of DeviceRequester

func NewDeviceRequest

func NewDeviceRequest() *DeviceRequest

NewDeviceRequest returns a new device request

func (*DeviceRequest) GetUserCodeState

func (d *DeviceRequest) GetUserCodeState() UserCodeState

func (*DeviceRequest) Sanitize

func (d *DeviceRequest) Sanitize(allowedParameters []string) Requester

func (*DeviceRequest) SetUserCodeState

func (d *DeviceRequest) SetUserCodeState(state UserCodeState)

type DeviceRequester

type DeviceRequester interface {
	// GetUserCodeState returns the state of the user code
	GetUserCodeState() UserCodeState

	// SetUserCodeState sets the state of the user code
	SetUserCodeState(state UserCodeState)

	Requester
}

DeviceRequester is an device endpoint's request context.

type DeviceResponder

type DeviceResponder interface {
	// GetDeviceCode returns the device_code
	GetDeviceCode() string
	// SetDeviceCode sets the device_code
	SetDeviceCode(code string)

	// GetUserCode returns the user_code
	GetUserCode() string
	// SetUserCode sets the user_code
	SetUserCode(code string)

	// GetVerificationURI returns the verification_uri
	GetVerificationURI() string
	// SetVerificationURI sets the verification_uri
	SetVerificationURI(uri string)

	// GetVerificationURIComplete returns the verification_uri_complete
	GetVerificationURIComplete() string
	// SetVerificationURIComplete sets the verification_uri_complete
	SetVerificationURIComplete(uri string)

	// GetExpiresIn returns the expires_in
	GetExpiresIn() int64
	// SetExpiresIn sets the expires_in
	SetExpiresIn(seconds int64)

	// GetInterval returns the interval
	GetInterval() int
	// SetInterval sets the interval
	SetInterval(seconds int)

	// GetHeader returns the response's header
	GetHeader() (header http.Header)
	// AddHeader adds a header key value pair to the response
	AddHeader(key, value string)
}

DeviceResponder is the device authorization endpoint's response

type DeviceResponse

type DeviceResponse struct {
	Header                  http.Header
	DeviceCode              string `json:"device_code"`
	UserCode                string `json:"user_code"`
	VerificationURI         string `json:"verification_uri"`
	VerificationURIComplete string `json:"verification_uri_complete,omitempty"`
	ExpiresIn               int64  `json:"expires_in"`
	Interval                int    `json:"interval,omitempty"`
}

DeviceResponse represents the device authorization response

func NewDeviceResponse

func NewDeviceResponse() *DeviceResponse

NewDeviceResponse returns a new DeviceResponse

func (*DeviceResponse) AddHeader

func (d *DeviceResponse) AddHeader(key, value string)

AddHeader adds a header to the response

func (*DeviceResponse) GetDeviceCode

func (d *DeviceResponse) GetDeviceCode() string

GetDeviceCode returns the response's device_code

func (*DeviceResponse) GetExpiresIn

func (d *DeviceResponse) GetExpiresIn() int64

GetExpiresIn returns the response's device code and user code lifetime in seconds if set

func (*DeviceResponse) GetHeader

func (d *DeviceResponse) GetHeader() http.Header

GetHeader returns the response's headers

func (*DeviceResponse) GetInterval

func (d *DeviceResponse) GetInterval() int

GetInterval returns the response's polling interval if set

func (*DeviceResponse) GetUserCode

func (d *DeviceResponse) GetUserCode() string

GetUserCode returns the response's user_code

func (*DeviceResponse) GetVerificationURI

func (d *DeviceResponse) GetVerificationURI() string

GetVerificationURI returns the response's verification uri

func (*DeviceResponse) GetVerificationURIComplete

func (d *DeviceResponse) GetVerificationURIComplete() string

GetVerificationURIComplete returns the response's complete verification uri if set

func (*DeviceResponse) SetDeviceCode

func (d *DeviceResponse) SetDeviceCode(code string)

SetDeviceCode sets the response's device_code

func (*DeviceResponse) SetExpiresIn

func (d *DeviceResponse) SetExpiresIn(seconds int64)

SetExpiresIn sets the response's device code and user code lifetime in seconds

func (*DeviceResponse) SetInterval

func (d *DeviceResponse) SetInterval(seconds int)

SetInterval sets the response's polling interval

func (*DeviceResponse) SetUserCode

func (d *DeviceResponse) SetUserCode(code string)

SetUserCode sets the response's user_code

func (*DeviceResponse) SetVerificationURI

func (d *DeviceResponse) SetVerificationURI(uri string)

SetVerificationURI sets the response's verification uri

func (*DeviceResponse) SetVerificationURIComplete

func (d *DeviceResponse) SetVerificationURIComplete(uri string)

SetVerificationURIComplete sets the response's complete verification uri

type DisableRefreshTokenValidationProvider

type DisableRefreshTokenValidationProvider interface {
	// GetDisableRefreshTokenValidation returns the disable refresh token validation flag.
	GetDisableRefreshTokenValidation(ctx context.Context) bool
}

DisableRefreshTokenValidationProvider returns the provider for configuring the refresh token validation.

type EnablePKCEPlainChallengeMethodProvider

type EnablePKCEPlainChallengeMethodProvider interface {
	// GetEnablePKCEPlainChallengeMethod returns the enable PKCE plain challenge method.
	GetEnablePKCEPlainChallengeMethod(ctx context.Context) bool
}

EnablePKCEPlainChallengeMethodProvider returns the provider for configuring the enable PKCE plain challenge method.

type EnforcePKCEForPublicClientsProvider

type EnforcePKCEForPublicClientsProvider interface {
	// GetEnforcePKCEForPublicClients returns the enforcement of PKCE for public clients.
	GetEnforcePKCEForPublicClients(ctx context.Context) bool
}

EnforcePKCEForPublicClientsProvider returns the provider for configuring the enforcement of PKCE for public clients.

type EnforcePKCEProvider

type EnforcePKCEProvider interface {
	// GetEnforcePKCE returns the enforcement of PKCE.
	GetEnforcePKCE(ctx context.Context) bool
}

EnforcePKCEProvider returns the provider for configuring the enforcement of PKCE.

type ExtraClaimsSession

type ExtraClaimsSession interface {
	// GetExtraClaims returns a map to store extra claims.
	// The returned value can be modified in-place.
	GetExtraClaims() map[string]interface{}
}

ExtraClaimsSession provides an interface for session to store any extra claims.

type FormPostHTMLTemplateProvider

type FormPostHTMLTemplateProvider interface {
	// GetFormPostHTMLTemplate returns the form post HTML template.
	GetFormPostHTMLTemplate(ctx context.Context) *template.Template
}

FormPostHTMLTemplateProvider returns the provider for configuring the form post HTML template.

type Fosite

type Fosite struct {
	Store Storage

	Config Configurator
}

Fosite implements OAuth2Provider.

func NewOAuth2Provider

func NewOAuth2Provider(s Storage, c Configurator) *Fosite

func (*Fosite) AuthenticateClient

func (f *Fosite) AuthenticateClient(ctx context.Context, r *http.Request, form url.Values) (Client, error)

AuthenticateClient authenticates client requests using the configured strategy `Fosite.ClientAuthenticationStrategy`, if nil it uses `Fosite.DefaultClientAuthenticationStrategy`

func (*Fosite) DefaultClientAuthenticationStrategy

func (f *Fosite) DefaultClientAuthenticationStrategy(ctx context.Context, r *http.Request, form url.Values) (_ Client, err error)

DefaultClientAuthenticationStrategy provides the fosite's default client authentication strategy, HTTP Basic Authentication and JWT Bearer

func (*Fosite) GetMinParameterEntropy

func (f *Fosite) GetMinParameterEntropy(ctx context.Context) int

GetMinParameterEntropy returns MinParameterEntropy if set. Defaults to fosite.MinParameterEntropy.

func (*Fosite) IntrospectToken

func (f *Fosite) IntrospectToken(ctx context.Context, token string, tokenUse TokenUse, session Session, scopes ...string) (_ TokenUse, _ AccessRequester, err error)

func (*Fosite) NewAccessRequest

func (f *Fosite) NewAccessRequest(ctx context.Context, r *http.Request, session Session) (_ AccessRequester, err error)

Implements

  • https://tools.ietf.org/html/rfc6749#section-2.3.1 Clients in possession of a client password MAY use the HTTP Basic authentication scheme as defined in [RFC2617] to authenticate with the authorization server. The client identifier is encoded using the "application/x-www-form-urlencoded" encoding algorithm per Appendix B, and the encoded value is used as the username; the client password is encoded using the same algorithm and used as the password. The authorization server MUST support the HTTP Basic authentication scheme for authenticating clients that were issued a client password. Including the client credentials in the request-body using the two parameters is NOT RECOMMENDED and SHOULD be limited to clients unable to directly utilize the HTTP Basic authentication scheme (or other password-based HTTP authentication schemes). The parameters can only be transmitted in the request-body and MUST NOT be included in the request URI.
  • https://tools.ietf.org/html/rfc6749#section-3.2.1
  • Confidential clients or other clients issued client credentials MUST authenticate with the authorization server as described in Section 2.3 when making requests to the token endpoint.
  • If the client type is confidential or the client was issued client credentials (or assigned other authentication requirements), the client MUST authenticate with the authorization server as described in Section 3.2.1.

func (*Fosite) NewAccessResponse

func (f *Fosite) NewAccessResponse(ctx context.Context, requester AccessRequester) (_ AccessResponder, err error)

func (*Fosite) NewAuthorizeRequest

func (f *Fosite) NewAuthorizeRequest(ctx context.Context, r *http.Request) (_ AuthorizeRequester, err error)

func (*Fosite) NewAuthorizeResponse

func (f *Fosite) NewAuthorizeResponse(ctx context.Context, ar AuthorizeRequester, session Session) (_ AuthorizeResponder, err error)

func (*Fosite) NewDeviceRequest

func (f *Fosite) NewDeviceRequest(ctx context.Context, r *http.Request) (_ DeviceRequester, err error)

NewDeviceRequest parses an http Request returns a Device request

func (*Fosite) NewDeviceResponse

func (f *Fosite) NewDeviceResponse(ctx context.Context, r DeviceRequester, session Session) (DeviceResponder, error)

NewDeviceResponse returns a new DeviceResponder

func (*Fosite) NewIntrospectionRequest

func (f *Fosite) NewIntrospectionRequest(ctx context.Context, r *http.Request, session Session) (_ IntrospectionResponder, err error)

NewIntrospectionRequest initiates token introspection as defined in https://tools.ietf.org/html/rfc7662#section-2.1

The protected resource calls the introspection endpoint using an HTTP POST [RFC7231] request with parameters sent as "application/x-www-form-urlencoded" data as defined in [W3C.REC-html5-20141028]. The protected resource sends a parameter representing the token along with optional parameters representing additional context that is known by the protected resource to aid the authorization server in its response.

* token REQUIRED. The string value of the token. For access tokens, this is the "access_token" value returned from the token endpoint defined in OAuth 2.0 [RFC6749], Section 5.1. For refresh tokens, this is the "refresh_token" value returned from the token endpoint as defined in OAuth 2.0 [RFC6749], Section 5.1. Other token types are outside the scope of this specification.

* token_type_hint OPTIONAL. A hint about the type of the token submitted for introspection. The protected resource MAY pass this parameter to help the authorization server optimize the token lookup. If the server is unable to locate the token using the given hint, it MUST extend its search across all of its supported token types. An authorization server MAY ignore this parameter, particularly if it is able to detect the token type automatically. Values for this field are defined in the "OAuth Token Type Hints" registry defined in OAuth Token Revocation [RFC7009].

The introspection endpoint MAY accept other OPTIONAL parameters to provide further context to the query. For instance, an authorization server may desire to know the IP address of the client accessing the protected resource to determine if the correct client is likely to be presenting the token. The definition of this or any other parameters are outside the scope of this specification, to be defined by service documentation or extensions to this specification. If the authorization server is unable to determine the state of the token without additional information, it SHOULD return an introspection response indicating the token is not active as described in Section 2.2.

To prevent token scanning attacks, the endpoint MUST also require some form of authorization to access this endpoint, such as client authentication as described in OAuth 2.0 [RFC6749] or a separate OAuth 2.0 access token such as the bearer token described in OAuth 2.0 Bearer Token Usage [RFC6750]. The methods of managing and validating these authentication credentials are out of scope of this specification.

For example, the following shows a protected resource calling the token introspection endpoint to query about an OAuth 2.0 bearer token. The protected resource is using a separate OAuth 2.0 bearer token to authorize this call.

The following is a non-normative example request:

POST /introspect HTTP/1.1
Host: server.example.com
Accept: application/json
Content-Type: application/x-www-form-urlencoded
Authorization: Bearer 23410913-abewfq.123483

token=2YotnFZFEjr1zCsicMWpAA

In this example, the protected resource uses a client identifier and client secret to authenticate itself to the introspection endpoint. The protected resource also sends a token type hint indicating that it is inquiring about an access token.

The following is a non-normative example request:

POST /introspect HTTP/1.1
Host: server.example.com
Accept: application/json
Content-Type: application/x-www-form-urlencoded
Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW

token=mF_9.B5f-4.1JqM&token_type_hint=access_token

func (*Fosite) NewPushedAuthorizeRequest

func (f *Fosite) NewPushedAuthorizeRequest(ctx context.Context, r *http.Request) (_ AuthorizeRequester, err error)

NewPushedAuthorizeRequest validates the request and produces an AuthorizeRequester object that can be stored

func (*Fosite) NewPushedAuthorizeResponse

func (f *Fosite) NewPushedAuthorizeResponse(ctx context.Context, ar AuthorizeRequester, session Session) (_ PushedAuthorizeResponder, err error)

NewPushedAuthorizeResponse executes the handlers and builds the response

func (*Fosite) NewRevocationRequest

func (f *Fosite) NewRevocationRequest(ctx context.Context, r *http.Request) (err error)

NewRevocationRequest handles incoming token revocation requests and validates various parameters as specified in: https://tools.ietf.org/html/rfc7009#section-2.1

The authorization server first validates the client credentials (in case of a confidential client) and then verifies whether the token was issued to the client making the revocation request. If this validation fails, the request is refused and the client is informed of the error by the authorization server as described below.

In the next step, the authorization server invalidates the token. The invalidation takes place immediately, and the token cannot be used again after the revocation.

* https://tools.ietf.org/html/rfc7009#section-2.2 An invalid token type hint value is ignored by the authorization server and does not influence the revocation response.

func (*Fosite) ParseResponseMode

func (f *Fosite) ParseResponseMode(ctx context.Context, r *http.Request, request *AuthorizeRequest) error

func (*Fosite) ResponseModeHandler

func (f *Fosite) ResponseModeHandler(ctx context.Context) ResponseModeHandler

func (*Fosite) WriteAccessError

func (f *Fosite) WriteAccessError(ctx context.Context, rw http.ResponseWriter, req Requester, err error)

Convert an error to an http response as per RFC6749

func (*Fosite) WriteAccessResponse

func (f *Fosite) WriteAccessResponse(ctx context.Context, rw http.ResponseWriter, requester AccessRequester, responder AccessResponder)

func (*Fosite) WriteAuthorizeError

func (f *Fosite) WriteAuthorizeError(ctx context.Context, rw http.ResponseWriter, ar AuthorizeRequester, err error)

func (*Fosite) WriteAuthorizeResponse

func (f *Fosite) WriteAuthorizeResponse(ctx context.Context, rw http.ResponseWriter, ar AuthorizeRequester, resp AuthorizeResponder)

func (*Fosite) WriteDeviceResponse

func (f *Fosite) WriteDeviceResponse(ctx context.Context, rw http.ResponseWriter, requester DeviceRequester, responder DeviceResponder)

WriteDeviceResponse writes the device response

func (*Fosite) WriteIntrospectionError

func (f *Fosite) WriteIntrospectionError(ctx context.Context, rw http.ResponseWriter, err error)

WriteIntrospectionError responds with token metadata discovered by token introspection as defined in https://tools.ietf.org/html/rfc7662#section-2.2

If the protected resource uses OAuth 2.0 client credentials to authenticate to the introspection endpoint and its credentials are invalid, the authorization server responds with an HTTP 401 (Unauthorized) as described in Section 5.2 of OAuth 2.0 [RFC6749].

If the protected resource uses an OAuth 2.0 bearer token to authorize its call to the introspection endpoint and the token used for authorization does not contain sufficient privileges or is otherwise invalid for this request, the authorization server responds with an HTTP 401 code as described in Section 3 of OAuth 2.0 Bearer Token Usage [RFC6750].

Note that a properly formed and authorized query for an inactive or otherwise invalid token (or a token the protected resource is not allowed to know about) is not considered an error response by this specification. In these cases, the authorization server MUST instead respond with an introspection response with the "active" field set to "false" as described in Section 2.2.

func (*Fosite) WriteIntrospectionResponse

func (f *Fosite) WriteIntrospectionResponse(ctx context.Context, rw http.ResponseWriter, r IntrospectionResponder)

WriteIntrospectionResponse responds with an error if token introspection failed as defined in https://tools.ietf.org/html/rfc7662#section-2.3

The server responds with a JSON object [RFC7159] in "application/ json" format with the following top-level members.

* active REQUIRED. Boolean indicator of whether or not the presented token is currently active. The specifics of a token's "active" state will vary depending on the implementation of the authorization server and the information it keeps about its tokens, but a "true" value return for the "active" property will generally indicate that a given token has been issued by this authorization server, has not been revoked by the resource owner, and is within its given time window of validity (e.g., after its issuance time and before its expiration time). See Section 4 for information on implementation of such checks.

* scope OPTIONAL. A JSON string containing a space-separated list of scopes associated with this token, in the format described in Section 3.3 of OAuth 2.0 [RFC6749].

* client_id OPTIONAL. Client identifier for the OAuth 2.0 client that requested this token.

* username OPTIONAL. Human-readable identifier for the resource owner who authorized this token.

* token_type OPTIONAL. Type of the token as defined in Section 5.1 of OAuth 2.0 [RFC6749].

* exp OPTIONAL. Integer timestamp, measured in the number of seconds since January 1 1970 UTC, indicating when this token will expire, as defined in JWT [RFC7519].

* iat OPTIONAL. Integer timestamp, measured in the number of seconds since January 1 1970 UTC, indicating when this token was originally issued, as defined in JWT [RFC7519].

* nbf OPTIONAL. Integer timestamp, measured in the number of seconds since January 1 1970 UTC, indicating when this token is not to be used before, as defined in JWT [RFC7519].

* sub OPTIONAL. Subject of the token, as defined in JWT [RFC7519]. Usually a machine-readable identifier of the resource owner who authorized this token.

* aud OPTIONAL. Service-specific string identifier or list of string identifiers representing the intended audience for this token, as defined in JWT [RFC7519].

* iss OPTIONAL. String representing the issuer of this token, as defined in JWT [RFC7519].

* jti OPTIONAL. String identifier for the token, as defined in JWT [RFC7519].

Specific implementations MAY extend this structure with their own service-specific response names as top-level members of this JSON object. Response names intended to be used across domains MUST be registered in the "OAuth Token Introspection Response" registry defined in Section 3.1.

The authorization server MAY respond differently to different protected resources making the same request. For instance, an authorization server MAY limit which scopes from a given token are returned for each protected resource to prevent a protected resource from learning more about the larger network than is necessary for its operation.

The response MAY be cached by the protected resource to improve performance and reduce load on the introspection endpoint, but at the cost of liveness of the information used by the protected resource to make authorization decisions. See Section 4 for more information regarding the trade off when the response is cached.

For example, the following response contains a set of information about an active token:

The following is a non-normative example response:

HTTP/1.1 200 OK
Content-Type: application/json

{
  "active": true,
  "client_id": "l238j323ds-23ij4",
  "username": "jdoe",
  "scope": "read write dolphin",
  "sub": "Z5O3upPC88QrAjx00dis",
  "aud": "https://protected.example.net/resource",
  "iss": "https://server.example.com/",
  "exp": 1419356238,
  "iat": 1419350238,
  "extension_field": "twenty-seven"
}

If the introspection call is properly authorized but the token is not active, does not exist on this server, or the protected resource is not allowed to introspect this particular token, then the authorization server MUST return an introspection response with the "active" field set to "false". Note that to avoid disclosing too much of the authorization server's state to a third party, the authorization server SHOULD NOT include any additional information about an inactive token, including why the token is inactive.

The following is a non-normative example response for a token that has been revoked or is otherwise invalid:

HTTP/1.1 200 OK
Content-Type: application/json

{
  "active": false
}

func (*Fosite) WritePushedAuthorizeError

func (f *Fosite) WritePushedAuthorizeError(ctx context.Context, rw http.ResponseWriter, ar AuthorizeRequester, err error)

WritePushedAuthorizeError writes the PAR error

func (*Fosite) WritePushedAuthorizeResponse

func (f *Fosite) WritePushedAuthorizeResponse(ctx context.Context, rw http.ResponseWriter, ar AuthorizeRequester, resp PushedAuthorizeResponder)

WritePushedAuthorizeResponse writes the PAR response

func (*Fosite) WriteRevocationResponse

func (f *Fosite) WriteRevocationResponse(ctx context.Context, rw http.ResponseWriter, err error)

WriteRevocationResponse writes a token revocation response as specified in: https://tools.ietf.org/html/rfc7009#section-2.2

The authorization server responds with HTTP status code 200 if the token has been revoked successfully or if the client submitted an invalid token.

Note: invalid tokens do not cause an error response since the client cannot handle such an error in a reasonable way. Moreover, the purpose of the revocation request, invalidating the particular token, is already achieved.

type G11NContext

type G11NContext interface {
	// GetLang returns the current language in the context
	GetLang() language.Tag
}

G11NContext is the globalization context

type GetJWTMaxDurationProvider

type GetJWTMaxDurationProvider interface {
	// GetJWTMaxDuration returns the JWT max duration.
	GetJWTMaxDuration(ctx context.Context) time.Duration
}

GetJWTMaxDurationProvider returns the provider for configuring the JWT max duration.

type GetSecretsHashingProvider

type GetSecretsHashingProvider interface {
	// GetSecretsHasher returns the client secrets hashing function.
	GetSecretsHasher(ctx context.Context) Hasher
}

GetSecretsHashingProvider provides the client secrets hashing function.

type GlobalSecretProvider

type GlobalSecretProvider interface {
	// GetGlobalSecret returns the global secret.
	GetGlobalSecret(ctx context.Context) ([]byte, error)
}

GlobalSecretProvider returns the provider for configuring the global secret.

type GrantType

type GrantType string

type GrantTypeJWTBearerCanSkipClientAuthProvider

type GrantTypeJWTBearerCanSkipClientAuthProvider interface {
	// GetGrantTypeJWTBearerCanSkipClientAuth returns the grant type JWT bearer can skip client auth.
	GetGrantTypeJWTBearerCanSkipClientAuth(ctx context.Context) bool
}

GrantTypeJWTBearerCanSkipClientAuthProvider returns the provider for configuring the grant type JWT bearer can skip client auth.

type GrantTypeJWTBearerIDOptionalProvider

type GrantTypeJWTBearerIDOptionalProvider interface {
	// GetGrantTypeJWTBearerIDOptional returns the grant type JWT bearer ID optional.
	GetGrantTypeJWTBearerIDOptional(ctx context.Context) bool
}

GrantTypeJWTBearerIDOptionalProvider returns the provider for configuring the grant type JWT bearer ID optional.

type GrantTypeJWTBearerIssuedDateOptionalProvider

type GrantTypeJWTBearerIssuedDateOptionalProvider interface {
	// GetGrantTypeJWTBearerIssuedDateOptional returns the grant type JWT bearer issued date optional.
	GetGrantTypeJWTBearerIssuedDateOptional(ctx context.Context) bool
}

GrantTypeJWTBearerIssuedDateOptionalProvider returns the provider for configuring the grant type JWT bearer issued date optional.

type GrantTypeJWTBearerOmitAssertionAudienceProvider

type GrantTypeJWTBearerOmitAssertionAudienceProvider interface {
	// GetGrantTypeJWTBearerOmitAssertionAudience returns whether the audience from the assertion JWT should be
	// omitted from the resulting access token. The Ory Hydra configuration defaults this to true (omit), as the
	// assertion audience identifies the authorization server rather than the access token's audience (RFC 7523).
	GetGrantTypeJWTBearerOmitAssertionAudience(ctx context.Context) bool
}

GrantTypeJWTBearerOmitAssertionAudienceProvider returns the provider for configuring whether the audience from the assertion JWT is omitted from the resulting access token in the jwt-bearer grant type.

type HMACHashingProvider

type HMACHashingProvider interface {
	// GetHMACHasher returns the hash function.
	GetHMACHasher(ctx context.Context) func() hash.Hash
}

HMACHashingProvider returns the provider for configuring the hash function.

type HTTPClientProvider

type HTTPClientProvider interface {
	// GetHTTPClient returns the HTTP client provider.
	GetHTTPClient(ctx context.Context) *retryablehttp.Client
}

HTTPClientProvider returns the provider for configuring the HTTP client.

type Hasher

type Hasher interface {
	// Compare compares data with a hash and returns an error
	// if the two do not match.
	Compare(ctx context.Context, hash, data []byte) error

	// Hash creates a hash from data or returns an error.
	Hash(ctx context.Context, data []byte) ([]byte, error)
}

Hasher defines how a oauth2-compatible hasher should look like.

type IDTokenIssuerProvider

type IDTokenIssuerProvider interface {
	// GetIDTokenIssuer returns the ID token issuer.
	GetIDTokenIssuer(ctx context.Context) string
}

IDTokenIssuerProvider returns the provider for configuring the ID token issuer.

type IDTokenLifespanProvider

type IDTokenLifespanProvider interface {
	// GetIDTokenLifespan returns the ID token lifespan.
	GetIDTokenLifespan(ctx context.Context) time.Duration
}

IDTokenLifespanProvider returns the provider for configuring the ID token lifespan.

type IgnoreUnknownScopesProvider

type IgnoreUnknownScopesProvider interface {
	// GetIgnoreUnknownScopes returns true if requested scopes that are not covered by the client's registered
	// scopes should be silently dropped from the request instead of failing it with an invalid_scope error.
	GetIgnoreUnknownScopes(ctx context.Context) bool
}

IgnoreUnknownScopesProvider returns the provider for configuring how unknown requested scopes are handled.

type IntrospectionResponder

type IntrospectionResponder interface {
	// IsActive returns true if the introspected token is active and false otherwise.
	IsActive() bool

	// GetAccessRequester returns nil when IsActive() is false and the original access request object otherwise.
	GetAccessRequester() AccessRequester

	// GetTokenUse optionally returns the type of the token that was introspected. This could be "access_token", "refresh_token",
	// or if the type can not be determined an empty string.
	GetTokenUse() TokenUse

	// GetAccessTokenType optionally returns the type of the access token that was introspected. This could be "bearer", "mac",
	// or empty string if the type of the token is refresh token.
	GetAccessTokenType() string
}

IntrospectionResponder is the response object that will be returned when token introspection was successful, for example when the client is allowed to perform token introspection. Refer to https://tools.ietf.org/html/rfc7662#section-2.2 for more details.

type IntrospectionResponse

type IntrospectionResponse struct {
	Active          bool            `json:"active"`
	AccessRequester AccessRequester `json:"extra"`
	TokenUse        TokenUse        `json:"token_use,omitempty"`
	AccessTokenType string          `json:"token_type,omitempty"`
	Lang            language.Tag    `json:"-"`
}

func (*IntrospectionResponse) GetAccessRequester

func (r *IntrospectionResponse) GetAccessRequester() AccessRequester

func (*IntrospectionResponse) GetAccessTokenType

func (r *IntrospectionResponse) GetAccessTokenType() string

func (*IntrospectionResponse) GetTokenUse

func (r *IntrospectionResponse) GetTokenUse() TokenUse

func (*IntrospectionResponse) IsActive

func (r *IntrospectionResponse) IsActive() bool

type JWKSFetcherStrategy

type JWKSFetcherStrategy interface {
	// Resolve returns the JSON Web Key Set, or an error if something went wrong. The forceRefresh, if true, forces
	// the strategy to fetch the key from the remote. If forceRefresh is false, the strategy may use a caching strategy
	// to fetch the key.
	Resolve(ctx context.Context, location string, ignoreCache bool) (*jose.JSONWebKeySet, error)
}

JWKSFetcherStrategy is a strategy which pulls (optionally caches) JSON Web Key Sets from a location, typically a client's jwks_uri.

func NewDefaultJWKSFetcherStrategy

func NewDefaultJWKSFetcherStrategy(opts ...func(*DefaultJWKSFetcherStrategy)) JWKSFetcherStrategy

NewDefaultJWKSFetcherStrategy returns a new instance of the DefaultJWKSFetcherStrategy.

type JWKSFetcherStrategyProvider

type JWKSFetcherStrategyProvider interface {
	// GetJWKSFetcherStrategy returns the JWKS fetcher strategy.
	GetJWKSFetcherStrategy(ctx context.Context) JWKSFetcherStrategy
}

JWKSFetcherStrategyProvider returns the provider for configuring the JWKS fetcher strategy.

type JWTScopeFieldProvider

type JWTScopeFieldProvider interface {
	// GetJWTScopeField returns the JWT scope field.
	GetJWTScopeField(ctx context.Context) jwt.JWTScopeFieldEnum
}

JWTScopeFieldProvider returns the provider for configuring the JWT scope field.

type MessageCatalogProvider

type MessageCatalogProvider interface {
	// GetMessageCatalog returns the message catalog.
	GetMessageCatalog(ctx context.Context) i18n.MessageCatalog
}

MessageCatalogProvider returns the provider for configuring the message catalog.

type MinParameterEntropyProvider

type MinParameterEntropyProvider interface {
	// GetMinParameterEntropy returns the minimum parameter entropy.
	GetMinParameterEntropy(_ context.Context) int
}

MinParameterEntropyProvider returns the provider for configuring the minimum parameter entropy.

type OAuth2Provider

type OAuth2Provider interface {
	// NewAuthorizeRequest returns an AuthorizeRequest.
	//
	// The following specs must be considered in any implementation of this method:
	// * https://tools.ietf.org/html/rfc6749#section-3.1
	//	 Extension response types MAY contain a space-delimited (%x20) list of
	//	 values, where the order of values does not matter (e.g., response
	//	 type "a b" is the same as "b a").  The meaning of such composite
	//	 response types is defined by their respective specifications.
	// * https://tools.ietf.org/html/rfc6749#section-3.1.2
	//   The redirection endpoint URI MUST be an absolute URI as defined by
	//   [RFC3986] Section 4.3.  The endpoint URI MAY include an
	//   "application/x-www-form-urlencoded" formatted (per Appendix B) query
	//   component ([RFC3986] Section 3.4), which MUST be retained when adding
	//   additional query parameters.  The endpoint URI MUST NOT include a
	//   fragment component.
	// * https://tools.ietf.org/html/rfc6749#section-3.1.2.2 (everything MUST be implemented)
	NewAuthorizeRequest(ctx context.Context, req *http.Request) (AuthorizeRequester, error)

	// NewAuthorizeResponse iterates through all response type handlers and returns their result or
	// ErrUnsupportedResponseType if none of the handlers were able to handle it.
	//
	// The following specs must be considered in any implementation of this method:
	// * https://tools.ietf.org/html/rfc6749#section-3.1.1
	//	 Extension response types MAY contain a space-delimited (%x20) list of
	//	 values, where the order of values does not matter (e.g., response
	//	 type "a b" is the same as "b a").  The meaning of such composite
	//	 response types is defined by their respective specifications.
	//	 If an authorization request is missing the "response_type" parameter,
	//	 or if the response type is not understood, the authorization server
	//	 MUST return an error response as described in Section 4.1.2.1.
	NewAuthorizeResponse(ctx context.Context, requester AuthorizeRequester, session Session) (AuthorizeResponder, error)

	// WriteAuthorizeError returns the error codes to the redirection endpoint or shows the error to the user, if no valid
	// redirect uri was given. Implements rfc6749#section-4.1.2.1
	//
	// The following specs must be considered in any implementation of this method:
	// * https://tools.ietf.org/html/rfc6749#section-3.1.2
	//   The redirection endpoint URI MUST be an absolute URI as defined by
	//   [RFC3986] Section 4.3.  The endpoint URI MAY include an
	//   "application/x-www-form-urlencoded" formatted (per Appendix B) query
	//   component ([RFC3986] Section 3.4), which MUST be retained when adding
	//   additional query parameters.  The endpoint URI MUST NOT include a
	//   fragment component.
	// * https://tools.ietf.org/html/rfc6749#section-4.1.2.1 (everything)
	// * https://tools.ietf.org/html/rfc6749#section-3.1.2.2 (everything MUST be implemented)
	WriteAuthorizeError(ctx context.Context, rw http.ResponseWriter, requester AuthorizeRequester, err error)

	// WriteAuthorizeResponse persists the AuthorizeSession in the store and redirects the user agent to the provided
	// redirect url or returns an error if storage failed.
	//
	// The following specs must be considered in any implementation of this method:
	// * https://tools.ietf.org/html/rfc6749#rfc6749#section-4.1.2.1
	//   After completing its interaction with the resource owner, the
	//   authorization server directs the resource owner's user-agent back to
	//   the client.  The authorization server redirects the user-agent to the
	//   client's redirection endpoint previously established with the
	//   authorization server during the client registration process or when
	//   making the authorization request.
	// * https://tools.ietf.org/html/rfc6749#section-3.1.2.2 (everything MUST be implemented)
	WriteAuthorizeResponse(ctx context.Context, rw http.ResponseWriter, requester AuthorizeRequester, responder AuthorizeResponder)

	// NewAccessRequest creates a new access request object and validates
	// various parameters.
	//
	// The following specs must be considered in any implementation of this method:
	// * https://tools.ietf.org/html/rfc6749#section-3.2 (everything)
	// * https://tools.ietf.org/html/rfc6749#section-3.2.1 (everything)
	//
	// Furthermore the registered handlers should implement their specs accordingly.
	NewAccessRequest(ctx context.Context, req *http.Request, session Session) (AccessRequester, error)

	// NewAccessResponse creates a new access response and validates that access_token and token_type are set.
	//
	// The following specs must be considered in any implementation of this method:
	// https://tools.ietf.org/html/rfc6749#section-5.1
	NewAccessResponse(ctx context.Context, requester AccessRequester) (AccessResponder, error)

	// WriteAccessError writes an access request error response.
	//
	// The following specs must be considered in any implementation of this method:
	// * https://tools.ietf.org/html/rfc6749#section-5.2 (everything)
	WriteAccessError(ctx context.Context, rw http.ResponseWriter, requester Requester, err error)

	// WriteAccessResponse writes the access response.
	//
	// The following specs must be considered in any implementation of this method:
	// https://tools.ietf.org/html/rfc6749#section-5.1
	WriteAccessResponse(ctx context.Context, rw http.ResponseWriter, requester AccessRequester, responder AccessResponder)

	// NewDeviceRequest validate the OAuth 2.0 Device Authorization Flow Request
	//
	// The following specs must be considered in any implementation of this method:
	// * https://www.rfc-editor.org/rfc/rfc8628#section-3.1 (everything MUST be implemented)
	// Parameters sent without a value MUST be treated as if they were
	// omitted from the request.  The authorization server MUST ignore
	// unrecognized request parameters.  Request and response parameters
	// MUST NOT be included more than once.
	NewDeviceRequest(ctx context.Context, req *http.Request) (DeviceRequester, error)

	// NewDeviceResponse persists the DeviceCodeSession and UserCodeSession in the store
	//
	// The following specs must be considered in any implementation of this method:
	// * https://www.rfc-editor.org/rfc/rfc8628#section-3.2 (everything MUST be implemented)
	// In response, the authorization server generates a unique device
	// verification code and an end-user code that are valid for a limited
	// time
	NewDeviceResponse(ctx context.Context, requester DeviceRequester, session Session) (DeviceResponder, error)

	// WriteDeviceResponse return to the user both codes and
	// some configuration information in a JSON formatted manner
	//
	// The following specs must be considered in any implementation of this method:
	// * https://www.rfc-editor.org/rfc/rfc8628#section-3.2 (everything MUST be implemented)
	// Response is an HTTP response body using the
	// "application/json" format [RFC8259] with a 200 (OK) status code.
	WriteDeviceResponse(ctx context.Context, rw http.ResponseWriter, requester DeviceRequester, responder DeviceResponder)

	// NewRevocationRequest handles incoming token revocation requests and validates various parameters.
	//
	// The following specs must be considered in any implementation of this method:
	// https://tools.ietf.org/html/rfc7009#section-2.1
	NewRevocationRequest(ctx context.Context, r *http.Request) error

	// WriteRevocationResponse writes the revoke response.
	//
	// The following specs must be considered in any implementation of this method:
	// https://tools.ietf.org/html/rfc7009#section-2.2
	WriteRevocationResponse(ctx context.Context, rw http.ResponseWriter, err error)

	// IntrospectToken returns token metadata, if the token is valid. Tokens generated by the authorization endpoint,
	// such as the authorization code, can not be introspected.
	IntrospectToken(ctx context.Context, token string, tokenUse TokenUse, session Session, scope ...string) (TokenUse, AccessRequester, error)

	// NewIntrospectionRequest initiates token introspection as defined in
	// https://tools.ietf.org/html/rfc7662#section-2.1
	NewIntrospectionRequest(ctx context.Context, r *http.Request, session Session) (IntrospectionResponder, error)

	// WriteIntrospectionError responds with an error if token introspection failed as defined in
	// https://tools.ietf.org/html/rfc7662#section-2.3
	WriteIntrospectionError(ctx context.Context, rw http.ResponseWriter, err error)

	// WriteIntrospectionResponse responds with token metadata discovered by token introspection as defined in
	// https://tools.ietf.org/html/rfc7662#section-2.2
	WriteIntrospectionResponse(ctx context.Context, rw http.ResponseWriter, r IntrospectionResponder)

	// NewPushedAuthorizeRequest validates the request and produces an AuthorizeRequester object that can be stored
	NewPushedAuthorizeRequest(ctx context.Context, r *http.Request) (AuthorizeRequester, error)

	// NewPushedAuthorizeResponse executes the handlers and builds the response
	NewPushedAuthorizeResponse(ctx context.Context, ar AuthorizeRequester, session Session) (PushedAuthorizeResponder, error)

	// WritePushedAuthorizeResponse writes the PAR response
	WritePushedAuthorizeResponse(ctx context.Context, rw http.ResponseWriter, ar AuthorizeRequester, resp PushedAuthorizeResponder)

	// WritePushedAuthorizeError writes the PAR error
	WritePushedAuthorizeError(ctx context.Context, rw http.ResponseWriter, ar AuthorizeRequester, err error)
}

OAuth2Provider is an interface that enables you to write OAuth2 handlers with only a few lines of code. Check Fosite for an implementation of this interface.

type OmitRedirectScopeParamProvider

type OmitRedirectScopeParamProvider interface {
	// GetOmitRedirectScopeParam must be set to true if the scope query param is to be omitted
	// in the authorization's redirect URI
	GetOmitRedirectScopeParam(ctx context.Context) bool
}

OmitRedirectScopeParamProvider returns the provider for configuring the omit redirect scope param.

type OpenIDConnectClient

type OpenIDConnectClient interface {
	// GetRequestURIs is an array of request_uri values that are pre-registered by the RP for use at the OP. Servers MAY
	// cache the contents of the files referenced by these URIs and not retrieve them at the time they are used in a request.
	// OPs can require that request_uri values used be pre-registered with the require_request_uri_registration
	// discovery parameter.
	GetRequestURIs() []string

	// GetJSONWebKeys returns the JSON Web Key Set containing the public key used by the client to authenticate.
	GetJSONWebKeys() *jose.JSONWebKeySet

	// GetJSONWebKeys returns the URL for lookup of JSON Web Key Set containing the
	// public key used by the client to authenticate.
	GetJSONWebKeysURI() string

	// JWS [JWS] alg algorithm [JWA] that MUST be used for signing Request Objects sent to the OP.
	// All Request Objects from this Client MUST be rejected, if not signed with this algorithm.
	GetRequestObjectSigningAlgorithm() string

	// Requested Client Authentication method for the Token Endpoint. The options are client_secret_post,
	// client_secret_basic, private_key_jwt, and none.
	GetTokenEndpointAuthMethod() string

	// JWS [JWS] alg algorithm [JWA] that MUST be used for signing the JWT [JWT] used to authenticate the
	// Client at the Token Endpoint for the private_key_jwt authentication method.
	GetTokenEndpointAuthSigningAlgorithm() string
}

OpenIDConnectClient represents a client capable of performing OpenID Connect requests.

type PARStorage

type PARStorage interface {
	// CreatePARSession stores the pushed authorization request context. The requestURI is used to derive the key.
	CreatePARSession(ctx context.Context, requestURI string, request AuthorizeRequester) error
	// GetPARSession gets the push authorization request context. The caller is expected to merge the AuthorizeRequest.
	GetPARSession(ctx context.Context, requestURI string) (AuthorizeRequester, error)
	// DeletePARSession deletes the context.
	DeletePARSession(ctx context.Context, requestURI string) (err error)
}

Storage holds information needed to store and retrieve PAR context.

type PARStorageProvider

type PARStorageProvider interface {
	PARStorage() PARStorage
}

type PushedAuthorizeEndpointHandler

type PushedAuthorizeEndpointHandler interface {
	// HandlePushedAuthorizeRequest handles a pushed authorize endpoint request. To extend the handler's capabilities, the http request
	// is passed along, if further information retrieval is required. If the handler feels that he is not responsible for
	// the pushed authorize request, he must return nil and NOT modify session nor responder neither requester.
	HandlePushedAuthorizeEndpointRequest(ctx context.Context, requester AuthorizeRequester, responder PushedAuthorizeResponder) error
}

PushedAuthorizeEndpointHandler is the interface that handles PAR (https://datatracker.ietf.org/doc/html/rfc9126)

type PushedAuthorizeEndpointHandlers

type PushedAuthorizeEndpointHandlers []PushedAuthorizeEndpointHandler

PushedAuthorizeEndpointHandlers is a list of PushedAuthorizeEndpointHandler

func (*PushedAuthorizeEndpointHandlers) Append

Append adds an AuthorizeEndpointHandler to this list. Ignores duplicates based on reflect.TypeOf.

type PushedAuthorizeRequestConfigProvider

type PushedAuthorizeRequestConfigProvider interface {
	// GetPushedAuthorizeRequestURIPrefix is the request URI prefix. This is
	// usually 'urn:ietf:params:oauth:request_uri:'.
	GetPushedAuthorizeRequestURIPrefix(ctx context.Context) string

	// GetPushedAuthorizeContextLifespan is the lifespan of the short-lived PAR context.
	GetPushedAuthorizeContextLifespan(ctx context.Context) time.Duration

	// EnforcePushedAuthorize indicates if PAR is enforced. In this mode, a client
	// cannot pass authorize parameters at the 'authorize' endpoint. The 'authorize' endpoint
	// must contain the PAR request_uri.
	EnforcePushedAuthorize(ctx context.Context) bool
}

PushedAuthorizeRequestConfigProvider is the configuration provider for pushed authorization request.

type PushedAuthorizeRequestHandlersProvider

type PushedAuthorizeRequestHandlersProvider interface {
	// GetPushedAuthorizeEndpointHandlers returns the handlers.
	GetPushedAuthorizeEndpointHandlers(ctx context.Context) PushedAuthorizeEndpointHandlers
}

PushedAuthorizeEndpointHandlersProvider returns the provider for configuring the PAR handlers.

type PushedAuthorizeResponder

type PushedAuthorizeResponder interface {
	// GetRequestURI returns the request_uri
	GetRequestURI() string
	// SetRequestURI sets the request_uri
	SetRequestURI(requestURI string)
	// GetExpiresIn gets the expires_in
	GetExpiresIn() int
	// SetExpiresIn sets the expires_in
	SetExpiresIn(seconds int)

	// GetHeader returns the response's header
	GetHeader() (header http.Header)

	// AddHeader adds a header key value pair to the response
	AddHeader(key, value string)

	// SetExtra sets a key value pair for the response.
	SetExtra(key string, value interface{})

	// GetExtra returns a key's value.
	GetExtra(key string) interface{}

	// ToMap converts the response to a map.
	ToMap() map[string]interface{}
}

PushedAuthorizeResponder is the response object for PAR

type PushedAuthorizeResponse

type PushedAuthorizeResponse struct {
	RequestURI string `json:"request_uri"`
	ExpiresIn  int    `json:"expires_in"`
	Header     http.Header
	Extra      map[string]interface{}
}

PushedAuthorizeResponse is the response object for PAR

func (*PushedAuthorizeResponse) AddHeader

func (a *PushedAuthorizeResponse) AddHeader(key, value string)

AddHeader adds

func (*PushedAuthorizeResponse) GetExpiresIn

func (a *PushedAuthorizeResponse) GetExpiresIn() int

GetExpiresIn gets

func (*PushedAuthorizeResponse) GetExtra

func (a *PushedAuthorizeResponse) GetExtra(key string) interface{}

GetExtra gets

func (*PushedAuthorizeResponse) GetHeader

func (a *PushedAuthorizeResponse) GetHeader() http.Header

GetHeader gets

func (*PushedAuthorizeResponse) GetRequestURI

func (a *PushedAuthorizeResponse) GetRequestURI() string

GetRequestURI gets

func (*PushedAuthorizeResponse) SetExpiresIn

func (a *PushedAuthorizeResponse) SetExpiresIn(seconds int)

SetExpiresIn sets

func (*PushedAuthorizeResponse) SetExtra

func (a *PushedAuthorizeResponse) SetExtra(key string, value interface{})

SetExtra sets

func (*PushedAuthorizeResponse) SetRequestURI

func (a *PushedAuthorizeResponse) SetRequestURI(requestURI string)

SetRequestURI sets

func (*PushedAuthorizeResponse) ToMap

func (a *PushedAuthorizeResponse) ToMap() map[string]interface{}

ToMap converts to a map

type RFC6749Error

type RFC6749Error struct {
	ErrorField       string
	DescriptionField string
	HintField        string
	CodeField        int
	DebugField       string
	// contains filtered or unexported fields
}

func ErrorToRFC6749Error

func ErrorToRFC6749Error(err error) *RFC6749Error

func (*RFC6749Error) Cause

func (e *RFC6749Error) Cause() error

func (*RFC6749Error) Debug

func (e *RFC6749Error) Debug() string

func (RFC6749Error) Error

func (e RFC6749Error) Error() string

func (*RFC6749Error) GetDescription

func (e *RFC6749Error) GetDescription() string

GetDescription returns a more description description, combined with hint and debug (when available).

func (RFC6749Error) Is

func (e RFC6749Error) Is(err error) bool

func (RFC6749Error) MarshalJSON

func (e RFC6749Error) MarshalJSON() ([]byte, error)

func (*RFC6749Error) Reason

func (e *RFC6749Error) Reason() string

func (*RFC6749Error) RequestID

func (e *RFC6749Error) RequestID() string

func (*RFC6749Error) Sanitize deprecated

func (e *RFC6749Error) Sanitize() *RFC6749Error

Sanitize strips the debug field

Deprecated: Use WithExposeDebug instead.

func (*RFC6749Error) StackTrace

func (e *RFC6749Error) StackTrace() (trace errors.StackTrace)

StackTrace returns the error's stack trace.

func (*RFC6749Error) Status

func (e *RFC6749Error) Status() string

func (*RFC6749Error) StatusCode

func (e *RFC6749Error) StatusCode() int

func (*RFC6749Error) ToValues

func (e *RFC6749Error) ToValues() url.Values

func (*RFC6749Error) UnmarshalJSON

func (e *RFC6749Error) UnmarshalJSON(b []byte) error

func (RFC6749Error) Unwrap

func (e RFC6749Error) Unwrap() error

func (*RFC6749Error) WithDebug

func (e *RFC6749Error) WithDebug(debug string) *RFC6749Error

func (*RFC6749Error) WithDebugf

func (e *RFC6749Error) WithDebugf(debug string, args ...interface{}) *RFC6749Error

func (*RFC6749Error) WithDescription

func (e *RFC6749Error) WithDescription(description string) *RFC6749Error

func (*RFC6749Error) WithExposeDebug

func (e *RFC6749Error) WithExposeDebug(exposeDebug bool) *RFC6749Error

WithExposeDebug if set to true exposes debug messages

func (*RFC6749Error) WithHint

func (e *RFC6749Error) WithHint(hint string) *RFC6749Error

func (*RFC6749Error) WithHintIDOrDefaultf

func (e *RFC6749Error) WithHintIDOrDefaultf(ID string, def string, args ...interface{}) *RFC6749Error

WithHintIDOrDefaultf accepts the ID of the hint message

func (*RFC6749Error) WithHintTranslationID

func (e *RFC6749Error) WithHintTranslationID(ID string) *RFC6749Error

WithHintTranslationID accepts the ID of the hint message and should be paired with WithHint and WithHintf to add a default message and vaargs.

func (*RFC6749Error) WithHintf

func (e *RFC6749Error) WithHintf(hint string, args ...interface{}) *RFC6749Error

func (RFC6749Error) WithLegacyFormat

func (e RFC6749Error) WithLegacyFormat(useLegacyFormat bool) *RFC6749Error

func (*RFC6749Error) WithLocalizer

func (e *RFC6749Error) WithLocalizer(catalog i18n.MessageCatalog, lang language.Tag) *RFC6749Error

func (*RFC6749Error) WithTrace

func (e *RFC6749Error) WithTrace(err error) *RFC6749Error

func (RFC6749Error) WithWrap

func (e RFC6749Error) WithWrap(cause error) *RFC6749Error

func (*RFC6749Error) Wrap

func (e *RFC6749Error) Wrap(err error)

type RFC6749ErrorJson

type RFC6749ErrorJson struct {
	Name        string `json:"error"`
	Description string `json:"error_description"`
	Hint        string `json:"error_hint,omitempty"`
	Code        int    `json:"status_code,omitempty"`
	Debug       string `json:"error_debug,omitempty"`
}

RFC6749ErrorJson is a helper struct for JSON encoding/decoding of RFC6749Error.

type RedirectSecureCheckerProvider

type RedirectSecureCheckerProvider interface {
	// GetRedirectSecureChecker returns the redirect URL security validator.
	GetRedirectSecureChecker(ctx context.Context) func(context.Context, *url.URL) bool
}

RedirectSecureCheckerProvider returns the provider for configuring the redirect URL security validator.

type RedirectURIMatcher

type RedirectURIMatcher func(rawurl string, client Client) (*url.URL, error)

RedirectURIMatcher resolves a requested redirect URI against the client's registered redirect URIs.

type RedirectURIMatcherProvider

type RedirectURIMatcherProvider interface {
	// GetRedirectURIMatcher returns the redirect URI matcher.
	GetRedirectURIMatcher(ctx context.Context) RedirectURIMatcher
}

RedirectURIMatcherProvider returns the provider for configuring redirect URI matching.

type RefreshTokenLifespanProvider

type RefreshTokenLifespanProvider interface {
	// GetRefreshTokenLifespan returns the refresh token lifespan.
	GetRefreshTokenLifespan(ctx context.Context) time.Duration
}

RefreshTokenLifespanProvider returns the provider for configuring the refresh token lifespan.

type RefreshTokenScopesProvider

type RefreshTokenScopesProvider interface {
	// GetRefreshTokenScopes returns the refresh token scopes.
	GetRefreshTokenScopes(ctx context.Context) []string
}

RefreshTokenScopesProvider returns the provider for configuring the refresh token scopes.

type Request

type Request struct {
	ID                string       `json:"id" gorethink:"id"`
	RequestedAt       time.Time    `json:"requestedAt" gorethink:"requestedAt"`
	Client            Client       `json:"client" gorethink:"client"`
	RequestedScope    Arguments    `json:"scopes" gorethink:"scopes"`
	GrantedScope      Arguments    `json:"grantedScopes" gorethink:"grantedScopes"`
	Form              url.Values   `json:"form" gorethink:"form"`
	Session           Session      `json:"session" gorethink:"session"`
	RequestedAudience Arguments    `json:"requestedAudience"`
	GrantedAudience   Arguments    `json:"grantedAudience"`
	Lang              language.Tag `json:"-"`
}

Request is an implementation of Requester

func NewRequest

func NewRequest() *Request

func (*Request) AppendRequestedAudience

func (a *Request) AppendRequestedAudience(audience string)

func (*Request) AppendRequestedScope

func (a *Request) AppendRequestedScope(scope string)

func (*Request) GetClient

func (a *Request) GetClient() Client

func (*Request) GetGrantedAudience

func (a *Request) GetGrantedAudience() Arguments

func (*Request) GetGrantedScopes

func (a *Request) GetGrantedScopes() Arguments

func (*Request) GetID

func (a *Request) GetID() string

func (*Request) GetLang

func (a *Request) GetLang() language.Tag

func (*Request) GetRequestForm

func (a *Request) GetRequestForm() url.Values

func (*Request) GetRequestedAt

func (a *Request) GetRequestedAt() time.Time

func (*Request) GetRequestedAudience

func (a *Request) GetRequestedAudience() (audience Arguments)

func (*Request) GetRequestedScopes

func (a *Request) GetRequestedScopes() Arguments

func (*Request) GetResource

func (a *Request) GetResource() (string, error)

func (*Request) GetSession

func (a *Request) GetSession() Session

func (*Request) GrantAudience

func (a *Request) GrantAudience(audience string)

func (*Request) GrantScope

func (a *Request) GrantScope(scope string)

func (*Request) Merge

func (a *Request) Merge(request Requester)

func (*Request) Sanitize

func (a *Request) Sanitize(allowedParameters []string) Requester

func (*Request) SetID

func (a *Request) SetID(id string)

func (*Request) SetRequestedAudience

func (a *Request) SetRequestedAudience(s Arguments)

func (*Request) SetRequestedScopes

func (a *Request) SetRequestedScopes(s Arguments)

func (*Request) SetSession

func (a *Request) SetSession(session Session)

type Requester

type Requester interface {
	// SetID sets the unique identifier.
	SetID(id string)

	// GetID returns a unique identifier.
	GetID() string

	// GetRequestedAt returns the time the request was created.
	GetRequestedAt() (requestedAt time.Time)

	// GetClient returns the request's client.
	GetClient() (client Client)

	// GetRequestedScopes returns the request's scopes.
	GetRequestedScopes() (scopes Arguments)

	// GetRequestedAudience returns the requested audiences for this request.
	GetRequestedAudience() (audience Arguments)

	// SetRequestedScopes sets the request's scopes.
	SetRequestedScopes(scopes Arguments)

	// SetRequestedAudience sets the requested audience.
	SetRequestedAudience(audience Arguments)

	// AppendRequestedScope appends a scope to the request.
	AppendRequestedScope(scope string)

	// GetGrantedScopes returns all granted scopes.
	GetGrantedScopes() (grantedScopes Arguments)

	// GetGrantedAudience returns all granted audiences.
	GetGrantedAudience() (grantedAudience Arguments)

	// GrantScope marks a request's scope as granted.
	GrantScope(scope string)

	// GrantAudience marks a request's audience as granted.
	GrantAudience(audience string)

	// GetSession returns a pointer to the request's session or nil if none is set.
	GetSession() (session Session)

	// SetSession sets the request's session pointer.
	SetSession(session Session)

	// GetRequestForm returns the request's form input.
	GetRequestForm() url.Values

	// GetResource returns the RFC 8707 resource.
	GetResource() (resource string, err error)

	// Merge merges the argument into the method receiver.
	Merge(requester Requester)

	// Sanitize returns a sanitized clone of the request which can be used for storage.
	Sanitize(allowedParameters []string) Requester
}

Requester is an abstract interface for handling requests in Fosite.

type ResponseModeClient

type ResponseModeClient interface {
	// GetResponseMode returns the response modes that client is allowed to send
	GetResponseModes() []ResponseModeType
}

ResponseModeClient represents a client capable of handling response_mode

type ResponseModeHandler

type ResponseModeHandler interface {
	// ResponseModes returns a set of supported response modes handled
	// by the interface implementation.
	//
	// In an authorize request with any of the provide response modes
	// methods `WriteAuthorizeResponse` and `WriteAuthorizeError` will be
	// invoked to write the successful or error authorization responses respectively.
	ResponseModes() ResponseModeTypes

	// WriteAuthorizeResponse writes successful responses
	//
	// Following headers are expected to be set by default:
	// header.Set("Cache-Control", "no-store")
	// header.Set("Pragma", "no-cache")
	WriteAuthorizeResponse(ctx context.Context, rw http.ResponseWriter, ar AuthorizeRequester, resp AuthorizeResponder)

	// WriteAuthorizeError writes error responses
	//
	// Following headers are expected to be set by default:
	// header.Set("Cache-Control", "no-store")
	// header.Set("Pragma", "no-cache")
	WriteAuthorizeError(ctx context.Context, rw http.ResponseWriter, ar AuthorizeRequester, err error)
}

ResponseModeHandler provides a contract for handling custom response modes

type ResponseModeHandlerExtensionProvider

type ResponseModeHandlerExtensionProvider interface {
	// GetResponseModeHandlerExtension returns the response mode handler extension.
	GetResponseModeHandlerExtension(ctx context.Context) ResponseModeHandler
}

ResponseModeHandlerExtensionProvider returns the provider for configuring the response mode handler extension.

type ResponseModeType

type ResponseModeType string

type ResponseModeTypes

type ResponseModeTypes []ResponseModeType

func (ResponseModeTypes) Has

type RevocationHandler

type RevocationHandler interface {
	// RevokeToken handles access and refresh token revocation.
	RevokeToken(ctx context.Context, token string, tokenType TokenType, client Client) error
}

RevocationHandler is the interface that allows token revocation for an OAuth2.0 provider. https://tools.ietf.org/html/rfc7009

RevokeToken is invoked after a new token revocation request is parsed.

https://tools.ietf.org/html/rfc7009#section-2.1 If the particular token is a refresh token and the authorization server supports the revocation of access tokens, then the authorization server SHOULD also invalidate all access tokens based on the same authorization grant (see Implementation Note). If the token passed to the request is an access token, the server MAY revoke the respective refresh token as well.

type RevocationHandlers

type RevocationHandlers []RevocationHandler

RevocationHandlers is a list of RevocationHandler

func (*RevocationHandlers) Append

Append adds an RevocationHandler to this list. Ignores duplicates based on reflect.TypeOf.

type RevocationHandlersProvider

type RevocationHandlersProvider interface {
	// GetRevocationHandlers returns the revocation handlers.
	GetRevocationHandlers(ctx context.Context) RevocationHandlers
}

RevocationHandlersProvider returns the provider for configuring the revocation handlers.

type RotatedGlobalSecretsProvider

type RotatedGlobalSecretsProvider interface {
	// GetRotatedGlobalSecrets returns the rotated global secrets.
	GetRotatedGlobalSecrets(ctx context.Context) ([][]byte, error)
}

RotatedGlobalSecretsProvider returns the provider for configuring the rotated global secrets.

type SanitationAllowedProvider

type SanitationAllowedProvider interface {
	// GetSanitationWhiteList is a whitelist of form values that are required by the token endpoint. These values
	// are safe for storage in a database (cleartext).
	GetSanitationWhiteList(ctx context.Context) []string
}

SanitationAllowedProvider returns the provider for configuring the sanitation white list.

type ScopeStrategy

type ScopeStrategy func(haystack []string, needle string) bool

ScopeStrategy is a strategy for matching scopes.

type ScopeStrategyProvider

type ScopeStrategyProvider interface {
	// GetScopeStrategy returns the scope strategy.
	GetScopeStrategy(ctx context.Context) ScopeStrategy
}

ScopeStrategyProvider returns the provider for configuring the scope strategy.

type SendDebugMessagesToClientsProvider

type SendDebugMessagesToClientsProvider interface {
	// GetSendDebugMessagesToClients returns the send debug messages to clients.
	GetSendDebugMessagesToClients(ctx context.Context) bool
}

SendDebugMessagesToClientsProvider returns the provider for configuring the send debug messages to clients.

type Session

type Session interface {
	// SetExpiresAt sets the expiration time of a token.
	//
	//  session.SetExpiresAt(fosite.AccessToken, time.Now().UTC().Add(time.Hour))
	SetExpiresAt(key TokenType, exp time.Time)

	// GetExpiresAt returns the expiration time of a token if set, or time.IsZero() if not.
	//
	//  session.GetExpiresAt(fosite.AccessToken)
	GetExpiresAt(key TokenType) time.Time

	// GetUsername returns the username, if set. This is optional and only used during token introspection.
	GetUsername() string

	// GetSubject returns the subject, if set. This is optional and only used during token introspection.
	GetSubject() string

	// Clone clones the session.
	Clone() Session
}

Session is an interface that is used to store session data between OAuth2 requests. It can be used to look up when a session expires or what the subject's name was.

type Storage

type Storage interface {
	FositeClientManager() ClientManager
}

Storage defines fosite's minimal storage interface.

type SupportedRequestObjectSigningAlgorithmsProvider

type SupportedRequestObjectSigningAlgorithmsProvider interface {
	// GetSupportedRequestObjectSigningAlgorithms returns the JWS "alg" values accepted for request objects
	// passed via the OpenID Connect "request" and "request_uri" authorization request parameters. An empty
	// list means every algorithm supported by the implementation is accepted.
	GetSupportedRequestObjectSigningAlgorithms(ctx context.Context) []string
}

SupportedRequestObjectSigningAlgorithmsProvider returns the provider for configuring the JWS algorithms accepted for OpenID Connect request objects.

type TokenEndpointHandler

type TokenEndpointHandler interface {
	// PopulateTokenEndpointResponse is responsible for setting return values and should only be executed if
	// the handler's HandleTokenEndpointRequest did not return ErrUnknownRequest.
	PopulateTokenEndpointResponse(ctx context.Context, requester AccessRequester, responder AccessResponder) error

	// HandleTokenEndpointRequest handles an authorize request. If the handler is not responsible for handling
	// the request, this method should return ErrUnknownRequest and otherwise handle the request.
	HandleTokenEndpointRequest(ctx context.Context, requester AccessRequester) error

	// CanSkipClientAuth indicates if client authentication can be skipped. By default it MUST be false, unless you are
	// implementing extension grant type, which allows unauthenticated client. CanSkipClientAuth must be called
	// before HandleTokenEndpointRequest to decide, if AccessRequester will contain authenticated client.
	CanSkipClientAuth(ctx context.Context, requester AccessRequester) bool

	// CanHandleRequest indicates, if TokenEndpointHandler can handle this request or not. If true,
	// HandleTokenEndpointRequest can be called.
	CanHandleTokenEndpointRequest(ctx context.Context, requester AccessRequester) bool
}

type TokenEndpointHandlers

type TokenEndpointHandlers []TokenEndpointHandler

TokenEndpointHandlers is a list of TokenEndpointHandler

func (*TokenEndpointHandlers) Append

Append adds an TokenEndpointHandler to this list. Ignores duplicates based on reflect.TypeOf.

type TokenEndpointHandlersProvider

type TokenEndpointHandlersProvider interface {
	// GetTokenEndpointHandlers returns the token endpoint handlers.
	GetTokenEndpointHandlers(ctx context.Context) TokenEndpointHandlers
}

TokenEndpointHandlersProvider returns the provider for configuring the token endpoint handlers.

type TokenEntropyProvider

type TokenEntropyProvider interface {
	// GetTokenEntropy returns the token entropy.
	GetTokenEntropy(ctx context.Context) int
}

TokenEntropyProvider returns the provider for configuring the token entropy.

type TokenIntrospectionHandlers

type TokenIntrospectionHandlers []TokenIntrospector

TokenIntrospectionHandlers is a list of TokenValidator

func (*TokenIntrospectionHandlers) Append

Append adds an AccessTokenValidator to this list. Ignores duplicates based on reflect.TypeOf.

type TokenIntrospectionHandlersProvider

type TokenIntrospectionHandlersProvider interface {
	// GetTokenIntrospectionHandlers returns the token introspection handlers.
	GetTokenIntrospectionHandlers(ctx context.Context) TokenIntrospectionHandlers
}

TokenIntrospectionHandlersProvider returns the provider for configuring the token introspection handlers.

type TokenIntrospector

type TokenIntrospector interface {
	IntrospectToken(ctx context.Context, token string, tokenUse TokenUse, accessRequest AccessRequester, scopes []string) (TokenUse, error)
}

type TokenType

type TokenType string

type TokenURLProvider

type TokenURLProvider interface {
	// GetTokenURLs returns the token URL.
	GetTokenURLs(ctx context.Context) []string
}

type TokenUse

type TokenUse = TokenType

type Transactional

type Transactional interface {
	Transaction(ctx context.Context, fn func(ctx context.Context) error) error
}

Transactional is an interface that a storage provider has to implement to ensure atomicity for certain flows that require transactional semantics. If the storage provider cannot provide transactional semantics, it still needs to implement this interface as a no-op. It is expected that the storage provider will examine context for an existing transaction each time a database operation is to be performed.

An implementation of Transaction should attempt to initiate a new transaction and store that under a unique key in the context so it will be passed on by fn to all storage provider methods. If fn returns an error, the transaction must be rolled back, otherwise it must be committed. It is permitted to automatically retry the transaction in case of specific errors. Fosite will always pass an idempotent function to Transaction.

type UseLegacyErrorFormatProvider

type UseLegacyErrorFormatProvider interface {
	// GetUseLegacyErrorFormat returns whether to use the legacy error format.
	//
	// DEPRECATED: Do not use this flag anymore.
	GetUseLegacyErrorFormat(ctx context.Context) bool
}

UseLegacyErrorFormatProvider returns the provider for configuring whether to use the legacy error format.

DEPRECATED: Do not use this flag anymore.

type UserCodeProvider

type UserCodeProvider interface {
	GetUserCodeLength(ctx context.Context) int
	GetUserCodeSymbols(ctx context.Context) []rune
}

DeviceAndUserCodeLifespanProvider returns the provider for configuring the device and user code lifespan

type UserCodeState

type UserCodeState int16

type VerifiableCredentialsNonceLifespanProvider

type VerifiableCredentialsNonceLifespanProvider interface {
	// GetNonceLifespan returns the nonce lifespan.
	GetVerifiableCredentialsNonceLifespan(ctx context.Context) time.Duration
}

VerifiableCredentialsNonceLifespanProvider returns the provider for configuring the access token lifespan.

Directories

Path Synopsis
Package compose provides various objects which can be used to instantiate OAuth2Providers with different functionality.
Package compose provides various objects which can be used to instantiate OAuth2Providers with different functionality.
handler
par
Package internal is a generated GoMock package.
Package internal is a generated GoMock package.
gen
token
jwt

Jump to

Keyboard shortcuts

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