goauth

package module
v0.16.4 Latest Latest
Warning

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

Go to latest
Published: Oct 29, 2022 License: MIT Imports: 23 Imported by: 39

README

GoAuth

Build Status Go Report Card 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. 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.
  2. Generically store and retrieve multiple app credentials in a single JSON object via the credentials package. Supports BasicAuth, OAuth 2, and JWT.
  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 grokify/beego-oauth2-demo

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 (
	GrantTypeAuthorizationCode = "authorization_code"
	GrantTypeClientCredentials = "client_credentials"
	GrantTypeJWTBearer         = "urn:ietf:params:oauth:grant-type:jwt-bearer" // #nosec G101
	GrantTypePassword          = "password"
	GrantTypeRefreshToken      = "refresh_token"
	ParamAssertion             = "assertion"
	ParamGrantType             = "grant_type"
	ParamPassword              = "password"
	ParamUsername              = "usernamae"
	TokenBasic                 = "Basic"
	TokenBearer                = "Bearer"
)
View Source
const (
	VERSION = "0.10"
	PATH    = "github.com/grokify/goauth"
)

Variables

View Source
var (
	RelCredentialsDir = ".credentials"
)

Functions

func BasicAuthHeader

func BasicAuthHeader(userid, password string) (string, error)

func BasicAuthToken

func BasicAuthToken(username, password string) (*oauth2.Token, error)

BasicAuthToken provides Basic Authentication support via an oauth2.Token.

func ClientTLSInsecureSkipVerify

func ClientTLSInsecureSkipVerify(client *http.Client) *http.Client

func HandlerFuncWrapBasicAuth added in v0.13.0

func HandlerFuncWrapBasicAuth(handler http.HandlerFunc, username, password, realm, errmsg string) http.HandlerFunc

func NewClientAuthCode

func NewClientAuthCode(conf oauth2.Config, authCode string) (*http.Client, error)

func NewClientAuthzTokenSimple

func NewClientAuthzTokenSimple(tokenType, accessToken string) *http.Client

NewClientAuthzTokenSimple returns a *http.Client given a token type and token string.

func NewClientBasicAuth

func NewClientBasicAuth(username, password string, tlsInsecureSkipVerify bool) (*http.Client, error)

NewClientBasicAuth returns a *http.Client given a basic auth username and password.

func NewClientBearerTokenSimpleOrJSON added in v0.13.0

func NewClientBearerTokenSimpleOrJSON(ctx context.Context, tokenOrJSON []byte) (*http.Client, error)

func NewClientHeaderQuery added in v0.15.2

func NewClientHeaderQuery(header http.Header, query url.Values, allowInsecure bool) *http.Client

NewClientHeaderQuery returns a new `*http.Client` that will set headers and query string parameters on very request.

func NewClientPassword

func NewClientPassword(conf oauth2.Config, ctx context.Context, username, password string) (*http.Client, error)

func NewClientPasswordConf

func NewClientPasswordConf(conf oauth2.Config, username, password string) (*http.Client, error)

func NewClientTLSToken

func NewClientTLSToken(ctx context.Context, tlsConfig *tls.Config, token *oauth2.Token) *http.Client

func NewClientToken

func NewClientToken(tokenType, tokenValue string, allowInsecure bool) *http.Client

func NewClientTokenBase64Encode

func NewClientTokenBase64Encode(tokenType, tokenValue string, allowInsecure bool) *http.Client

func NewClientTokenJSON

func NewClientTokenJSON(ctx context.Context, tokenJSON []byte) (*http.Client, error)

func NewClientTokenOAuth2

func NewClientTokenOAuth2(token *oauth2.Token) *http.Client

func NewClientWebTokenStore

func NewClientWebTokenStore(ctx context.Context, conf *oauth2.Config, tStore *TokenStoreFile, forceNewToken bool, state string) (*http.Client, error)

func NewTokenCLIFromWeb added in v0.14.2

func NewTokenCLIFromWeb(cfg *oauth2.Config, state string) (*oauth2.Token, error)

NewTokenCLIFromWeb enables a CLI app with no UI to generate a OAuth2 AuthURL which is copy and pasted into a web browser to return an an OAuth 2 authorization code and state, where the authorization code is entered on the command line.

func NewTokenOAuth2JWT added in v0.13.0

func NewTokenOAuth2JWT(tokenURL, clientID, clientSecret, jwtBase64Enc string) (*oauth2.Token, error)

func ParseJwtTokenString

func ParseJwtTokenString(tokenString string, secretKey string, claims jwt.Claims) (*jwt.Token, error)

func ParseToken

func ParseToken(rawToken []byte) (*oauth2.Token, error)

ParseToken parses a OAuth 2 token and returns an `*oauth2.Token` with custom properties.

func ParseTokenReader added in v0.11.0

func ParseTokenReader(r io.Reader) (*oauth2.Token, error)

func PathVersion

func PathVersion() string

func RFC7617UserPass

func RFC7617UserPass(userid, password string) (string, error)

RFC7617UserPass base64 encodes a user-id and password per: https://tools.ietf.org/html/rfc7617#section-2

func ReadTokenFile

func ReadTokenFile(fpath string) (*oauth2.Token, error)

ReadTokenFile retrieves a Token from a given filepath.

func TokenClientCredentials

func TokenClientCredentials(cfg clientcredentials.Config) (*oauth2.Token, error)

TokenClientCredentials is an alternative to `clientcredentials.Config.Token()` which does not work for some APIs. More investigation is needed but it appears the issue is encoding the HTTP request body. The approach here uses `&` in the URL encoded values.

func UserCredentialsDir

func UserCredentialsDir() (string, error)

func UserCredentialsDirMk

func UserCredentialsDirMk(perm os.FileMode) (string, error)

func WriteTokenFile

func WriteTokenFile(fpath string, tok *oauth2.Token) error

WriteTokenFile writes a token file to the the filepaths.

Types

type AppCredentials

type AppCredentials struct {
	Service      string   `json:"service,omitempty"`
	ClientID     string   `json:"client_id"`
	ClientSecret string   `json:"client_secret"`
	RedirectURIs []string `json:"redirect_uris"`
	AuthURI      string   `json:"auth_uri"`
	TokenURI     string   `json:"token_uri"`
	Scopes       []string `json:"scopes"`
}

// ApplicationCredentials represents information for an app.

type ApplicationCredentials struct {
	ServerURL    string
	ClientID     string
	ClientSecret string
	Endpoint     oauth2.Endpoint
}

func (*AppCredentials) Config

func (ac *AppCredentials) Config() *oauth2.Config

func (*AppCredentials) Defaultify

func (ac *AppCredentials) Defaultify()

type AppCredentialsWrapper

type AppCredentialsWrapper struct {
	Web       *AppCredentials `json:"web"`
	Installed *AppCredentials `json:"installed"`
}

func NewAppCredentialsWrapperFromBytes

func NewAppCredentialsWrapperFromBytes(data []byte) (AppCredentialsWrapper, error)

func (*AppCredentialsWrapper) Config

func (w *AppCredentialsWrapper) Config() (*oauth2.Config, error)

type AuthorizationType

type AuthorizationType int
const (
	Anonymous AuthorizationType = iota
	Basic
	Bearer
	Digest
	NTLM
	Negotiate
	OAuth
)

func (AuthorizationType) String

func (a AuthorizationType) String() string

String returns the English name of the authorizationTypes ("Basic", "Bearer", ...).

type OAuth2Util

type OAuth2Util interface {
	SetClient(*http.Client)
	GetSCIMUser() (scim.User, error)
}

type Scope

type Scope struct {
	Name        string `json:"name"`
	Description string `json:"definition"`
}

type ServiceType

type ServiceType int
const (
	Google ServiceType = iota
	Facebook
	RingCentral
	Aha
)

type TokenStoreFile

type TokenStoreFile struct {
	Token    *oauth2.Token
	Filepath string
}

func NewTokenStoreFile

func NewTokenStoreFile(file string) *TokenStoreFile

func NewTokenStoreFileDefault

func NewTokenStoreFileDefault(tokenPath string, useDefaultDir bool, perm os.FileMode) (*TokenStoreFile, error)

func (*TokenStoreFile) NewTokenCLIFromWeb added in v0.14.2

func (ts *TokenStoreFile) NewTokenCLIFromWeb(cfg *oauth2.Config, state string) (*oauth2.Token, error)

func (*TokenStoreFile) Read

func (ts *TokenStoreFile) Read() error

func (*TokenStoreFile) Write

func (ts *TokenStoreFile) Write() error

type UserCredentials

type UserCredentials struct {
	Username string
	Password string
}

UserCredentials represents a user's credentials.

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