oauth2

package
v0.0.0-...-f15f685 Latest Latest
Warning

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

Go to latest
Published: Sep 14, 2025 License: BSD-3-Clause Imports: 6 Imported by: 0

Documentation

Overview

Package oauth2 implements base primitives for parsing a subset of oauth2 messages and errors

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func SendCodeAuthResponse

func SendCodeAuthResponse(w http.ResponseWriter, req *http.Request, resp *CodeAuthResponse)

SendCodeAuthResponse sends the appropriate response to an auth request of response_type code, aka "Code flow"

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

func SendTokenAuthResponse

func SendTokenAuthResponse(w http.ResponseWriter, req *http.Request, resp *TokenAuthResponse)

SendTokenAuthResponse sends the appropriate response to an auth request of response_type token, aka "Implicit flow"

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

func WriteAuthError

func WriteAuthError(w http.ResponseWriter, req *http.Request, redirectURI *url.URL, code AuthErrorCode, state, description string, cause error) error

WriteAuthError will build and send an authError for this HTTP response cycle, returning the error that was written. It will ignore any errors actually writing the error to the user.

func WriteError

func WriteError(w http.ResponseWriter, req *http.Request, err error) error

WriteError handles the passed error appropriately. After calling this, the HTTP sequence should be considered complete.

For errors in the authorization endpoint, the user will be redirected with the code appended to the redirect URL. https://tools.ietf.org/html/rfc6749#section-4.1.2.1

For unknown errors, an InternalServerError response will be sent

func WriteHTTPError

func WriteHTTPError(w http.ResponseWriter, req *http.Request, code int, message string, cause error, causeMsg string) error

WriteHTTPError will build and send an httpErr for this HTTP response cycle, returning the error that was written. It will ignore any errors actually writing the error to the user.

func WriteTokenResponse

func WriteTokenResponse(w http.ResponseWriter, resp *TokenResponse) error

WriteTokenResponse sends a response for the token endpoint.

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

Types

type AuthError

type AuthError struct {
	State       string
	Code        AuthErrorCode
	Description string
	RedirectURI string
	Cause       error
}

func (*AuthError) Error

func (a *AuthError) Error() string

func (*AuthError) Unwrap

func (a *AuthError) Unwrap() error

type AuthErrorCode

type AuthErrorCode string
const (
	AuthErrorCodeInvalidRequest           AuthErrorCode = "invalid_request"
	AuthErrorCodeUnauthorizedClient       AuthErrorCode = "unauthorized_client"
	AuthErrorCodeAccessDenied             AuthErrorCode = "access_denied"
	AuthErrorCodeUnsupportedResponseType  AuthErrorCode = "unsupported_response_type"
	AuthErrorCodeInvalidScope             AuthErrorCode = "invalid_scope"
	AuthErrorCodeErrServerError           AuthErrorCode = "server_error"
	AuthErrorCodeErrTemporarilyUnvailable AuthErrorCode = "temporarily_unavailable"
)

https://tools.ietf.org/html/rfc6749#section-4.1.2.1 nolint:unused,varcheck,deadcode

type AuthRequest

type AuthRequest struct {
	ClientID string
	// RedirectURI the client specified. This is an OPTIONAL field, if not
	// passed will be set to the zero value
	RedirectURI  string
	State        string
	Scopes       []string
	ResponseType ResponseType
	// CodeChallenge is the PKCE code challenge. If it is provided, it will be
	// S256 format.
	CodeChallenge string

	// Raw is the full, unprocessed set of values passed to this request.
	Raw url.Values
}

func ParseAuthRequest

func ParseAuthRequest(req *http.Request) (authReq *AuthRequest, err error)

ParseAuthRequest can be used to process an oauth2 authentication request, returning information about it. It can handle both the code and implicit auth types. If an error is returned, it should be passed to the user via writeError

https://tools.ietf.org/html/rfc6749#section-4.1.1 https://tools.ietf.org/html/rfc6749#section-4.2.1

type BearerError

type BearerError struct {
	Realm       string
	Code        BearerErrorCode
	Description string
}

BearerError represents the contents that can be returned in the www-authenticate header for requests failing to auth under oauth2 bearer token usage

https://tools.ietf.org/html/rfc6750#section-3

func (*BearerError) String

func (b *BearerError) String() string

String encodes the error in a format suitible for including in a www-authenticate header

type BearerErrorCode

type BearerErrorCode string
const (
	// The request is missing a required parameter, includes an unsupported
	// parameter or parameter value, repeats the same parameter, uses more than
	// one method for including an access token, or is otherwise malformed.  The
	// resource server SHOULD respond with the HTTP 400 (Bad Request) status
	// code.
	BearerErrorCodeInvalidRequest BearerErrorCode = "invalid_request"
	// The access token provided is expired, revoked, malformed, or invalid for
	// other reasons.  The resource SHOULD respond with the HTTP 401
	// (Unauthorized) status code.  The client MAY request a new access token
	// and retry the protected resource request.
	BearerErrorCodeInvalidToken BearerErrorCode = "invalid_token"
	// The request requires higher privileges than provided by the access token.
	// The resource server SHOULD respond with the HTTP 403 (Forbidden) status
	// code and MAY include the "scope" attribute with the scope necessary to
	// access the protected resource.
	BearerErrorCodeInsufficientScope BearerErrorCode = "insufficient_scope"
)

https://tools.ietf.org/html/rfc6750#section-3.1 nolint:unused,varcheck,deadcode

type CodeAuthResponse

type CodeAuthResponse struct {
	RedirectURI *url.URL
	State       string
	Code        string
}

func (*CodeAuthResponse) ToRedirectURI

func (c *CodeAuthResponse) ToRedirectURI() *url.URL

ToRedirectURI builds a redirect URI to direct the user to for this response.

type GrantType

type GrantType string
const (
	GrantTypeAuthorizationCode GrantType = "authorization_code"
	GrantTypeRefreshToken      GrantType = "refresh_token"
)

type HTTPError

type HTTPError struct {
	Code int
	// Message is presented to the user, so this should be considered.
	// if it's not set, "Internal error" will be used.
	Message string
	// cause message is presented in the Error() output, so it should be used
	// for internal text
	CauseMsg string
	Cause    error
	// WWWAuthenticate is passed in the appropriate header field in the response
	WWWAuthenticate string
}

func (*HTTPError) Error

func (h *HTTPError) Error() string

func (*HTTPError) Unwrap

func (h *HTTPError) Unwrap() error

type ResponseType

type ResponseType string
const (
	ResponseTypeCode     ResponseType = "code"
	ResponseTypeImplicit ResponseType = "token"

	CodeChallengeMethodS256 = "S256"
)

type TokenAuthResponse

type TokenAuthResponse struct {
	RedirectURI *url.URL
	State       string
	Token       string
	TokenType   TokenType
	Scopes      []string
	ExpiresIn   time.Duration
}

type TokenError

type TokenError struct {
	// ErrorCode indicates the type of error that occurred
	ErrorCode TokenErrorCode `json:"error,omitempty"`
	// Description: OPTIONAL.  Human-readable ASCII [USASCII] text providing
	// additional information, used to assist the client developer in
	// understanding the error that occurred. Values for the "error_description"
	// parameter MUST NOT include characters outside the set %x20-21 / %x23-5B /
	// %x5D-7E.
	Description string `json:"error_description,omitempty"`
	// ErrorURI: OPTIONAL.  A URI identifying a human-readable web page with
	// information about the error, used to provide the client developer with
	// additional information about the error. Values for the "error_uri"
	// parameter MUST conform to the URI-reference syntax and thus MUST NOT
	// include characters outside the set %x21 / %x23-5B / %x5D-7E.
	ErrorURI string `json:"error_uri,omitempty"`
	// 	WWWAuthenticate is set when an invalid_client error is returned, and
	// 	that response indicates the authentication scheme to be used by the
	// 	client
	WWWAuthenticate string `json:"-"`
	// Cause wraps any upstream error that resulted in this token being issued,
	// if this error should be unrwappable
	Cause error `json:"-"`
}

TokenError represents an error returned from calling the token endpoint.

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

func (*TokenError) Error

func (t *TokenError) Error() string

Error returns a string representing this error

func (*TokenError) Unwrap

func (t *TokenError) Unwrap() error

type TokenErrorCode

type TokenErrorCode string

TokenErrorCode are the types of error that can be returned

const (
	// TokenErrorCodeInvalidRequest: The request is missing a required
	// parameter, includes an unsupported parameter value (other than grant
	// type), repeats a parameter, includes multiple credentials, utilizes more
	// than one mechanism for authenticating the client, or is otherwise
	// malformed.
	TokenErrorCodeInvalidRequest TokenErrorCode = "invalid_request"
	// TokenErrorCodeInvalidClient: Client authentication failed (e.g., unknown
	// client, no client authentication included, or unsupported authentication
	// method).  The authorization server MAY return an HTTP 401 (Unauthorized)
	// status code to indicate which HTTP authentication schemes are supported.
	// If the client attempted to authenticate via the "Authorization" request
	// header field, the authorization server MUST respond with an HTTP 401
	// (Unauthorized) status code and include the "WWW-Authenticate" response
	// header field matching the authentication scheme used by the client.
	TokenErrorCodeInvalidClient TokenErrorCode = "invalid_client"
	// TokenErrorCodeInvalidGrant: 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.
	TokenErrorCodeInvalidGrant TokenErrorCode = "invalid_grant"
	// TokenErrorCodeUnauthorizedClient: The authenticated client is not
	// authorized to use this authorization grant type.
	TokenErrorCodeUnauthorizedClient TokenErrorCode = "unauthorized_client"
	// TokenErrorCodeUnsupportedGrantType: The authorization grant type is not
	// supported by the authorization server.
	TokenErrorCodeUnsupportedGrantType TokenErrorCode = "unsupported_grant_type"
	// TokenErrorCodeInvalidScope: The requested scope is invalid, unknown,
	// malformed, or exceeds the scope granted by the resource owner.
	TokenErrorCodeInvalidScope TokenErrorCode = "invalid_scope"
)

https://tools.ietf.org/html/rfc6749#section-5.2 nolint:unused,varcheck,deadcode

type TokenRequest

type TokenRequest struct {
	GrantType    GrantType
	Code         string
	RefreshToken string
	RedirectURI  string
	ClientID     string
	ClientSecret string
	// CodeVerifier is the PKCE code verifier, if it was submitted with this
	// request.
	CodeVerifier string
}

func ParseTokenRequest

func ParseTokenRequest(req *http.Request) (*TokenRequest, error)

ParseTokenRequest parses the information from a request for an access token.

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

type TokenResponse

type TokenResponse struct {
	AccessToken  string
	TokenType    string
	ExpiresIn    time.Duration
	RefreshToken string
	Scopes       []string
	ExtraParams  map[string]interface{}
}

TokenResponse ref: https://tools.ietf.org/html/rfc6749#section-5.1

this does eventually end up as JSON, but because of how we want to handle the extra params bit we don't tag this struct

type TokenType

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

Jump to

Keyboard shortcuts

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