oauth2

package module
v0.0.0-...-78f10ff Latest Latest
Warning

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

Go to latest
Published: Feb 26, 2024 License: MIT Imports: 11 Imported by: 3

README

go-oauth2

Go Reference builds.sr.ht status

A lightweight library for OAuth 2.0.

Contributing

Send patches on the mailing list. Discuss in #emersion on Libera Chat.

License

MIT

Documentation

Overview

Package oauth2 implements OAuth 2.0 specified in RFC 6749.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type AuthMethod

type AuthMethod string

AuthMethod indicates how the token endpoint authenticates requests.

See RFC 7591 section 2.

const (
	AuthMethodNone              AuthMethod = "none"
	AuthMethodClientSecretPost  AuthMethod = "client_secret_post"
	AuthMethodClientSecretBasic AuthMethod = "client_secret_basic"
)

type AuthorizationCodeResp

type AuthorizationCodeResp struct {
	Code  string
	State string
	Iss   string // issuer identifier
}

AuthorizationCodeResp contains the data returned by the authorization endpoint with a code grant.

type AuthorizationOptions

type AuthorizationOptions struct {
	Scope []string
	State string

	// RFC 9470 section 4
	ACRValues []string
	MaxAge    time.Duration
}

AuthorizationOptions are optional parameters for the authorization endpoint.

type Client

type Client struct {
	HTTPClient   *http.Client // optional, defaults to http.DefaultClient
	Server       *ServerMetadata
	ClientID     string
	ClientSecret string // optional
	RedirectURI  string // optional
}

Client is an OAuth 2.0 client.

func (*Client) AuthorizationCodeURL

func (c *Client) AuthorizationCodeURL(options *AuthorizationOptions) string

AuthorizationCodeURL returns the URL to redirect the user to to initiate OAuth 2.0 authorization.

The caller will typically use Client.ParseAuthorizationCodeResp once the user is redirected back.

func (*Client) DeviceAuth

func (c *Client) DeviceAuth(ctx context.Context, options *DeviceAuthOptions) (*DeviceAuthResp, error)

DeviceAuth performs the device authorisation request.

See RFC 8628.

func (*Client) Exchange

func (c *Client) Exchange(ctx context.Context, code string) (*TokenResp, error)

Exchange sends a request to the token endpoint to exchange a code.

func (*Client) Introspect

func (c *Client) Introspect(ctx context.Context, token string) (*IntrospectionResp, error)

Introspect performs token introspection for an access or refresh token.

See RFC 7662.

func (*Client) NewHTTPClient

func (c *Client) NewHTTPClient(tokenResp *TokenResp) *http.Client

NewHTTPClient returns a new HTTP client which adds OAuth 2.0 credentials to outgoing requests.

The token response must include a bearer token, or else nil is returned.

func (*Client) ObtainClientToken

func (c *Client) ObtainClientToken(ctx context.Context, options *ClientTokenOptions) (*TokenResp, error)

ObtainClientToken obtains an access token from client credentials only.

func (*Client) ParseAuthorizationCodeResp

func (c *Client) ParseAuthorizationCodeResp(u *url.URL) (*AuthorizationCodeResp, error)

ParseAuthorizationCodeResp parses an authorization response from URL query parameters.

The caller will typically use Client.Exchange to obtain an access token from the authorization code.

func (*Client) PollDeviceToken

func (c *Client) PollDeviceToken(ctx context.Context, auth *DeviceAuthResp) (*TokenResp, error)

PollDeviceToken performs the device authorisation request, polling the endpoint until such time that either the server responds with a token, the device code times out, or the server responds with an error.

See RFC 8628.

func (*Client) Refresh

func (c *Client) Refresh(ctx context.Context, refreshToken string, options *RefreshTokenOptions) (*TokenResp, error)

Refresh obtains a fresh access token from a refresh token.

func (*Client) Register

func (c *Client) Register(ctx context.Context, metadata *ClientMetadata, options *RegisterOptions) (*RegisterResp, error)

Register registers a new OAuth client.

See RFC 7591 section 3.

func (*Client) Revoke

func (c *Client) Revoke(ctx context.Context, token string) error

Revoke revokes an access or refresh token.

See RFC 7009.

type ClientMetadata

type ClientMetadata struct {
	RedirectURIs            []string       `json:"redirect_uris,omitempty"`
	TokenEndpointAuthMethod AuthMethod     `json:"token_endpoint_auth_method,omitempty"`
	GrantTypes              []GrantType    `json:"grant_types,omitempty"`
	ResponseTypes           []ResponseType `json:"response_types,omitempty"`
	ClientName              string         `json:"client_name,omitempty"`
	ClientURI               string         `json:"client_uri,omitempty"`
	LogoURI                 string         `json:"logo_uri,omitempty"`
	Scope                   []string       `json:"-"`
	Contacts                []string       `json:"contacts,omitempty"`
	TOSURI                  string         `json:"tos_uri,omitempty"`
	PolicyURI               string         `json:"policy_uri,omitempty"`
	JWKSURI                 string         `json:"jwks_uri,omitempty"`
	JWKS                    struct{}       `json:"jwks,omitempty"` // TODO
	SoftwareID              string         `json:"software_id,omitempty"`
	SoftwareVersion         string         `json:"software_version,omitempty"`
}

ClientMetadata contains registered client metadata defined in RFC 7591.

func (*ClientMetadata) MarshalJSON

func (metadata *ClientMetadata) MarshalJSON() ([]byte, error)

MarshalJSON implements encoding/json.Marshaler.

func (*ClientMetadata) UnmarshalJSON

func (metadata *ClientMetadata) UnmarshalJSON(b []byte) error

UnmarshalJSON implements encoding/json.Unmarshaler.

type ClientTokenOptions

type ClientTokenOptions struct {
	Scope []string
}

ClientTokenOptions contains optional parameters for the token endpoint when used with the client credentials grant.

type DeviceAuthOptions

type DeviceAuthOptions struct {
	Scope []string
}

DeviceAuthOptions are optional parameters for the device authorisation endpoint.

type DeviceAuthResp

type DeviceAuthResp struct {
	DeviceCode              string        `json:"device_code"`
	UserCode                string        `json:"user_code"`
	VerificationURI         string        `json:"verification_uri"`
	VerificationURIComplete string        `json:"verification_uri_complete,omitempty"`
	ExpiresIn               time.Duration `json:"-"`
	Interval                time.Duration `json:"-"`
}

DeviceAuthResp contains the data returned by the device authorisation endpoint.

All fields except DeviceCode, UserCode and ExpiresIn are optional.

func (*DeviceAuthResp) MarshalJSON

func (dar *DeviceAuthResp) MarshalJSON() ([]byte, error)

MarshalJSON implements encoding/json.Marshaler.

func (*DeviceAuthResp) UnmarshalJSON

func (dar *DeviceAuthResp) UnmarshalJSON(b []byte) error

UnmarshalJSON implements encoding/json.Unmarshaler.

type Error

type Error struct {
	Code        ErrorCode `json:"error"`
	Description string    `json:"error_description,omitempty"`
	URI         string    `json:"error_uri,omitempty"`
	State       string    `json:"-"`
	Iss         string    `json:"-"` // issuer identifier
}

Error is an OAuth 2.0 error returned by the server.

All fields except Code are optional.

func (*Error) Error

func (err *Error) Error() string

Error implements the error interface.

type ErrorCode

type ErrorCode string

ErrorCode is an OAuth 2.0 error code.

const (
	// RFC 6749
	ErrorCodeInvalidRequest          ErrorCode = "invalid_request"
	ErrorCodeUnauthorizedClient      ErrorCode = "unauthorized_client"
	ErrorCodeAccessDenied            ErrorCode = "access_denied"
	ErrorCodeUnsupportedResponseType ErrorCode = "unsupported_response_type"
	ErrorCodeInvalidScope            ErrorCode = "invalid_scope"
	ErrorCodeServerError             ErrorCode = "server_error"
	ErrorCodeTemporarilyUnavailable  ErrorCode = "temporarily_unavailable"
	ErrorCodeInvalidClient           ErrorCode = "invalid_client"
	ErrorCodeInvalidGrant            ErrorCode = "invalid_grant"
	ErrorCodeUnsupportedGrantType    ErrorCode = "unsupported_grant_type"

	// RFC 7009
	ErrorCodeUnsupportedTokenType ErrorCode = "unsupported_token_type"

	// RFC 8628 section 3.5
	ErrorCodeAuthorizationPending ErrorCode = "authorization_pending"
	ErrorCodeSlowDown             ErrorCode = "slow_down"
	ErrorCodeExpiredToken         ErrorCode = "expired_token"

	// RFC 7591 section 3.2.2
	ErrorCodeInvalidRedirectURI          ErrorCode = "invalid_redirect_uri"
	ErrorCodeInvalidClientMetadata       ErrorCode = "invalid_client_metadata"
	ErrorCodeInvalidSoftwareStatement    ErrorCode = "invalid_software_statement"
	ErrorCodeUnapprovedSoftwareStatement ErrorCode = "unapproved_software_statement"

	// RFC 9470 section 3
	ErrorCodeInsufficientUserAuthentication ErrorCode = "insufficient_user_authentication"
)

type GrantType

type GrantType string

GrantType indicates which grant types are supported by the token endpoint.

See RFC 7591 section 2.

const (
	GrantTypeAuthorizationCode GrantType = "authorization_code"
	GrantTypeImplicit          GrantType = "implicit"
	GrantTypePassword          GrantType = "password"
	GrantTypeClientCredentials GrantType = "client_credentials"
	GrantTypeRefreshToken      GrantType = "refresh_token"
	GrantTypeJWTBearer         GrantType = "urn:ietf:params:oauth:grant-type:jwt-bearer"
	GrantTypeSAML2Bearer       GrantType = "urn:ietf:params:oauth:grant-type:saml2-bearer"

	// RFC 8628 section 4
	GrantTypeDeviceCode GrantType = "urn:ietf:params:oauth:grant-type:device_code"
)

type IntrospectionResp

type IntrospectionResp struct {
	Active    bool      `json:"active"`
	Scope     []string  `json:"-"`
	ClientID  string    `json:"client_id,omitempty"`
	Username  string    `json:"username,omitempty"`
	TokenType TokenType `json:"token_type,omitempty"`
	ExpiresAt time.Time `json:"-"`
	IssuedAt  time.Time `json:"-"`
	NotBefore time.Time `json:"-"`

	Subject  string `json:"sub,omitempty"`
	Audience string `json:"aud,omitempty"`
	Issuer   string `json:"iss,omitempty"`
	JWTID    string `json:"jti,omitempty"`

	// RFC 9470 section 6.2
	ACR      string    `json:"acr,omitempty"`
	AuthTime time.Time `json:"-"`
}

IntrospectionResp contains the data returned by the introspection endpoint.

All fields except Active are optional.

func (*IntrospectionResp) MarshalJSON

func (ir *IntrospectionResp) MarshalJSON() ([]byte, error)

MarshalJSON implements encoding/json.Marshaler.

func (*IntrospectionResp) UnmarshalJSON

func (ir *IntrospectionResp) UnmarshalJSON(b []byte) error

UnmarshalJSON implements encoding/json.Unmarshaler.

type RefreshTokenOptions

type RefreshTokenOptions struct {
	Scope []string
}

RefreshTokenOptions contains optional parameters for the token endpoint when used with the refresh token grant.

type RegisterOptions

type RegisterOptions struct {
	TokenResp *TokenResp
}

RegisterOptions contains optional parameters for client registration.

type RegisterResp

type RegisterResp struct {
	ClientID              string    `json:"client_id"`
	ClientSecret          string    `json:"client_secret,omitempty"`
	ClientIDIssuedAt      time.Time `json:"-"`
	ClientSecretExpiresAt time.Time `json:"-"`
}

RegisterResp contains data returned by the client registration endpoint.

func (*RegisterResp) MarshalJSON

func (resp *RegisterResp) MarshalJSON() ([]byte, error)

MarshalJSON implements encoding/json.Marshaler.

func (*RegisterResp) UnmarshalJSON

func (resp *RegisterResp) UnmarshalJSON(b []byte) error

UnmarshalJSON implements encoding/json.Unmarshaler.

type ResponseMode

type ResponseMode string

ResponseMode indicates how the code/token is returned from the authorization endpoint.

See: https://openid.net/specs/oauth-v2-multiple-response-types-1_0.html#ResponseModes

const (
	ResponseModeQuery    ResponseMode = "query"
	ResponseModeFragment ResponseMode = "fragment"
	ResponseModeFormPost ResponseMode = "form_post" // https://openid.net/specs/oauth-v2-form-post-response-mode-1_0.html
)

type ResponseType

type ResponseType string

ResponseType is the desired response for the authorization endpoint.

See RFC 7591 section 2.

const (
	ResponseTypeCode  ResponseType = "code"
	ResponseTypeToken ResponseType = "token"
)

type ServerMetadata

type ServerMetadata struct {
	Issuer                 string         `json:"issuer"`
	AuthorizationEndpoint  string         `json:"authorization_endpoint,omitempty"`
	TokenEndpoint          string         `json:"token_endpoint,omitempty"`
	JWKSURI                string         `json:"jwks_uri,omitempty"`
	RegistrationEndpoint   string         `json:"registration_endpoint,omitempty"`
	ScopesSupported        []string       `json:"scopes_supported,omitempty"`
	ResponseTypesSupported []ResponseType `json:"response_types_supported"`
	ResponseModesSupported []ResponseMode `json:"response_modes_supported,omitempty"`
	GrantTypesSupported    []GrantType    `json:"grant_types_supported,omitempty"`

	TokenEndpointAuthMethodsSupported          []AuthMethod `json:"token_endpoint_auth_methods_supported,omitempty"`
	TokenEndpointAuthSigningAlgValuesSupported []string     `json:"token_endpoint_auth_signing_alg_values_supported,omitempty"`

	ServiceDocumentation string   `json:"service_documentation,omitempty"`
	UILocalesSupported   []string `json:"ui_locales_supported,omitempty"`
	OpPolicyURI          string   `json:"op_policy_uri,omitempty"`
	OpTOSURI             string   `json:"op_tos_uri,omitempty"`

	RevocationEndpoint                              string       `json:"revocation_endpoint,omitempty"`
	RevocationEndpointAuthMethodsSupported          []AuthMethod `json:"revocation_endpoint_auth_methods_supported,omitempty"`
	RevocationEndpointAuthSigningAlgValuesSupported []string     `json:"revocation_endpoint_auth_signing_alg_values_supported,omitempty"`

	IntrospectionEndpoint                              string       `json:"introspection_endpoint,omitempty"`
	IntrospectionEndpointAuthMethodsSupported          []AuthMethod `json:"introspection_endpoint_auth_methods_supported,omitempty"`
	IntrospectionEndpointAuthSigningAlgValuesSupported []string     `json:"introspection_endpoint_auth_signing_alg_values_supported,omitempty"`

	CodeChallengeMethodsSupported []string `json:"code_challenge_methods_supported,omitempty"`

	// RFC 8628 section 4
	DeviceAuthorizationEndpoint string `json:"device_authorization_endpoint,omitempty"`

	// RFC 9207 section 3
	AuthorizationResponseIssParameterSupported bool `json:"authorization_response_iss_parameter_supported,omitempty"`

	// RFC 9470 section 7
	ACRValuesSupported []string `json:"acr_values_supported,omitempty"`
}

ServerMetadata contains authorization server metadata defined in RFC 8414.

All fields except Issuer are optional.

func DiscoverServerMetadata

func DiscoverServerMetadata(ctx context.Context, issuer string) (*ServerMetadata, error)

DiscoverServerMetadata fetches authorization server metadata.

type TokenResp

type TokenResp struct {
	AccessToken  string        `json:"access_token"`
	TokenType    TokenType     `json:"token_type"`
	ExpiresIn    time.Duration `json:"-"`
	RefreshToken string        `json:"refresh_token,omitempty"`
	Scope        []string      `json:"-"`
}

TokenResp is the data returned by the token endpoint.

All fields except AccessToken and TokenType are optional.

func (*TokenResp) MarshalJSON

func (tr *TokenResp) MarshalJSON() ([]byte, error)

MarshalJSON implements encoding/json.Marshaler.

func (*TokenResp) UnmarshalJSON

func (tr *TokenResp) UnmarshalJSON(b []byte) error

UnmarshalJSON implements encoding/json.Unmarshaler.

type TokenType

type TokenType string

TokenType is an access token type.

const (
	TokenTypeBearer TokenType = "bearer" // RFC 6750
	TokenTypeNA     TokenType = "n_a"    // RFC 8693 section 2.2.1
	TokenTypePoP    TokenType = "pop"    // RFC 9200
)

Jump to

Keyboard shortcuts

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