oauth

package
v0.0.0-...-bc49051 Latest Latest
Warning

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

Go to latest
Published: Mar 27, 2024 License: MIT Imports: 17 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// GoogleKeysURL is the url we fetch google's public verification keys in JWK form.
	GoogleKeysURL = "https://www.googleapis.com/oauth2/v3/certs"
	// GoogleIssuer is the expected `iss` field on JWTs from google.
	GoogleIssuer = "https://accounts.google.com"
	// GoogleIssuerAlternate is the alternate expected `iss` field on JWTs from google.
	GoogleIssuerAlternate = "accounts.google.com"
)

Variables

View Source
var (
	// DefaultScopes is the default oauth scopes.
	DefaultScopes = []string{
		oidc.ScopeOpenID,
		"email",
		"profile",
	}
)

Functions

func MustSerializeState

func MustSerializeState(state State) string

MustSerializeState serializes a state value but panics if there is an error.

func SerializeState

func SerializeState(state State) (output string, err error)

SerializeState serializes the oauth state.

Types

type Config

type Config struct {
	// ClientID is part of the oauth credential pair.
	ClientID string `json:"clientID,omitempty" yaml:"clientID,omitempty"`
	// ClientSecret is part of the oauth credential pair.
	ClientSecret string `json:"clientSecret,omitempty" yaml:"clientSecret,omitempty"`
	// Secret is an encryption key used to verify oauth state.
	Secret string `json:"secret,omitempty" yaml:"secret,omitempty"`
	// RedirectURL is the oauth return url.
	RedirectURL string `json:"redirectURL,omitempty" yaml:"redirectURL,omitempty"`
	// HostedDomain is a specific domain we want to filter identities to.
	HostedDomain string `json:"hostedDomain,omitempty" yaml:"hostedDomain,omitempty"`
	// AllowedDomains is a strict list of hosted domains to allow authenticated users from.
	// If it is unset or empty, it will allow users from *any* hosted domain.
	AllowedDomains []string `json:"allowedDomains,omitempty" yaml:"allowedDomains,omitempty"`
	// Scopes are oauth scopes to request.
	Scopes []string `json:"scopes,omitempty" yaml:"scopes,omitempty"`
}

Config is the config options.

func (Config) DecodeSecret

func (c Config) DecodeSecret() ([]byte, error)

DecodeSecret decodes the secret if set from hex encoding.

func (Config) GenerateSecret

func (c Config) GenerateSecret(_ context.Context) (*string, error)

GenerateSecret generates a secret.

func (Config) IsZero

func (c Config) IsZero() bool

IsZero returns if the config is set or not.

func (*Config) Resolve

func (c *Config) Resolve(ctx context.Context) error

Resolve adds extra steps to perform during `configutil.Read(...)`.

func (Config) ScopesOrDefault

func (c Config) ScopesOrDefault() []string

ScopesOrDefault returns the scopes or a default set.

type Error

type Error string

Error is an error string.

const (
	// ErrCodeMissing is returned if the code was missing from an oauth return request.
	ErrCodeMissing Error = "state missing from request"
	// ErrStateMissing is returned if the state was missing from an oauth return request.
	ErrStateMissing Error = "state missing from request"
	// ErrInvalidHostedDomain is an error returned if the JWT hosted zone doesn't match any of the whitelisted domains.
	ErrInvalidHostedDomain Error = "hosted domain validation failed"
	// ErrInvalidAntiforgeryToken is an error returns on oauth finish that indicates we didn't originate the auth request.
	ErrInvalidAntiforgeryToken Error = "invalid anti-forgery token"

	// ErrInvalidJWTAudience is an error in validing the token jwt.
	ErrInvalidJWTAudience Error = "invalid jwt audience; should match clientID"
	// ErrInvalidJWTIssuer is an error in validing the token jwt.
	ErrInvalidJWTIssuer Error = "invalid jwt issuer; should be a valid google issuer"
	// ErrInvalidJWTHostedDomain is an error in validing the token jwt.
	ErrInvalidJWTHostedDomain Error = "invalid jwt hosted domain; must be in the allowed domain list"
	// ErrInvalidJWT is returned when we fail to decode or verify the token jwt.
	ErrInvalidJWT Error = "invalid jwt; failed to decode or verify"

	// ErrProfileJSONUnmarshal is an error returned if the json unmarshal failed.
	ErrProfileJSONUnmarshal Error = "profile json unmarshal failed"

	// ErrFailedCodeExchange happens if the code exchange for an access token fails.
	ErrFailedCodeExchange Error = "oauth code exchange failed"
	// ErrGoogleResponseStatus is an error that can occur when querying the google apis.
	ErrGoogleResponseStatus Error = "google returned a non 2xx response"

	// ErrSecretRequired is a configuration error indicating we did not provide a secret.
	ErrSecretRequired Error = "manager secret required"
	// ErrClientIDRequired is a self validation error.
	ErrClientIDRequired Error = "clientID is required"
	// ErrClientSecretRequired is a self validation error.
	ErrClientSecretRequired Error = "clientSecret is required"
	// ErrRedirectURIRequired is a self validation error.
	ErrRedirectURIRequired Error = "redirectURI is required"
	// ErrInvalidRedirectURI is an error in validating the redirect uri.
	ErrInvalidRedirectURI Error = "invalid redirectURI"
)

func (Error) Error

func (e Error) Error() string

Error returns the error as a string.

type GoogleClaims

type GoogleClaims struct {
	Email         string `json:"email"`
	EmailVerified bool   `json:"email_verified"`
	HD            string `json:"hd"`
	Nonce         string `json:"nonce"`
	FamilyName    string `json:"family_name"`
	GivenName     string `json:"given_name"`
	Locale        string `json:"locale"`
	Picture       string `json:"picture"`
	Profile       string `json:"profile"`
}

GoogleClaims are extensions to the jwt standard claims for google oauth.

See additional documentation here: https://developers.google.com/identity/sign-in/web/backend-auth

type Manager

type Manager struct {
	Secret         []byte
	HostedDomain   string
	AllowedDomains []string
	// contains filtered or unexported fields
}

Manager is the oauth manager.

func MustNew

func MustNew(ctx context.Context, options ...Option) *Manager

MustNew returns a new manager mutated by a given set of options and will panic on error.

func New

func New(ctx context.Context, options ...Option) (*Manager, error)

New returns a new manager mutated by a given set of options.

func (*Manager) CreateState

func (m *Manager) CreateState(options ...StateOption) (state State)

CreateState creates auth state.

func (*Manager) FetchProfile

func (m *Manager) FetchProfile(ctx context.Context, accessToken string) (profile Profile, err error)

FetchProfile gets a google profile for an access token.

func (*Manager) Finish

func (m *Manager) Finish(r *http.Request) (result *Result, err error)

Finish processes the returned code, exchanging for an access token, and fetches the user profile.

func (*Manager) OAuthURL

func (m *Manager) OAuthURL(r *http.Request, stateOptions ...StateOption) (oauthURL string, err error)

OAuthURL is the auth url for google with a given clientID. This is typically the link that a user will click on to start the auth process.

func (*Manager) ValidateState

func (m *Manager) ValidateState(state State) error

ValidateState validates oauth state.

type Option

type Option func(*Manager) error

Option is an option for oauth managers.

func OptAllowedDomains

func OptAllowedDomains(allowedDomains ...string) Option

OptAllowedDomains sets the manager allowedDomains.

func OptClientID

func OptClientID(cliendID string) Option

OptClientID sets the manager cliendID.

func OptClientSecret

func OptClientSecret(clientSecret string) Option

OptClientSecret sets the manager clientSecret.

func OptConfig

func OptConfig(cfg Config) Option

OptConfig sets a manager based on a config.

func OptHostedDomain

func OptHostedDomain(hostedDomain string) Option

OptHostedDomain sets the manager hostedDomain.

func OptRedirectURL

func OptRedirectURL(redirectURL string) Option

OptRedirectURL sets the manager redirectURI.

func OptScopes

func OptScopes(scopes ...string) Option

OptScopes sets the manager scopes.

func OptSecret

func OptSecret(secret []byte) Option

OptSecret sets the manager secret.

type Profile

type Profile struct {
	ID            string `json:"id"`
	Email         string `json:"email"`
	VerifiedEmail bool   `json:"verified_email"`
	Name          string `json:"name"`
	GivenName     string `json:"given_name"`
	FamilyName    string `json:"family_name"`
	Link          string `json:"link"`
	Gender        string `json:"gender"`
	Locale        string `json:"locale"`
	PictureURL    string `json:"picture"`
}

Profile is a profile with google.

type Response

type Response struct {
	AccessToken  string
	TokenType    string
	RefreshToken string
	Expiry       time.Time
	HostedDomain string
}

Response is the response details from the oauth exchange.

type Result

type Result struct {
	Response Response
	Profile  Profile
	State    State
}

Result is the final result of the oauth exchange. It is the user profile of the user and the state information.

type State

type State struct {
	// Token is a plaintext random token.
	Token string
	// SecureToken is the hashed version of the token.
	// If a key is set, it validates that our app created the oauth state.
	SecureToken string
	// RedirectURI is the redirect uri.
	RedirectURI string
	// Extra includes other state you might need to encode.
	Extra map[string]interface{}
}

State is the oauth state.

func DeserializeState

func DeserializeState(raw string) (state State, err error)

DeserializeState deserializes the oauth state.

type StateOption

type StateOption func(*State)

StateOption is an option for state objects

func OptStateExtra

func OptStateExtra(key string, value interface{}) StateOption

OptStateExtra sets the redirect uri on the stae.

func OptStateRedirectURI

func OptStateRedirectURI(redirectURI string) StateOption

OptStateRedirectURI sets the redirect uri on the stae.

func OptStateSecureToken

func OptStateSecureToken(secureToken string) StateOption

OptStateSecureToken sets the secure token on the state.

Jump to

Keyboard shortcuts

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