goauth

package module
v0.22.3 Latest Latest
Warning

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

Go to latest
Published: Nov 10, 2024 License: MIT Imports: 30 Imported by: 39

README

GoAuth

Build Status Go Report Card CodeClimate Docs License

GoAuth provides helper libraries for authentication in Go, with a focus on API services. It covers OAuth 2.0, JWT, TLS client authentication and Basic Auth. A primary goal is to be able to create a *http.Client from a single JSON application definition.

Major features include:

  1. The base goauth package is designed to provide a single file format for handling configuration of all methods of authentication, including BasicAuth, OAuth 2.0, and JWT credentials. The primary use case is to have a single JSON definition of multiple applications for multiple services which can be used to generate token and API requests. It works with goauth/endpoints to add endpoints for known services.
  2. Create *http.Client for multiple API services. Use NewClient() functions to create *http.Client structs for services not supported in oauth2 like aha, metabase, ringcentral, salesforce, visa, etc. Generating *http.Client structs is especially useful for using with Swagger Codegen auto-generated SDKs to support different auth models.
  3. Create OAuth 2.0 authorization code token from the command line (for test purposes). No website is needed.
  4. Retrieve canonical user information via helper libraries to retrieve canonical user information from services. The SCIM user schema is used for a canonical user model. This may be replaced/augmented by OIDC userinfo in the future.
  5. Transparently handle OAuth 2 for multiple services, e.g. a website that supports Google and Facebook auth. This is demoed in github.com/grokify/beegoutil

Installation

$ go get github.com/grokify/goauth

Usage

Canonical User Information

ClientUtil structs satisfy the interface having SetClient() and GetSCIMUser() functions.

Google
import(
	"github.com/grokify/goauth/google"
)

// googleOAuth2HTTPClient is *http.Client from Golang OAuth2
googleClientUtil := google.NewClientUtil(googleOAuth2HTTPClient)
scimuser, err := googleClientUtil.GetSCIMUser()
Facebook
import(
	"github.com/grokify/goauth/facebook"
)

// fbOAuth2HTTPClient is *http.Client from Golang OAuth2
fbClientUtil := facebook.NewClientUtil(fbOAuth2HTTPClient)
scimuser, err := fbClientUtil.GetSCIMUser()
RingCentral
import(
	"github.com/grokify/goauth/ringcentral"
)

// rcOAuth2HTTPClient is *http.Client from Golang OAuth2
rcClientUtil := ringcentral.NewClientUtil(rcOAuth2HTTPClient)
scimuser, err := rcClientUtil.GetSCIMUser()

Test Redirect URL

This repo comes with a generic test OAuth 2 redirect page which can be used with headless (no-UI) apps. To use this test URL, configure the following URL to be your OAuth 2 redirect URI. This will write the Authorization Code in the HTMl which you can then copy and paste into your own app.

The URL is located here:

Example App

See the following repo for a Beego-based demo app:

Documentation

Index

Constants

View Source
const (
	TypeBasic       = "basic"
	TypeHeaderQuery = "headerquery"
	TypeOAuth2      = "oauth2"
	TypeJWT         = "jwt"
	TypeGCPSA       = "gcpsa" // Google Cloud Platform Service Account
)
View Source
const (
	SigningMethodES256 = "ES256"
	SigningMethodES384 = "ES384"
	SigningMethodES512 = "ES512"
	SigningMethodHS256 = "HS256"
	SigningMethodHS384 = "HS384"
	SigningMethodHS512 = "HS512"
)

Variables

View Source
var (
	ErrBasicAuthNotPopulated   = errors.New("basic auth is not populated")
	ErrHeaderQueryNotPopulated = errors.New("header query is not populated")
	ErrJWTNotPopulated         = errors.New("jwt is not populated")
	ErrJWTNotSupported         = errors.New("jwt is not supported for function")
	ErrOAuth2NotPopulated      = errors.New("oauth2 is not populated")
	ErrTypeNotSupported        = errors.New("credentials type not supported")
	ErrGCPSANotPopulated       = errors.New("gcp service account credentials are not populated")
)

Functions

func NewClient added in v0.21.9

func NewClient(ctx context.Context, goauthfile, goauthkey string) (*http.Client, error)

func NewTokenCLI added in v0.18.0

func NewTokenCLI(ctx context.Context, creds Credentials, state string) (token *oauth2.Token, err error)

Types

type AuthCodeOptions added in v0.18.0

type AuthCodeOptions []oauth2.AuthCodeOption

func (*AuthCodeOptions) Add added in v0.18.0

func (opts *AuthCodeOptions) Add(k, v string)

func (*AuthCodeOptions) AddMap added in v0.18.0

func (opts *AuthCodeOptions) AddMap(m map[string][]string)

type Credentials added in v0.18.0

type Credentials struct {
	Service     string                  `json:"service,omitempty"`
	Type        string                  `json:"type,omitempty"`
	Subdomain   string                  `json:"subdomain,omitempty"`
	Basic       *CredentialsBasicAuth   `json:"basic,omitempty"`
	HeaderQuery *CredentialsHeaderQuery `json:"headerquery,omitempty"`
	GCPSA       *CredentialsGCP         `json:"gcpsa,omitempty"`
	JWT         *CredentialsJWT         `json:"jwt,omitempty"`
	OAuth2      *CredentialsOAuth2      `json:"oauth2,omitempty"`
	Token       *oauth2.Token           `json:"token,omitempty"`
	Additional  url.Values              `json:"additional,omitempty"`
}

func NewCredentialsJSON added in v0.18.0

func NewCredentialsJSON(credsData, accessToken []byte) (Credentials, error)

func ReadCredentialsFromSetFile added in v0.22.1

func ReadCredentialsFromSetFile(credentialsSetFilename, accountKey string, inclAccountsOnError bool) (Credentials, error)

func (*Credentials) Inflate added in v0.18.0

func (creds *Credentials) Inflate() error

func (*Credentials) NewClient added in v0.18.0

func (creds *Credentials) NewClient(ctx context.Context) (*http.Client, error)

func (*Credentials) NewClientCLI added in v0.18.0

func (creds *Credentials) NewClientCLI(ctx context.Context, oauth2State string) (*http.Client, error)

func (*Credentials) NewSimpleClient added in v0.18.0

func (creds *Credentials) NewSimpleClient(ctx context.Context) (*httpsimple.Client, error)

func (*Credentials) NewSimpleClientHTTP added in v0.18.0

func (creds *Credentials) NewSimpleClientHTTP(httpClient *http.Client) (*httpsimple.Client, error)

func (*Credentials) NewToken added in v0.18.0

func (creds *Credentials) NewToken(ctx context.Context) (*oauth2.Token, error)

func (*Credentials) NewTokenCLI added in v0.18.0

func (creds *Credentials) NewTokenCLI(ctx context.Context, oauth2State string) (*oauth2.Token, error)

NewTokenCLI retrieves a token using CLI approach for OAuth 2.0 authorization code or password grant.

type CredentialsBasicAuth added in v0.18.0

type CredentialsBasicAuth struct {
	Username      string            `json:"username,omitempty"`
	Password      string            `json:"password,omitempty"`
	Encoded       string            `json:"encoded,omitempty"`
	ServerURL     string            `json:"serverURL,omitempty"`
	AllowInsecure bool              `json:"allowInsecure,omitempty"`
	Metadata      map[string]string `json:"metadata,omitempty"`
}

func (*CredentialsBasicAuth) NewClient added in v0.18.0

func (c *CredentialsBasicAuth) NewClient() (*http.Client, error)

func (*CredentialsBasicAuth) NewSimpleClient added in v0.18.0

func (c *CredentialsBasicAuth) NewSimpleClient() (httpsimple.Client, error)

type CredentialsGCP added in v0.20.0

type CredentialsGCP struct {
	GCPCredentials google.Credentials `json:"gcpCredentials,omitempty"`
	Scopes         []string           `json:"scopes,omitempty"`
}

CredentialsOAuth2 supports OAuth 2.0 authorization_code, password, and client_credentials grant flows.

func CredentialsGCPReadFile added in v0.20.0

func CredentialsGCPReadFile(name string) (*CredentialsGCP, error)

func (*CredentialsGCP) NewClient added in v0.20.0

func (cg *CredentialsGCP) NewClient(ctx context.Context) (*http.Client, error)

NewClient returns a `*http.Client` and `error`.

type CredentialsHeaderQuery added in v0.18.0

type CredentialsHeaderQuery struct {
	ServerURL     string      `json:"serverURL,omitempty"`
	Header        http.Header `json:"header,omitempty"`
	Query         url.Values  `json:"query,omitempty"`
	AllowInsecure bool        `json:"allowInsecure,omitempty"`
}

func (*CredentialsHeaderQuery) NewClient added in v0.18.0

func (c *CredentialsHeaderQuery) NewClient() *http.Client

func (*CredentialsHeaderQuery) NewSimpleClient added in v0.18.0

func (c *CredentialsHeaderQuery) NewSimpleClient() httpsimple.Client

type CredentialsJWT added in v0.18.0

type CredentialsJWT struct {
	Issuer        string `json:"issuer,omitempty"`
	PrivateKey    string `json:"privateKey,omitempty"`
	SigningMethod string `json:"signingMethod,omitempty"`
}

func (*CredentialsJWT) StandardToken added in v0.18.0

func (jc *CredentialsJWT) StandardToken(tokenDuration time.Duration) (*jwt.Token, string, error)

type CredentialsOAuth2 added in v0.18.0

type CredentialsOAuth2 struct {
	ServerURL            string              `json:"serverURL,omitempty"`
	ApplicationID        string              `json:"applicationID,omitempty"`
	ClientID             string              `json:"clientID,omitempty"`
	ClientSecret         string              `json:"clientSecret,omitempty"`
	Endpoint             oauth2.Endpoint     `json:"endpoint,omitempty"`
	RedirectURL          string              `json:"redirectURL,omitempty"`
	OAuthEndpointID      string              `json:"oauthEndpointID,omitempty"`
	Scopes               []string            `json:"scope,omitempty"`
	GrantType            string              `json:"grantType,omitempty"`
	PKCE                 bool                `json:"pkce"`
	Username             string              `json:"username,omitempty"`
	Password             string              `json:"password,omitempty"`
	JWT                  string              `json:"jwt,omitempty"`
	Token                *oauth2.Token       `json:"token,omitempty"`
	AuthCodeOpts         map[string][]string `json:"authCodeOpts,omitempty"`
	AuthCodeExchangeOpts map[string][]string `json:"authCodeExchangeOpts,omitempty"`
	TokenBodyOpts        url.Values          `json:"tokenBodyOpts,omitempty"`
	Metadata             map[string]string   `json:"metadata,omitempty"`
}

CredentialsOAuth2 supports OAuth 2.0 authorization_code, password, and client_credentials grant flows.

func NewCredentialsOAuth2Env added in v0.18.0

func NewCredentialsOAuth2Env(envPrefix string) CredentialsOAuth2

func ParseCredentialsOAuth2 added in v0.18.0

func ParseCredentialsOAuth2(b []byte) (CredentialsOAuth2, error)

func (*CredentialsOAuth2) AuthCodeURL added in v0.18.0

func (oc *CredentialsOAuth2) AuthCodeURL(state string, opts map[string][]string) string

func (*CredentialsOAuth2) BasicAuthHeader added in v0.18.0

func (oc *CredentialsOAuth2) BasicAuthHeader() (string, error)

func (*CredentialsOAuth2) Config added in v0.18.0

func (oc *CredentialsOAuth2) Config() oauth2.Config

func (*CredentialsOAuth2) ConfigClientCredentials added in v0.18.0

func (oc *CredentialsOAuth2) ConfigClientCredentials() clientcredentials.Config

func (*CredentialsOAuth2) Exchange added in v0.18.0

func (oc *CredentialsOAuth2) Exchange(ctx context.Context, code string, opts map[string][]string) (*oauth2.Token, error)

func (*CredentialsOAuth2) InflateURL added in v0.18.0

func (oc *CredentialsOAuth2) InflateURL(apiURLPath string) string

func (*CredentialsOAuth2) IsGrantType added in v0.18.0

func (oc *CredentialsOAuth2) IsGrantType(grantType string) bool

func (*CredentialsOAuth2) MarshalJSON added in v0.18.0

func (oc *CredentialsOAuth2) MarshalJSON(prefix, indent string) ([]byte, error)

MarshalJSON returns JSON. It is useful for exporting creating configs to be parsed.

func (*CredentialsOAuth2) NewClient added in v0.18.0

func (oc *CredentialsOAuth2) NewClient(ctx context.Context) (*http.Client, *oauth2.Token, error)

func (*CredentialsOAuth2) NewSimpleClient added in v0.21.0

func (oc *CredentialsOAuth2) NewSimpleClient(ctx context.Context) (*httpsimple.Client, error)

func (*CredentialsOAuth2) NewToken added in v0.18.0

func (oc *CredentialsOAuth2) NewToken(ctx context.Context) (*oauth2.Token, error)

NewToken retrieves an `*oauth2.Token` when the requisite information is available. Note this uses `clientcredentials.Config.Token()` which doesn't always work. In This situation, use `authutil.TokenClientCredentials()` as an alternative. Note: authorization code is only supported for CLI testing purposes. In a production application, it should be done in a multi-step process to redirect the user to the authorization URL, retrieve the auth code and then `Exchange` it for a token. The `state` value is currently a randomly generated string as this should be used for testing purposes only.

func (*CredentialsOAuth2) NewTokenPasswordCredentials added in v0.21.2

func (oc *CredentialsOAuth2) NewTokenPasswordCredentials(ctx context.Context) (*oauth2.Token, error)

NewTokenPasswordCredentials provides fine-grained token request.

func (*CredentialsOAuth2) PasswordRequestBody added in v0.18.0

func (oc *CredentialsOAuth2) PasswordRequestBody() url.Values

func (*CredentialsOAuth2) RefreshToken added in v0.18.0

func (oc *CredentialsOAuth2) RefreshToken(ctx context.Context, tok *oauth2.Token) (*oauth2.Token, []byte, error)

func (*CredentialsOAuth2) RefreshTokenSimple added in v0.18.0

func (oc *CredentialsOAuth2) RefreshTokenSimple(ctx context.Context, refreshToken string) (*oauth2.Token, []byte, error)

type CredentialsSet added in v0.18.0

type CredentialsSet struct {
	Credentials map[string]Credentials `json:"credentials,omitempty"`
}

func ReadFileCredentialsSet added in v0.18.0

func ReadFileCredentialsSet(credentialsSetFilename string, inflateEndpoints bool) (*CredentialsSet, error)

func (*CredentialsSet) Accounts added in v0.18.0

func (set *CredentialsSet) Accounts() []string

func (*CredentialsSet) Get added in v0.18.0

func (set *CredentialsSet) Get(key string) (Credentials, error)

func (*CredentialsSet) Inflate added in v0.18.0

func (set *CredentialsSet) Inflate() error

func (*CredentialsSet) Keys added in v0.18.0

func (set *CredentialsSet) Keys() []string

func (*CredentialsSet) NewClient added in v0.20.0

func (set *CredentialsSet) NewClient(ctx context.Context, key string) (*http.Client, error)

func (*CredentialsSet) WriteFile added in v0.18.0

func (set *CredentialsSet) WriteFile(filename, prefix, indent string, perm fs.FileMode) error

type Options added in v0.18.0

type Options struct {
	CredsPath string `long:"creds" description:"Environment File Path" required:"true"`
	Account   string `long:"account" description:"Environment Variable Name"`
	Token     string `long:"token" description:"Token"`
	CLI       []bool `long:"cli" description:"CLI"`
}

Options is a struct to be used with `ParseOptions()` or `github.com/jessevdk/go-flags`. It can be embedded in another struct and used directly with `github.com/jessevdk/go-flags`.

func ParseOptions added in v0.22.1

func ParseOptions() (*Options, error)

func (*Options) Credentials added in v0.22.0

func (opts *Options) Credentials() (Credentials, error)

func (*Options) CredentialsSet added in v0.22.1

func (opts *Options) CredentialsSet(inflateEndpoints bool) (*CredentialsSet, error)

func (*Options) NewClient added in v0.22.1

func (opts *Options) NewClient(ctx context.Context) (*http.Client, error)

func (*Options) UseCLI added in v0.18.0

func (opts *Options) UseCLI() bool

Directories

Path Synopsis
aha
auth0 contains a Go implementation of Auth0's PKCE support: https://auth0.com/docs/api-auth/tutorials/authorization-code-grant-pkce
auth0 contains a Go implementation of Auth0's PKCE support: https://auth0.com/docs/api-auth/tutorials/authorization-code-grant-pkce
cmd
jwt
examples
jwt
examples/send_ics
This package posts an ICS file to Gmail.
This package posts an ICS file to Gmail.
util

Jump to

Keyboard shortcuts

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