protocol

package
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Feb 13, 2023 License: Apache-2.0 Imports: 12 Imported by: 0

Documentation

Overview

Package protocol provides ...

Package protocol provides ...

Package protocol provides ...

Package protocol provides ...

Package protocol provides ...

Package protocol provides ...

Package protocol provides ...

Package protocol provides ...

Package protocol provides ...

Package protocol provides ...

Package protocol provides ...

Package protocol provides ...

Package protocol provides ...

Index

Constants

View Source
const (
	// "code" for requesting an authorization code
	ResponseTypeCode ResponseType = "code"
	// "token" for requesting an access token (implicit grant)
	ResponseTypeToken ResponseType = "token"
	// "id_token" for requesting an oidc on OAuth2
	// https://openid.net/specs/oauth-v2-multiple-response-types-1_0.html#id_token
	ResponseTypeIDToken ResponseType = "id_token"
	// The Response Type none SHOULD NOT be combined with other Response Types.
	// https://openid.net/specs/oauth-v2-multiple-response-types-1_0.html#none
	ResponseTypeNone ResponseType = "none"
	// "device" is custom response_type for Device Code Flow
	ResponseTypeDevice = "device"

	ResponseTypeCodeToken        = "code token"
	ResponseTypeCodeIDToken      = "code id_token"
	ResponseTypeTokenIDToken     = "token id_token"
	ResponseTypeCodeTokenIDToken = "code token id_token"
)

Response type list, The following table lists the correspondence between response_type values that the Client will use and grant_type values that MUST be included in the registered grant_types list

code: authorization_code
id_token: implicit
token id_token: implicit
code id_token: authorization_code, implicit
code token: authorization_code, implicit
code token id_token: authorization_code, implicit
View Source
const (
	// A web application is a confidential client running on a web server.  Resource owners access the client
	// via an HTML user interface rendered in a user-agent on the device used by the resource owner.  The
	// client credentials as well as any access token issued to the client are stored on the web server and
	// are not exposed to or accessible by the resource owner.
	ClientAppTypeWeb = "web"
	// A user-agent-based application is a public client in which the client code is downloaded from a web
	// server and executes within a user-agent (e.g., web browser) on the device used by the resource owner.
	// Protocol data and credentials are easily accessible (and often visible) to the resource owner. Since
	// such applications reside within the user-agent, they can make seamless use of the user-agent
	// capabilities when requesting authorization.
	ClientAppTypeUserAgent = "useragent"
	// A native application is a public client installed and executed on the device used by the resource owner.
	// Protocol data and credentials are accessible to the resource owner. It is assumed that any client
	// authentication credentials included in the application can be extracted. On the other hand, dynamically
	// issued credentials such as access tokens or refresh tokens can receive an acceptable level of protection.
	// At a minimum, these credentials are protected from hostile servers with which the application may
	// interact.  On some platforms, these credentials might be protected from other applications residing on
	// the same device.
	ClientAppTypeNative = "native"
)

client profile list

View Source
const (
	// The value of the "client_assertion" parameter contains a single JWT.  It MUST NOT contain more than one
	// JWT.
	ClientAssertionTypeJWTBearer = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"
	// The value of the "client_assertion" parameter MUST contain a single SAML 2.0 Assertion.  The SAML
	// Assertion XML data MUST be encoded using base64url, where the encoding adheres to the definition in
	// Section 5 of RFC 4648 [RFC4648] and where the padding bits are set to zero.  To avoid the need for
	// subsequent encoding steps (by "application/x-www-form-urlencoded" [W3C.REC-html401-19991224], for
	// example), the base64url-encoded data SHOULD NOT be line wrapped and pad characters ("=") SHOULD NOT
	// be included.
	ClientAssertionTypeSMAL2Bearer = "urn:ietf:params:oauth:client-assertion-type:saml2-bearer"
)

assertion type list

Variables

View Source
var (
	// https://www.rfc-editor.org/rfc/rfc6750.html#section-3.1
	ErrInvalidRequest = Error{
		ErrorCode:   "invalid_request",
		Description: "The request is missing a required parameter, includes an invalid parameter value, includes a parameter more than once, or is otherwise malformed.",
		// contains filtered or unexported fields
	}
	ErrInvalidToken = Error{
		ErrorCode:   "invalid_token",
		Description: "The access token provided is expired, revoked, malformed, or invalid for other reasons.",
		// contains filtered or unexported fields
	}
	ErrInsufficientScope = Error{
		ErrorCode:   "insufficient_scope",
		Description: "The request requires higher privileges than provided by the access token.",
		// contains filtered or unexported fields
	}
	// https://www.rfc-editor.org/rfc/rfc7009.html#section-2.2.1
	ErrUnsupportedTokenType = Error{
		ErrorCode:   "unsupported_token_type",
		Description: "The authorization server does not support the revocation of the presented token type.",
		// contains filtered or unexported fields
	}
	ErrUnauthorizedClient = Error{
		ErrorCode:   "unauthorized_client",
		Description: "The client is not authorized to request a token using this method.",
		// contains filtered or unexported fields
	}
	ErrAccessDenied = Error{
		ErrorCode:   "access_denied",
		Description: "The resource owner or authorization server denied the request.",
		// contains filtered or unexported fields
	}
	ErrUnsupportedResponseType = Error{
		ErrorCode:   "unsupported_response_type",
		Description: "The authorization server does not support obtaining a token using this method.",
		// contains filtered or unexported fields
	}
	ErrInvalidScope = Error{
		ErrorCode:   "invalid_scope",
		Description: "The requested scope is invalid, unknown, or malformed.",
		// contains filtered or unexported fields
	}
	ErrServerError = Error{
		ErrorCode:   "server_error",
		Description: "The authorization server encountered an unexpected condition that prevented it from fulfilling the request.",
		// contains filtered or unexported fields
	}
	ErrTemporarilyUnavailable = Error{
		ErrorCode:   "temporarily_unavailable",
		Description: "The authorization server is currently unable to handle the request due to a temporary overloading or maintenance of the server.",
		// contains filtered or unexported fields
	}
	ErrUnsupportedGrantType = Error{
		ErrorCode:   "unsupported_grant_type",
		Description: "The authorization grant type is not supported by the authorization server.",
		// contains filtered or unexported fields
	}
	ErrInvalidGrant = Error{
		ErrorCode:   "invalid_grant",
		Description: "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.",
		// contains filtered or unexported fields
	}
	ErrInvalidClient = Error{
		ErrorCode:   "invalid_client",
		Description: "Client authentication failed (e.g., unknown client, no client authentication included, or unsupported authentication method).",
		// contains filtered or unexported fields
	}
	// Device Access Token Response
	// https://datatracker.ietf.org/doc/html/rfc8628#section-3.5
	ErrAuthorizationPending = Error{
		ErrorCode:   "authorization_pending",
		Description: "The authorization request is still pending as the end user hasn't yet completed the user-interaction steps.",
		// contains filtered or unexported fields
	}
	ErrSlowDown = Error{
		ErrorCode:   "slow_down",
		Description: "the authorization request is still pending and polling should continue, but the interval MUST be increased by 5 seconds for this and all subsequent requests.",
		// contains filtered or unexported fields
	}
	ErrExpiredToken = Error{
		ErrorCode:   "expired_token",
		Description: "The device_code has expired, and the device authorization session has concluded.",
		// contains filtered or unexported fields
	}
	// https://www.rfc-editor.org/rfc/rfc8707.html#name-resource-parameter
	ErrInvalidTarget = Error{
		ErrorCode:   "invalid_target",
		Description: "The requested resource is invalid, missing, unknown, or malformed.",
		// contains filtered or unexported fields
	}
	// https://www.rfc-editor.org/rfc/rfc9200.html#section-5.8.3
	ErrUnsupportedPopKey = Error{
		ErrorCode:   "unsupported_pop_key",
		Description: "The client submits an asymmetric key in the token request that the RS cannot process.",
		// contains filtered or unexported fields
	}
	ErrIncompatibleAceProfiles = Error{
		ErrorCode:   "incompatible_ace_profiles",
		Description: "The client and the RS it has requested an access token for do not share a common profile.",
		// contains filtered or unexported fields
	}
	// https://datatracker.ietf.org/doc/draft-ietf-oauth-rar/22/
	ErrInvalidAuthorizationDetails = Error{
		ErrorCode:   "invalid_authorization_details",
		Description: "Unknown authorization details type or authorization details not conforming to the respective type definition.",
		// contains filtered or unexported fields
	}
	// Authentication Error Response
	// https://openid.net/specs/openid-connect-core-1_0.html#AuthError
	ErrInteractionRequired = Error{
		ErrorCode:   "interaction_required",
		Description: "The Authorization Server requires End-User interaction of some form to proceed, but prompt is none.",
		// contains filtered or unexported fields
	}
	ErrLoginRequired = Error{
		ErrorCode:   "login_required",
		Description: "The Authorization Server requires End-User authentication.",
		// contains filtered or unexported fields
	}
	ErrAccountSelectionRequired = Error{
		ErrorCode:   "account_selection_required",
		Description: "The End-User is REQUIRED to select a session at the Authorization Server.",
		// contains filtered or unexported fields
	}
	ErrConsentRequired = Error{
		ErrorCode:   "consent_required",
		Description: "The Authorization Server requires End-User consent.",
		// contains filtered or unexported fields
	}
	ErrInvalidRequestURI = Error{
		ErrorCode:   "invalid_request_uri",
		Description: "The request_uri in the Authorization Request returns an error or contains invalid data.",
		// contains filtered or unexported fields
	}
	ErrInvalidRequestObject = Error{
		ErrorCode:   "invalid_request_object",
		Description: "The request parameter contains an invalid Request Object.",
		// contains filtered or unexported fields
	}
	ErrRequestNotSupported = Error{
		ErrorCode:   "request_not_supported",
		Description: "Does not support use of the request parameter",
		// contains filtered or unexported fields
	}
	ErrRequestURINotSupported = Error{
		ErrorCode:   "request_uri_not_supported",
		Description: "Does not support use of the request_uri parameter",
		// contains filtered or unexported fields
	}
	ErrRegistrationNotSupported = Error{
		ErrorCode:   "registration_not_supported",
		Description: "Does not support use of the registration parameter",
		// contains filtered or unexported fields
	}
)

error code list

View Source
var CheckSessionIframe *template.Template

CheckSessionIframe check session endpoint iframe

View Source
var DefaultExpirations = Expirations{
	CodeExpiration:         600,
	AccessTokenExpiration:  3600,
	RefreshTokenExpiration: 3600,
	IDTokenExpiration:      3600,
	PollingInterval:        5,
}

DefaultExpirations default expirations

View Source
var ErrNotFoundEntity = errors.New("not found entity")

ErrNotFoundEntity not found object

Functions

func IsExtensionGrants

func IsExtensionGrants(grantType GrantType) bool

IsExtensionGrants judge GrantType whether extension grants

func IsValidDisplay

func IsValidDisplay(opt Display) bool

IsValidDisplay whether display option is valid

func IsValidPrompt

func IsValidPrompt(opt Prompt) bool

IsValidPrompt whether prompt option is valid

func OutputHTML

func OutputHTML(resp *Response, w http.ResponseWriter, r *http.Request) error

OutputHTML encodes the Response to HTML and writes to the http.ResponseWriter

func OutputJSON

func OutputJSON(resp *Response, w http.ResponseWriter, r *http.Request) error

OutputJSON encodes the Response to JSON and writes to the http.ResponseWriter

Types

type AccessData

type AccessData struct {
	*AccessRequest
	// final authorization result
	UserData  *UserInfo         `json:"user_data"`
	Scope     SpaceDelimitedArr `json:"scope"`
	CreatedAt time.Time         `json:"created_at"`

	AccessToken  string `json:"access_token"`
	TokenType    string `json:"token_type"`
	ExpiresIn    int    `json:"expires_in"`
	RefreshToken string `json:"refresh_token"`

	Client Client `json:"-"`
}

AccessData access data

type AccessRequest

type AccessRequest struct {
	GrantType GrantType `json:"grant_type"`

	// authorization_code
	AuthorizationCodeReq *GrantAuthorizationCodeRequest `json:"authorization_code_req,omitempty"`
	// refresh_token
	RefreshTokenReq *GrantRefreshTokenRequest `json:"refresh_token_req,omitempty"`
	// client_credentials nothing todo
	ClientCredentialsReq *GrantClientCredentialsRequest `json:"client_credentials_req,omitempty"`
	// password
	PasswordReq *GrantPasswordRequest `json:"password_req,omitempty"`
	// implicit
	ImplicitReq *GrantImplicitRequest `json:"implicit_req,omitempty"`
	// urn:ietf:params:oauth:grant-type:jwt-bearer
	JwtBearerReq *GrantJwtBearerRequest `json:"jwt_bearer_req,omitempty"`
	// urn:ietf:params:oauth:grant-type:token-exchange
	TokenExchangeReq *GrantTokenExchangeRequest `json:"token_exchange_req,omitempty"`
	// urn:ietf:params:oauth:grant-type:device_code
	DeviceCodeReq *GrantDeviceCodeRequest `json:"device_code_req,omitempty"`
	// urn:ietf:params:oauth:grant-type:saml2-bearer
	Saml2BearerReq *GrantSaml2BearerRequest `json:"saml2_bearer_req,omitempty"`

	Issuer          string         `json:"-" schema:"-"` // dynamic issuer
	Client          Client         `json:"-" schema:"-"` // client
	GenerateRefresh bool           `json:"-" schema:"-"` // should generate refresh_token
	AccessData      *AccessData    `json:"-" schema:"-"` // previous access data
	UserID          string         `json:"user_id" schema:"-"`
	AuthorizeData   *AuthorizeData `json:"authorize_data,omitempty" schema:"-"`
}

AccessRequest is a request for access tokens

type Address

type Address struct {
	// Full mailing address, formatted for display or use on a mailing label. This field MAY contain multiple lines, separated by
	// newlines. Newlines can be represented either as a carriage return/line feed pair ("\r\n") or as a single line feed character
	// ("\n").
	Formatted string `json:"formatted,omitempty" structs:"promoted,omitempty"`
	// Full street address component, which MAY include house number, street name, Post Office Box, and multi-line extended street
	// address information. This field MAY contain multiple lines, separated by newlines. Newlines can be represented either as a
	// carriage return/line feed pair ("\r\n") or as a single line feed character ("\n").
	StreetAddress string `json:"street_address,omitempty" structs:"street_address,omitempty"`
	// City or locality component.
	Locality string `json:"locality,omitempty" structs:"locality,omitempty"`
	// State, province, prefecture, or region component.
	Region string `json:"region,omitempty" structs:"region,omitempty"`
	// Zip code or postal code component.
	PostalCode string `json:"postal_code,omitempty" structs:"postal_code,omitempty"`
	// Country name component.
	Country string `json:"country,omitempty" structs:"country,omitempty"`
}

Address The Address Claim represents a physical mailing address.

type AuthorizeData

type AuthorizeData struct {
	*AuthorizeRequest

	ExpiresIn int       `json:"expires_in"`
	CreatedAt time.Time `json:"created_at"`
}

AuthorizeData authorize data

type AuthorizeRequest

type AuthorizeRequest struct {
	// required & recommended
	ResponseType SpaceDelimitedArr `schema:"response_type" json:"response_type"`
	ClientID     string            `schema:"client_id" json:"client_id"`
	RedirectURI  string            `schema:"redirect_uri" json:"redirect_uri"`
	State        string            `schema:"state" json:"state"`
	Scope        SpaceDelimitedArr `schema:"scope" json:"scope"`
	// openid optional
	Nonce        string            `schema:"nonce" json:"nonce,omitempty"`
	ResponseMode ResponseMode      `schema:"response_mode" json:"response_mode,omitempty"`
	Display      Display           `schema:"display" json:"display,omitempty"`
	Prompt       SpaceDelimitedArr `schema:"prompt" json:"prompt,omitempty"`
	MaxAge       int               `schema:"max_age" json:"max_age,omitempty"`
	UILocales    Locales           `schema:"ui_locales" json:"ui_locales,omitempty"`
	IDTokenHint  string            `schema:"id_token_hint" json:"id_token_hint,omitempty"`
	LoginHint    string            `schema:"login_hint" json:"login_hint,omitempty"`
	ACRValues    []string          `schema:"acr_values" json:"acr_values,omitempty"`
	// code challenge
	CodeChallenge       string              `schema:"code_challenge" json:"code_challenge,omitempty"`
	CodeChallengeMethod CodeChallengeMethod `schema:"code_challenge_method" json:"code_challenge_method,omitempty"`
	// request object
	Request string `schema:"request" json:"request,omitempty"`

	Issuer        string `schema:"-" json:"-"` // dynamic issuer
	Client        Client `schema:"-" json:"-"`
	UserID        string `schema:"-" json:"user_id,omitempty"` // logined userID
	OpenID        bool   `schema:"-" json:"open_id,omitempty"`
	OfflineAccess bool   `schema:"-" json:"offline_access,omitempty"`
}

AuthorizeRequest An Authentication Request is an OAuth 2.0 Authorization Request that requests that the End-User be authenticated by the Authorization Server. https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest

type CheckSessionRequest

type CheckSessionRequest struct {
	ClientID string `schema:"client_id"`

	Issuer    string `schema:"-"` // dynamic issuer
	Origin    string `schema:"-"`
	ExpiresIn int    `schema:"-"`
}

CheckSessionRequest check_session_iframe endpoint

type ClaimType

type ClaimType string

ClaimType the Claim Types that the OpenID Provider supports

const (
	// Claims that are directly asserted by the OpenID Provider.
	ClaimTypeNormal ClaimType = "normal"
	// Claims that are asserted by a Claims Provider other than the OpenID Provider but are returned
	// by OpenID Provider.
	ClaimTypeAggregated ClaimType = "aggregated"
	// Claims that are asserted by a Claims Provider other than the OpenID Provider but are returned
	// as references by the OpenID Provider.
	ClaimTypeDistributed ClaimType = "distributed"
)

claim type list

type Client

type Client interface {
	// ClientID return client id
	ClientID() string
	// ClientSecret return client secret, NOTE public client should not return secret key
	ClientSecret() string
	// ClientType client type
	ClientType() ClientType
	// RedirectURI return client redirect uri, multiple URLs by comma-separating.
	// see https://www.rfc-editor.org/rfc/rfc6749#section-3.1.2
	RedirectURI() string
	// ResponseTypes allowed authorize type
	ResponseTypes() []ResponseType
	// GrantTypes grant types
	GrantTypes() []GrantType
	// IsScopeAllowed allowed custom unknown scopes
	IsScopeAllowed(scope string) bool

	// PrivateKey loads the client private key
	PrivateKey() (crypto.Signer, error)
	// JWTSigningMethod sign with idtoken
	JWTSigningMethod() jwt.SigningMethod
	// DeviceAuthPath device authorize path
	DeviceAuthPath() string
	// ExpirationOptions client expirations, seconds
	ExpirationOptions() Expirations
}

Client OAuth2/OIDC client

type ClientAppType

type ClientAppType string

ClientAppType OAuth2 has been designed around the following client profiles

type ClientAssertionType

type ClientAssertionType string

ClientAssertionType client authentication, the client uses the following parameter values and encodings.

type ClientAuthMethod

type ClientAuthMethod string

ClientAuthMethod This section defines a set of Client Authentication methods that are used by Clients to authenticate to the Authorization Server when using the Token Endpoint. During Client Registration, the RP (Client) MAY register a Client Authentication method. If no method is registered, the default method is client_secret_basic. https://openid.net/specs/openid-connect-core-1_0.html#ClientAuthentication

const (
	// Clients that have received a client_secret value from the Authorization Server authenticate with the
	// Authorization Server in accordance with Section 2.3.1 of OAuth 2.0 [RFC6749] using the HTTP Basic
	// authentication scheme.
	ClientAuthMethodSecretBasic ClientAuthMethod = "client_secret_basic"
	// Clients that have received a client_secret value from the Authorization Server, authenticate with the
	// Authorization Server in accordance with Section 2.3.1 of OAuth 2.0 [RFC6749] by including the Client
	// Credentials in the request body.
	ClientAuthMethodSecretPost ClientAuthMethod = "client_secret_post"
	// Clients that have received a client_secret value from the Authorization Server create a JWT using an
	// HMAC SHA algorithm, such as HMAC SHA-256. The HMAC (Hash-based Message Authentication Code) is
	// calculated using the octets of the UTF-8 representation of the client_secret as the shared key.
	//  iss REQUIRED
	//  sub REQUIRED
	//  aud REQUIRED
	//  jti REQUIRED
	//  exp REQUIRED
	//  iat OPTIONAL
	ClientAuthMethodSecretJWT ClientAuthMethod = "client_secret_jwt"
	// Clients that have registered a public key sign a JWT using that key.
	//  iss REQUIRED
	//  sub REQUIRED
	//  aud REQUIRED
	//  jti REQUIRED
	//  exp REQUIRED
	//  iat OPTIONAL
	ClientAuthMethodPrivateKeyJWT ClientAuthMethod = "private_key_jwt"
	// The Client does not authenticate itself at the Token Endpoint, either because it uses only the Implicit
	// Flow (and so does not use the Token Endpoint) or because it is a Public Client with no Client Secret or
	// other authentication mechanism.
	ClientAuthMethodNone ClientAuthMethod = "none"

	// https://www.rfc-editor.org/rfc/rfc8705.html
	// Indicates that client authentication to the authorization server will occur with mutual TLS utilizing
	// the PKI method of associating a certificate to a client
	ClientAuthMethodTLSClientAuth = "tls_client_auth"
	// Indicates that client authentication to the authorization server will occur using mutual TLS with the
	// client utilizing a self-signed certificate.
	ClientAuthMethodSelfSignedTLSClientAuth = "self_signed_tls_client_auth"
)

client auth method list

type ClientType

type ClientType string

ClientType OAuth defines two client types, based on their ability to authenticate securely with the authorization server (i.e., ability to maintain the confidentiality of their client credentials) https://www.rfc-editor.org/rfc/rfc6749#section-2.1

const (
	// Clients capable of maintaining the confidentiality of their credentials (e.g., client implemented on a
	// secure server with restricted access to the client credentials), or capable of secure client
	// authentication using other means.
	ClientTypeConfidential ClientType = "confidential"
	// Clients incapable of maintaining the confidentiality of their credentials (e.g., clients executing on
	// the device used by the resource owner, such as an installed native application or a web browser-based
	// application), and incapable of secure client authentication via any other means.
	ClientTypePublic ClientType = "public"
)

client type

type CodeChallengeMethod

type CodeChallengeMethod string

CodeChallengeMethod proof key for code exchange method

const (
	// code_verifier
	CodeChallengeMethodPlain CodeChallengeMethod = "plain"
	// BASE64URL-ENCODE(SHA256(ASCII(code_verifier)))
	CodeChallengeMethodS256 CodeChallengeMethod = "S256"
)

PKCE code challenge method list

type Configuration

type Configuration struct {
	// URL using the https scheme with no query or fragment component that the OP asserts as its Issuer Identifier.
	// This also MUST be identical to the iss Claim value in ID Tokens issued from this Issuer.
	Issuer string `json:"issuer"` // REQUIRED, eg: https://example.com/oidc
	// URL of the authorization server's authorization endpoint [RFC6749].  This is REQUIRED unless no grant types
	// are supported that use the authorization endpoint.
	AuthorizationEndpoint string `json:"authorization_endpoint"` // REQUIRED, eg: https://example.com/oidc/authorize
	// URL of the authorization server's token endpoint. This is REQUIRED unless only the implicit grant type is supported.
	TokenEndpoint string `json:"token_endpoint"` // REQUIRED, eg: https://example.com/oidc/token
	// URL of the OP's UserInfo Endpoint.
	UserinfoEndpoint string `json:"userinfo_endpoint"` // REQUIRED, eg: https://example.com/oidc/userinfo
	// URL of the authorization server's JWK Set [JWK] document.
	JwksURI string `json:"jwks_uri"` // REQUIRED, eg: https://example.com/oidc/jwks.json
	// See https://www.rfc-editor.org/rfc/rfc7591 and https://openid.net/specs/openid-connect-registration-1_0.html
	RegistrationEndpoint string `json:"registration_endpoint,omitempty"` // RECOMMENDED
	// Defines how to manage OpenID Connect sessions, including postMessage-based logout and RP-initiated logout
	// functionality, see https://openid.net/specs/openid-connect-session-1_0.html
	EndSessionEndpoint string `json:"end_session_endpoint,omitempty"` // OPTIONAL
	// OpenID Provider Metadata parameter MUST be included in the Server's discovery responses when Session Management
	// and Discovery are supported
	CheckSessionIframe string `json:"check_session_iframe,omitempty"` // OPTIONAL
	// The Device Code grant type is used by browserless or input-constrained devices in the device flow to exchange
	// a previously obtained device code for an access token. ee https://www.rfc-editor.org/rfc/rfc8628
	DeviceAuthorizationEndpoint string `json:"device_authorization_endpoint,omitempty"` // OPTIONAL
	// This is used to enable a "log out" feature in clients, allowing the authorization server to clean up any
	// security credentials associated with the authorization. see https://oauth.net/2/token-revocation/
	RevocationEndpoint string `json:"revocation_endpoint,omitempty"` // OPTIONAL
	// The endpoint is an OAuth 2.0 endpoint that takes a parameter representing an OAuth 2.0 token and returns a JSON
	// [RFC7159] document representing the meta information surrounding the token, including whether this token is
	// currently active. see https://www.rfc-editor.org/rfc/rfc7662
	IntrospectionEndpoint string `json:"introspection_endpoint,omitempty"` // OPTIONAL

	// RECOMMENDED, scope values that this server supports
	ScopesSupported []Scope `json:"scopes_supported,omitempty"`
	// REQUIRED, code, id_token, token id_token
	ResponseTypesSupported []ResponseType `json:"response_types_supported"`
	// OPTIONAL, if omitted, default: query, fragment
	ResponseModesSupported []ResponseMode `json:"response_modes_supported,omitempty"`
	// OPTIONAL, if omitted, default: authorization_code, implicit
	GrantTypesSupported []GrantType `json:"grant_types_supported,omitempty"`
	// OPTIONAL, absolute URI or RFC6711 registered name
	ACRValuesSupported []string `json:"acr_values_supported,omitempty"`
	// REQUIRED, valid types include: pairwise and public
	SubjectTypesSupported []SubjectType `json:"subject_types_supported"`
	// REQUIRED, see JWT https://datatracker.ietf.org/doc/html/rfc7519
	IDTokenSigningAlgValuesSupported []string `json:"id_token_signing_alg_values_supported"`
	// OPTIONAL, see JWT
	IDTokenEncryptionAlgValuesSupported []string `json:"id_token_encryption_alg_values_supported,omitempty"`
	// OPTIONAL, see JWT
	IDTokenEncryptionEncValuesSupported []string `json:"id_token_encryption_enc_values_supported,omitempty"`
	// OPTIONAL, see JWS https://datatracker.ietf.org/doc/html/rfc7515
	UserinfoSigningAlgValuesSupported []string `json:"userinfo_signing_alg_values_supported,omitempty"`
	// OPTIONAL, see JWE https://datatracker.ietf.org/doc/html/rfc7516
	UserinfoEncryptionAlgValuesSupported []string `json:"userinfo_encryption_alg_values_supported,omitempty"`
	// OPTIONAL, see JWA https://datatracker.ietf.org/doc/html/rfc7518
	UserinfoEncryptionEncValuesSupported []Display `json:"userinfo_encryption_enc_values_supported,omitempty"`
	// OPTIONAL, see Core6.1, should support none and RS256
	RequestObjectSigningAlgValuesSupported []string `json:"request_object_signing_alg_values_supported,omitempty"`
	// OPTIONAL, JWE encryption algorithm
	RequestObjectEncryptionAlgValuesSupported []string `json:"request_object_encryption_alg_values_supported,omitempty"`
	// OPTIONAL, JWE encryption algorithm
	RequestObjectEncryptionEncValuesSupported []string `json:"request_object_encryption_enc_values_supported,omitempty"`
	// OPTIONAL, options are: client_secret_post, client_secret_basic, client_secret_jwt, private_key_jwt
	// https://openid.net/specs/openid-connect-core-1_0.html#ClientAuthentication
	TokenEndpointAuthMethodsSupported []ClientAuthMethod `json:"token_endpoint_auth_methods_supported,omitempty"`
	// OPTIONAL, JWT signing algorithm, should support RS256
	TokenEndpointAuthSigningAlgValuesSupported []string `json:"token_endpoint_auth_signing_alg_values_supported,omitempty"`
	// OPTIONAL, see Core3.1.2.1
	DisplayValuesSupported []Display `json:"display_values_supported,omitempty"`
	// OPTIONAL, see Core5.6, values: normal, aggregated, distributed, if omitted, normal should support
	ClaimTypesSupported []ClaimType `json:"claim_types_supported,omitempty"`
	// RECOMMENDED
	ClaimsSupported []string `json:"claims_supported,omitempty"`
	// OPTIONAL
	ServiceDocumentation string `json:"service_documentation,omitempty"`
	// OPTIONAL, locale language
	ClaimsLocalesSupported []string `json:"claims_locales_supported,omitempty"`
	// OPTIONAL, see BCP47 RFC5646
	UILocalesSupported []string `json:"ui_locales_supported,omitempty"`
	// OPTIONAL
	ClaimsParameterSupported bool `json:"claims_parameter_supported,omitempty"`
	// OPTIONAL
	RequestParameterSupported bool `json:"request_parameter_supported,omitempty"`
	// OPTIONAL, specifying whether the OP supports use of the request_uri parameter, with true indicating support.
	// If omitted, the default value is true.
	RequestURIParameterSupported bool `json:"request_uri_parameter_supported,omitempty"`
	// OPTIONAL, whether the OP requires any request_uri values used to be pre-registered using the request_uris
	// registration parameter. Pre-registration is REQUIRED when the value is true. If omitted, the default value is false.
	RequireRequestURIRegistration bool `json:"require_request_uri_registration,omitempty"`
	// OPTIONAL
	OPPolicyURI string `json:"op_policy_uri,omitempty"`
	// OPTIONAL
	OPTosURI string `json:"op_tos_uri,omitempty"`

	// OPTIONAL, a list of client authentication methods supported by this revocation endpoint
	RevocationEndpointAuthMethodsSupported []ClientAuthMethod `json:"revocation_endpoint_auth_methods_supported,omitempty"`
	// OPTIONAL, see JWT
	RevocationEndpointAuthSigningAlgValuesSupported []string `json:"revocation_endpoint_auth_signing_alg_values_supported,omitempty"`
	// OPTIONAL, a list of client authentication methods supported by this introspection endpoint.
	IntrospectionEndpointAuthMethodSupported []ClientAuthMethod `json:"introspection_endpoint_auth_method_supported,omitempty"`
	// OPTIONAL, see JWS
	IntrospectionEndpointAuthSigningAlgValuesSupported []string `json:"introspection_endpoint_auth_signing_alg_values_supported,omitempty"`
	// OPTIONAL, see https://oauth.net/2/pkce/
	CodeChallengeMethodsSupported []CodeChallengeMethod `json:"code_challenge_methods_supported,omitempty"`
}

Configuration see https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata and https://www.rfc-editor.org/rfc/rfc8414 See example: https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfigurationResponse

type CustomClaims

type CustomClaims = jwt.MapClaims

CustomClaims alias jwt.MapClaims

type Display

type Display string

Display specifies how the Authorization Server displays the authentication and consent user interface pages to the End-User.

const (
	// The Authorization Server SHOULD display the authentication and consent UI consistent
	// with a full User Agent page view. If the display parameter is not specified, this is
	// the default display mode.
	DisplayPage Display = "page"
	// The Authorization Server SHOULD display the authentication and consent UI consistent
	// with a popup User Agent window. The popup User Agent window should be of an appropriate
	// size for a login-focused dialog and should not obscure the entire window that it is
	// popping up over.
	DisplayPopup Display = "popup"
	// The Authorization Server SHOULD display the authentication and consent UI consistent
	// with a device that leverages a touch interface.
	DisplayTouch Display = "touch"
	// The Authorization Server SHOULD display the authentication and consent UI consistent
	// with a "feature phone" type display.
	DisplayWap Display = "wap"
)

Display list

type EndSessionRequest

type EndSessionRequest struct {
	IDTokenHint           string `schema:"id_token_hint"`
	ClientID              string `schema:"client_id"`
	PostLogoutRedirectURI string `schema:"post_logout_redirect_uri"`
	State                 string `schema:"state"`

	Issuer string `schema:"-"` // dynamic issuer
}

EndSessionRequest end_session endpoint

type Error

type Error struct {
	ErrorCode   string `json:"error" schema:"error"`
	Description string `json:"description" schema:"error_description"`
	State       string `json:"state" schema:"state"`
	// contains filtered or unexported fields
}

Error OAuth2 error codes

func (Error) Desc

func (e Error) Desc(desc string) Error

Desc custom description

func (Error) Error

func (e Error) Error() string

Error implements error interface

func (Error) Wrap

func (e Error) Wrap(err error) Error

Wrap wrap error

type Expirations

type Expirations struct {
	// Authorize code expires
	CodeExpiration int
	// Access token expires
	AccessTokenExpiration int
	// Refresh token expires
	RefreshTokenExpiration int
	// ID token expires
	IDTokenExpiration int

	// Device code polling interval
	PollingInterval int
}

Expirations settings expiration

type GrantAuthorizationCodeRequest

type GrantAuthorizationCodeRequest struct {
	Code         string `schema:"code" json:"code"`
	RedirectURI  string `schema:"redirect_uri" json:"redirect_uri"`
	CodeVerifier string `schema:"code_verifier" json:"code_verifier"` // PKCE
	ClientID     string `schema:"client_id" json:"client_id"`
	// Extension grants
	ClientAssertion     string `schema:"client_assertion" json:"client_assertion"`
	ClientAssertionType string `schema:"client_assertion_type" json:"client_assertion_type"`
}

GrantAuthorizationCodeRequest authorization_code

type GrantClientCredentialsRequest

type GrantClientCredentialsRequest struct {
	Scope SpaceDelimitedArr `schema:"scope" json:"scope"`
}

GrantClientCredentialsRequest client_credentials

type GrantDeviceCodeRequest

type GrantDeviceCodeRequest struct {
	ClientID string            `schema:"client_id" json:"client_id"`
	Scope    SpaceDelimitedArr `schema:"scope" json:"scope,omitempty"`
}

GrantDeviceCodeRequest urn:ietf:params:oauth:grant-type:device_code

type GrantImplicitRequest

type GrantImplicitRequest struct {
	RedirectURI string            `json:"redirect_uri"`
	Scope       SpaceDelimitedArr `json:"scope"`
}

GrantImplicitRequest implicit

type GrantJwtBearerRequest

type GrantJwtBearerRequest struct {
	ClientID  string            `schema:"client_id" json:"client_id"`
	Assertion string            `schema:"assertion" json:"assertion"`
	Scope     SpaceDelimitedArr `schema:"scope" json:"scope"`
}

GrantJwtBearerRequest urn:ietf:params:oauth:grant-type:jwt-bearer

type GrantPasswordRequest

type GrantPasswordRequest struct {
	Username string            `schema:"username" json:"username"`
	Password string            `schema:"password" json:"password"`
	Scope    SpaceDelimitedArr `schema:"scope" json:"scope"`
}

GrantPasswordRequest passowrd

type GrantRefreshTokenRequest

type GrantRefreshTokenRequest struct {
	RefreshToken string            `schema:"refresh_token" json:"refresh_token"`
	Scope        SpaceDelimitedArr `schema:"scope" json:"scope"`
	// Extension grants
	ClientAssertion     string `schema:"client_assertion" json:"client_assertion"`
	ClientAssertionType string `schema:"client_assertion_type" json:"client_assertion_type"`
}

GrantRefreshTokenRequest refresh_token

type GrantSaml2BearerRequest

type GrantSaml2BearerRequest struct {
	ClientID  string            `schema:"client_id" json:"client_id"`
	Assertion string            `schema:"assertion" json:"assertion"`
	Scope     SpaceDelimitedArr `schema:"scope" json:"scope"`
}

GrantSaml2BearerRequest urn:ietf:params:oauth:grant-type:saml2-bearer

type GrantTokenExchangeRequest

type GrantTokenExchangeRequest struct {
	SubjectToken       string            `schema:"subject_token" json:"subject_token"`
	SubjectTokenType   string            `schema:"subject_token_type" json:"subject_token_type"`
	ActorToken         string            `schema:"actor_token" json:"actor_token,omitempty"`
	ActorTokenType     string            `schema:"actor_token_type" json:"actor_token_type,omitempty"`
	Resource           []string          `schema:"resource" json:"resource,omitempty"` // required if actor_token present
	Audience           jwt.ClaimStrings  `schema:"audience" json:"audience,omitempty"`
	RequestedTokenType string            `schema:"requested_token_type" json:"requested_token_type,omitempty"`
	Scope              SpaceDelimitedArr `schema:"scope" json:"scope,omitempty"`
}

GrantTokenExchangeRequest urn:ietf:params:oauth:grant-type:token-exchange

type GrantType

type GrantType string

GrantType grant access type

const (
	// "authorization_code" used for the Token Request in the Authorization Code Flow
	GrantTypeAuthorizationCode GrantType = "authorization_code"
	// "refresh_token" used for the Token Request in the Refresh Token Flow
	GrantTypeRefreshToken GrantType = "refresh_token"
	// "client_credentials" used for the Token Request in the Client Credentials Flow
	GrantTypeClientCredentials = "client_credentials"
	// "password" used for the Token Request in the Password Flow
	GrantTypePassword GrantType = "password"
	// "implicit" used for the Token Request in the Implicit Flow, not real
	GrantTypeImplicit GrantType = "__implicit"

	// GrantTypeBearer "urn:ietf:params:oauth:grant-type:jwt-bearer" used for the JWT Authorization Grant
	// https://www.rfc-editor.org/rfc/rfc7523
	GrantTypeJwtBearer GrantType = "urn:ietf:params:oauth:grant-type:jwt-bearer"
	// GrantTypeTokenExchange "urn:ietf:params:oauth:grant-type:token-exchange" used for the OAuth Token Exchange Grant
	// https://oauth.net/2/token-exchange/
	GrantTypeTokenExchange GrantType = "urn:ietf:params:oauth:grant-type:token-exchange"
	// GrantTypeDeviceCode "urn:ietf:params:oauth:grant-type:device_code" used for the Device Code Grant
	// https://datatracker.ietf.org/doc/html/rfc8628
	GrantTypeDeviceCode GrantType = "urn:ietf:params:oauth:grant-type:device_code"
	// GrantTypeSAML2Bearer urn:ietf:params:oauth:grant-type:saml2-bearer used for OAuth SMAL2
	// https://www.rfc-editor.org/rfc/rfc7522.html
	GrantTypeSAML2Bearer = "urn:ietf:params:oauth:grant-type:saml2-bearer"
)

Grant type list, The correlation between the two fields is listed in the table below. https://www.rfc-editor.org/rfc/rfc7591#page-12

+-----------------------------------------------+-------------------+
| grant_types value includes:                   | response_types    |
|                                               | value includes:   |
+-----------------------------------------------+-------------------+
| authorization_code                            | code              |
| implicit                                      | token             |
| password                                      | (none)            |
| client_credentials                            | (none)            |
| refresh_token                                 | (none)            |
| urn:ietf:params:oauth:grant-type:jwt-bearer   | (none)            |
| urn:ietf:params:oauth:grant-type:saml2-bearer | (none)            |
+-----------------------------------------------+-------------------+

type IDToken

type IDToken struct {
	Issuer     string           `json:"iss"`
	Subject    string           `json:"sub"` // User identifier
	Audience   jwt.ClaimStrings `json:"aud"` // Must contain oauth2 client_id
	Expiration *jwt.NumericDate `json:"exp"` // Expiration time on or after which the ID Token MUST NOT be accepted for processing.
	IssuedAt   *jwt.NumericDate `json:"iat"` // Time at which the JWT was issued

	// When a max_age request is made or when auth_time is requested as an Essential Claim, then this Claim is REQUIRED;
	// otherwise, its inclusion is OPTIONAL.
	AuthTime *jwt.NumericDate `json:"auth_time,omitempty"`
	// String value used to associate a Client session with an ID Token, and to mitigate replay attacks. If present in
	// the ID Token, Clients MUST verify that the nonce Claim Value is equal to the value of the nonce parameter sent in
	// the Authentication Request. If present in the Authentication Request, Authorization Servers MUST include a nonce
	// Claim in the ID Token with the Claim Value being the nonce value sent in the Authentication Request.
	Nonce string `json:"nonce,omitempty"`

	// Authentication Context Class Reference. String specifying an Authentication Context Class Reference value that
	// identifies the Authentication Context Class that the authentication performed satisfied. The value "0" indicates
	// the End-User authentication did not meet the requirements of ISO/IEC 29115 [ISO29115] level 1.
	// eg. urn:mace:incommon:iap:silver
	ACSR string `json:"acsr,omitempty"`
	// Authentication Methods References. JSON array of strings that are identifiers for authentication methods used in
	// the authentication. For instance, values might indicate that both password and OTP authentication methods were used.
	AMR []string `json:"amr,omitempty"`
	// Authorized party - the party to which the ID Token was issued. If present, it MUST contain the OAuth 2.0 Client ID
	// of this party. This Claim is only needed when the ID Token has a single audience value and that audience is different
	// than the authorized party. It MAY be included even when the authorized party is the same as the sole audience.
	AZP string `json:"azp,omitempty"`

	// Access Token hash value. Its value is the base64url encoding of the left-most half of the hash of the octets of the
	// ASCII representation of the access_token value, where the hash algorithm used is the hash algorithm used in the alg
	// Header Parameter of the ID Token's JOSE Header. For instance, if the alg is RS256, hash the access_token value with
	// SHA-256, then take the left-most 128 bits and base64url encode them. The at_hash value is a case sensitive string.
	// see https://openid.net/specs/openid-connect-core-1_0.html#CodeIDToken
	ATHash string `json:"at_hash,omitempty"`
	// Code hash value. Its value is the base64url encoding of the left-most half of the hash of the octets of the ASCII
	// representation of the code value, where the hash algorithm used is the hash algorithm used in the alg Header Parameter
	// of the ID Token's JOSE Header. For instance, if the alg is HS512, hash the code value with SHA-512, then take the
	// left-most 256 bits and base64url encode them. The c_hash value is a case sensitive string.
	// If the ID Token is issued from the Authorization Endpoint with a code, which is the case for the response_type values
	// code id_token and code id_token token, this is REQUIRED; otherwise, its inclusion is OPTIONAL.
	CHash string `json:"c_hash,omitempty"`

	// Public key used to check the signature of an ID Token issued by a Self-Issued OpenID Provider, as specified in Section 7.
	// The key is a bare key in JWK [JWK] format (not an X.509 certificate value). The sub_jwk value is a JSON object. Use of
	// the sub_jwk Claim is NOT RECOMMENDED when the OP is not Self-Issued.
	// see https://openid.net/specs/openid-connect-core-1_0.html#SelfIssuedResponse
	SubJWK *jose.JSONWebKey `json:"sub_jwk,omitempty"`

	jwt.RegisteredClaims
}

IDToken The primary extension that OpenID Connect makes to OAuth 2.0 to enable End-Users to be Authenticated is the ID Token data structure. The ID Token is a security token that contains Claims about the Authentication of an End-User by an Authorization Server when using a Client, and potentially other requested Claims. The ID Token is represented as a JSON Web Token (JWT) [JWT]. https://openid.net/specs/openid-connect-core-1_0.html#IDToken

type Locales

type Locales []language.Tag

Locales local tag

func (*Locales) UnmarshalText

func (l *Locales) UnmarshalText(text []byte) error

UnmarshalText unmarhsal text

type Prompt

type Prompt string

Prompt Space delimited, case sensitive list of ASCII string values that specifies whether the Authorization Server prompts the End-User for reauthentication and consent.

const (
	// The Authorization Server MUST NOT display any authentication or consent user interface
	// pages. An error is returned if an End-User is not already authenticated or the Client
	// does not have pre-configured consent for the requested Claims or does not fulfill other
	// conditions for processing the request.
	PromptNone Prompt = "none"
	// The Authorization Server SHOULD prompt the End-User for reauthentication.
	PromptLogin Prompt = "login"
	// The Authorization Server SHOULD prompt the End-User for consent before returning
	// information to the Client.
	PromptConsent Prompt = "consent"
	// The Authorization Server SHOULD prompt the End-User to select a user account. This enables
	// an End-User who has multiple accounts at the Authorization Server to select amongst the
	// multiple accounts that they might have current sessions for.
	PromptSelectAccount Prompt = "select_account"
)

Prompt list

type Response

type Response struct {
	Header http.Header
	Output map[string]interface{}

	// oauth2 or oidc error code
	ErrCode error

	ResponseMode ResponseMode
	RedirectURL  string
}

Response response for request

func NewResponse

func NewResponse() *Response

NewResponse output

func (*Response) GetRedirectURL

func (resp *Response) GetRedirectURL() (string, error)

GetRedirectURL returns the redirect url with all query string parameters

func (*Response) GetStatusCode

func (resp *Response) GetStatusCode() int

GetStatusCode get the http status code

func (*Response) SetErrorURI

func (resp *Response) SetErrorURI(err Error, uri, state string)

SetErrorURI sets an error id, description, state, and uri on the Response

func (*Response) SetRedirectURL

func (resp *Response) SetRedirectURL(url string)

SetRedirectURL changes the response to redirect to the given uri

func (*Response) SetResponseMode

func (resp *Response) SetResponseMode(mode ResponseMode)

SetResponseMode sets response mode

type ResponseMode

type ResponseMode string

ResponseMode Informs the Authorization Server of the mechanism to be used for returning Authorization Response parameters from the Authorization Endpoint. https://openid.net/specs/oauth-v2-multiple-response-types-1_0.html#ResponseModes

const (
	// In this mode, Authorization Response parameters are encoded in the query string added
	// to the redirect_uri when redirecting back to the Client.
	ResponseModeQuery ResponseMode = "query"
	// In this mode, Authorization Response parameters are encoded in the fragment added to
	// the redirect_uri when redirecting back to the Client.
	ResponseModeFragment ResponseMode = "fragment"
	// In this mode, Authorization Response parameters are encoded as HTML form values that
	// are auto-submitted in the User Agent, and thus are transmitted via the HTTP POST
	// method to the Client, with the result parameters being encoded in the body using the
	// application/x-www-form-urlencoded format.
	// see https://openid.net/specs/oauth-v2-form-post-response-mode-1_0.html
	ResponseModeFormPost ResponseMode = "form_post"

	// This specification defines a new response mode for RFC6749 that uses HTML5 Web Messaging
	// (a.k.a window.postMessage()) instead of the redirect for the Authorization Response
	// from the Authorization Endpoint.
	// https://datatracker.ietf.org/doc/html/draft-sakimura-oauth-wmrm-00
	ResponseModeWebMessage ResponseMode = "web_message"
)

Response mode list

type ResponseType

type ResponseType string

ResponseType authorization endpoint is used by the authorization code grant type and implicit grant type flows 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. https://datatracker.ietf.org/doc/html/rfc6749#section-3.1.1

type RevocationRequest

type RevocationRequest struct {
	Token         string        `schema:"token"` // access_token or refresh_token
	TokenTypeHint TokenTypeHint `schema:"token_type_hint"`

	Issuer string `schema:"-"` // dynamic issuer
	Client Client `schema:"-"`
}

RevocationRequest revocation endpoint

type Scope

type Scope = string

Scope OpenID Connect Clients use scope values, as defined in Section 3.3 of OAuth 2.0 [RFC6749], to specify what access privileges are being requested for Access Tokens. The scopes associated with Access Tokens determine what resources will be available when they are used to access OAuth 2.0 protected endpoints. Protected Resource endpoints MAY perform different actions and return different information based on the scope values and other parameters used when requesting the presented Access Token. https://openid.net/specs/openid-connect-core-1_0.html#ScopeClaims

const (
	ScopeOpenID Scope = "openid"
	// OPTIONAL. This scope value requests access to the End-User's default profile Claims,
	// which are: name, family_name, given_name, middle_name, nickname, preferred_username,
	// profile, picture, website, gender, birthdate, zoneinfo, locale, and updated_at.
	ScopeProfile Scope = "profile"
	// OPTIONAL. This scope value requests access to the email and email_verified Claims.
	ScopeEmail Scope = "email"
	// OPTIONAL. This scope value requests access to the address Claim.
	ScopeAddress Scope = "address"
	// OPTIONAL. This scope value requests access to the phone_number and phone_number_verified
	// Claims.
	ScopePhone Scope = "phone"
	// This (optional) scope value requests that an OAuth 2.0 Refresh Token be issued that
	// can be used to obtain an Access Token that grants access to the End-User's UserInfo
	// Endpoint even when the End-User is not present (not logged in).
	ScopeOfflineAccess = "offline_access"
)

scope list

type Session

type Session interface {
	// AllowedOrigin is that postMessage from op host
	AllowedOrigin() string
	// SessionExpiresIn user session expires with cookie
	SessionExpiresIn(cookie string) int
}

Session session manager

type SpaceDelimitedArr

type SpaceDelimitedArr []string

SpaceDelimitedArr space delimited string

func (SpaceDelimitedArr) Encode

func (s SpaceDelimitedArr) Encode() string

Encode implements schema

func (SpaceDelimitedArr) MarshalJSON

func (s SpaceDelimitedArr) MarshalJSON() ([]byte, error)

MarshalJSON marshal json

func (SpaceDelimitedArr) MarshalText

func (s SpaceDelimitedArr) MarshalText() ([]byte, error)

MarshalText marhsal text

func (*SpaceDelimitedArr) UnmarshalJSON

func (s *SpaceDelimitedArr) UnmarshalJSON(data []byte) error

UnmarshalJSON unmarhsal json

func (*SpaceDelimitedArr) UnmarshalText

func (s *SpaceDelimitedArr) UnmarshalText(text []byte) error

UnmarshalText unmarhsal text

type Storage

type Storage interface {
	// Client loads the client by id (client_id)
	Client(clientID string) (Client, error)
	// UserDataScopes get user info by scopes
	UserDataScopes(uid string, scopes []Scope) (*UserInfo, error)

	// SaveAuthorize saves authorize data.
	SaveAuthorize(code string, data *AuthorizeData, exp int) error
	// LoadAuthorize looks up AuthorizeData by a code.
	// Client information MUST be loaded together.
	// Optionally can return error if expired.
	LoadAuthorize(code string) (data *AuthorizeData, err error)
	// RemoveAuthorize revokes or deletes the authorization code.
	RemoveAuthorize(code string) error

	// SaveAccess writes AccessData.
	// If RefreshToken is not blank, it must save in a way that can be loaded using LoadRefresh.
	SaveAccess(token string, data *AccessData, exp int) error
	// LoadAccess retrieves access data by token. Client information MUST be loaded together.
	// AuthorizeData and AccessData DON'T NEED to be loaded if not easily available.
	// Optionally can return error if expired.
	LoadAccess(token string) (data *AccessData, err error)
	// RemoveAccess revokes or deletes an AccessData.
	RemoveAccess(token string) error

	// SaveRefresh save refresh token
	SaveRefresh(refresh, token string, exp int) (err error)
	// LoadRefresh retrieves refresh AccessData. Client information MUST be loaded together.
	// AuthorizeData and AccessData DON'T NEED to be loaded if not easily available.
	// Optionally can return error if expired.
	LoadRefresh(token string) (data *AccessData, err error)
	// RemoveRefresh revokes or deletes refresh AccessData.
	RemoveRefresh(token string) error
}

Storage store interface

type SubjectType

type SubjectType string

SubjectType A Subject Identifier is a locally unique and never reassigned identifier within the Issuer for the End-User, which is intended to be consumed by the Client. Two Subject Identifier types are defined by this specification

const (
	// This provides a different sub value to each Client, so as not to enable Clients to correlate
	// the End-User's activities without permission.
	SubjectTypePairwise SubjectType = "pairwise"
	// This provides the same sub (subject) value to all Clients. It is the default if the provider
	// has no subject_types_supported element in its discovery document.
	SubjectTypePublic SubjectType = "public"
)

subject list

type TokenType

type TokenType string

TokenType grant token type

const (
	// https://www.rfc-editor.org/rfc/rfc7519.html
	TokenTypeJWT TokenType = "urn:ietf:params:oauth:token-type:jwt"
	// https://www.rfc-editor.org/rfc/rfc8693.html#name-token-type-identifiers
	TokenTypeAccessToken  TokenType = "urn:ietf:params:oauth:token-type:access_token"
	TokenTypeRefreshToken TokenType = "urn:ietf:params:oauth:token-type:refresh_token"
	TokenTypeIDToken      TokenType = "urn:ietf:params:oauth:token-type:id_token"
	TokenTypeSAML1        TokenType = "urn:ietf:params:oauth:token-type:saml1"
	TokenTypeSAML2        TokenType = "urn:ietf:params:oauth:token-type:saml2"
)

Token type list

type TokenTypeHint

type TokenTypeHint string

TokenTypeHint A hint about the type of the token submitted for revocation. Clients MAY pass this parameter in order to help the authorization server to optimize the token lookup.

const (
	// An access token as defined in [RFC6749], Section 1.4
	TokenTypeHintAccessToken TokenTypeHint = "access_token"
	// refresh_token: A refresh token as defined in [RFC6749], Section 1.5
	TokenTypeHintRefreshToken TokenTypeHint = "refresh_token"
)

token type list

type UserInfo

type UserInfo struct {
	// Scope: openid
	//
	// Subject - Identifier for the End-User at the Issuer.
	Subject string `json:"sub,omitempty" structs:"sub,omitempty"`

	// Scope: profile
	//
	// nd-User's full name in displayable form including all name parts, possibly including titles and suffixes, ordered according
	// to the End-User's locale and preferences.
	Name string `json:"name,omitempty" structs:"name,omitempty"`
	// Given name(s) or first name(s) of the End-User. Note that in some cultures, people can have multiple given names; all
	// can be present, with the names being separated by space characters.
	GivenName string `json:"given_name,omitempty" structs:"given_name,omitempty"`
	// Surname(s) or last name(s) of the End-User. Note that in some cultures, people can have multiple family names or no family
	// name; all can be present, with the names being separated by space characters.
	FamilyName string `json:"family_name,omitempty" structs:"family_name,omitempty"`
	// Middle name(s) of the End-User. Note that in some cultures, people can have multiple middle names; all can be present, with
	// the names being separated by space characters. Also note that in some cultures, middle names are not used.
	MiddleName string `json:"middle_name,omitempty" structs:"middle_name,omitempty"`
	// Casual name of the End-User that may or may not be the same as the given_name. For instance, a nickname value of Mike might
	// be returned alongside a given_name value of Michael.
	Nickname string `json:"nickname,omitempty" structs:"nickname,omitempty"`
	// Shorthand name by which the End-User wishes to be referred to at the RP, such as janedoe or j.doe. This value MAY be any
	// valid JSON string including special characters such as @, /, or whitespace. The RP MUST NOT rely upon this value being
	// unique, as discussed in Section 5.7.
	PreferredUsername string `json:"preferred_username,omitempty" structs:"preferred_username,omitempty"`
	// URL of the End-User's profile page. The contents of this Web page SHOULD be about the End-User.
	Profile string `json:"profile,omitempty" structs:"profile,omitempty"`
	// URL of the End-User's profile picture. This URL MUST refer to an image file (for example, a PNG, JPEG, or GIF image file),
	// rather than to a Web page containing an image. Note that this URL SHOULD specifically reference a profile photo of the
	// End-User suitable for displaying when describing the End-User, rather than an arbitrary photo taken by the End-User.
	Picture string `json:"picture,omitempty" structs:"picture,omitempty"`
	// URL of the End-User's Web page or blog. This Web page SHOULD contain information published by the End-User or an organization
	// that the End-User is affiliated with.
	Website string `json:"website,omitempty" structs:"website,omitempty"`
	// End-User's gender. Values defined by this specification are female and male. Other values MAY be used when neither of the defined
	// values are applicable.
	Gender string `json:"gender,omitempty" structs:"gender,omitempty"`
	// End-User's birthday, represented as an ISO 8601:2004 [ISO8601‑2004] YYYY-MM-DD format. The year MAY be 0000, indicating that
	// it is omitted. To represent only the year, YYYY format is allowed. Note that depending on the underlying platform's date related
	// function, providing just year can result in varying month and day, so the implementers need to take this factor into account
	// to correctly process the dates.
	Birthdate string `json:"birthdate,omitempty" structs:"birthdate,omitempty"`
	// String from zoneinfo [zoneinfo] time zone database representing the End-User's time zone. For example, Europe/Paris or
	// America/Los_Angeles.
	Zoneinfo string `json:"zoneinfo,omitempty" structs:"zoneinfo,omitempty"`
	// End-User's locale, represented as a BCP47 [RFC5646] language tag. This is typically an ISO 639-1 Alpha-2 [ISO639‑1] language
	// code in lowercase and an ISO 3166-1 Alpha-2 [ISO3166‑1] country code in uppercase, separated by a dash. For example, en-US or
	// fr-CA. As a compatibility note, some implementations have used an underscore as the separator rather than a dash, for example,
	// en_US; Relying Parties MAY choose to accept this locale syntax as well.
	Locale string `json:"locale,omitempty" structs:"locale,omitempty"`
	// Time the End-User's information was last updated. Its value is a JSON number representing the number of seconds from
	// 1970-01-01T0:0:0Z as measured in UTC until the date/time.
	UpdatedAt *jwt.NumericDate `json:"updated_at,omitempty" structs:"updated_at,omitempty"`

	// Scope: email
	//
	// End-User's preferred e-mail address. Its value MUST conform to the RFC 5322 [RFC5322] addr-spec syntax. The RP MUST NOT rely
	// upon this value being unique, as discussed in Section 5.7.
	Email string `json:"email,omitempty" structs:"email,omitempty"`
	// True if the End-User's e-mail address has been verified; otherwise false. When this Claim Value is true, this means that the
	// OP took affirmative steps to ensure that this e-mail address was controlled by the End-User at the time the verification was
	// performed. The means by which an e-mail address is verified is context-specific, and dependent upon the trust framework or
	// contractual agreements within which the parties are operating.
	EmailVerified *bool `json:"email_verified,omitempty" structs:"email_verified,omitempty"`

	// Scope: phone
	//
	// End-User's preferred telephone number. E.164 [E.164] is RECOMMENDED as the format of this Claim, for example, +1 (425) 555-1212
	// or +56 (2) 687 2400. If the phone number contains an extension, it is RECOMMENDED that the extension be represented using the
	// RFC 3966 [RFC3966] extension syntax, for example, +1 (604) 555-1234;ext=5678.
	PhoneNumber string `json:"phone_number,omitempty" structs:"phone_number,omitempty"`
	// True if the End-User's phone number has been verified; otherwise false. When this Claim Value is true, this means that the OP
	// took affirmative steps to ensure that this phone number was controlled by the End-User at the time the verification was performed.
	// The means by which a phone number is verified is context-specific, and dependent upon the trust framework or contractual
	// agreements within which the parties are operating. When true, the phone_number Claim MUST be in E.164 format and any extensions
	// MUST be represented in RFC 3966 format.
	PhoneNumberVerified *bool `json:"phone_number_verified,omitempty" structs:"phone_number_verified,omitempty"`

	// Scope: address
	//
	// End-User's preferred postal address. The value of the address member is a JSON [RFC4627] structure containing some or all of the
	// members defined in Section 5.1.1.
	Address *Address `json:"address,omitempty" structs:"address,omitempty"`

	jwt.MapClaims `json:"claims,omitempty" structs:"claims,omitempty"`
}

UserInfo This specification defines a set of standard Claims. They can be requested to be returned either in the UserInfo Response, per Section 5.3.2, or in the ID Token, per Section 2.

type UserInfoRequest

type UserInfoRequest struct {
	Token string `schema:"-"`

	Issuer     string      `schema:"-"` // dynamic issuer
	Subject    string      `schema:"-"`
	AccessData *AccessData `schema:"-"`
}

UserInfoRequest userinfo request

Jump to

Keyboard shortcuts

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