goauth

package module
v0.23.29 Latest Latest
Warning

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

Go to latest
Published: Feb 14, 2026 License: MIT Imports: 33 Imported by: 44

README

GoAuth

Build Status Lint Status Go Report Card Docs License

GoAuth is a comprehensive Go authentication library designed to simplify OAuth 2.0, JWT, and other authentication methods for API services. It provides a unified configuration system for handling multiple authentication types and services, making it easy to create authenticated *http.Client instances from a single JSON configuration file.

Features

  • Unified Credentials Management: Single JSON configuration format for multiple authentication types and services
  • Multiple Authentication Types: OAuth 2.0, JWT, Basic Auth, GCP Service Account, and custom header/query authentication
  • 40+ OAuth 2.0 Providers: Pre-configured endpoints for popular services
  • Multiple Grant Types: Authorization Code, Client Credentials, Password, JWT Bearer, SAML2 Bearer, and Refresh Token
  • PKCE Support: Proof Key for Code Exchange for enhanced security
  • SCIM User Model: Canonical user information retrieval across services using SCIM schema
  • CLI Tools: Command-line utilities for token generation and API requests
  • Multi-Service OAuth: Support for applications using multiple OAuth providers (e.g., "Login with Google" and "Login with Facebook")

Installation

go get github.com/grokify/goauth

Requirements: Go 1.24+

Supported OAuth 2.0 Providers

GoAuth includes pre-configured OAuth 2.0 endpoints for the following services:

Service Service Key Notes
Aha aha Requires subdomain
Asana asana
Atlassian atlassian
eBay ebay Production
eBay Sandbox ebaysandbox Sandbox
Facebook facebook
GitHub github
Google google
HubSpot hubspot
Instagram instagram
Lyft lyft
Mailchimp mailchimp
Monday.com monday
PagerDuty pagerduty
PayPal paypal Production
PayPal Sandbox paypalsandbox Sandbox
Pipedrive pipedrive
Practicesuite practicesuite
RingCentral ringcentral Production
RingCentral Sandbox ringcentralsandbox Sandbox
Shippo shippo
Shopify shopify Requires subdomain
Slack slack
Stack Overflow stackoverflow
Stripe stripe
Todoist todoist
Uber uber
WePay wepay Production
WePay Sandbox wepaysandbox Sandbox
Wrike wrike
Wunderlist wunderlist
Zoom zoom

Additional service-specific packages are available for: Auth0, Metabase, Salesforce, SuccessFactors, Visa, SparkPost, and Zendesk.

Authentication Types

GoAuth supports the following authentication types:

Type Type Key Description
Basic Auth basic HTTP Basic Authentication
OAuth 2.0 oauth2 OAuth 2.0 with multiple grant types
JWT jwt JSON Web Token generation
GCP Service Account gcpsa Google Cloud Platform Service Account
Google OAuth 2.0 googleoauth2 Google-specific OAuth 2.0
Header/Query headerquery Custom header or query parameter authentication
OAuth 2.0 Grant Types
  • authorization_code - Authorization Code flow
  • client_credentials - Client Credentials flow
  • password - Resource Owner Password Credentials
  • urn:ietf:params:oauth:grant-type:jwt-bearer - JWT Bearer
  • urn:ietf:params:oauth:grant-type:saml2-bearer - SAML2 Bearer
  • refresh_token - Refresh Token
  • account_credentials - Account Credentials (Zoom Server-to-Server)

Configuration

Credentials Set (Multiple Accounts)

GoAuth uses a JSON configuration format that supports multiple credentials:

{
  "credentials": {
    "my-google-app": {
      "service": "google",
      "type": "oauth2",
      "oauth2": {
        "clientID": "your-client-id",
        "clientSecret": "your-client-secret",
        "redirectURL": "https://example.com/callback",
        "scope": ["email", "profile"],
        "grantType": "authorization_code"
      }
    },
    "my-ringcentral-app": {
      "service": "ringcentral",
      "type": "oauth2",
      "oauth2": {
        "clientID": "your-client-id",
        "clientSecret": "your-client-secret",
        "grantType": "password",
        "username": "your-username",
        "password": "your-password"
      }
    },
    "my-api-key": {
      "type": "headerquery",
      "headerquery": {
        "serverURL": "https://api.example.com",
        "header": {
          "X-API-Key": "your-api-key"
        }
      }
    }
  }
}
Credential Types
OAuth 2.0 Credentials
{
  "service": "github",
  "type": "oauth2",
  "oauth2": {
    "serverURL": "https://api.github.com",
    "clientID": "your-client-id",
    "clientSecret": "your-client-secret",
    "redirectURL": "https://example.com/callback",
    "scope": ["repo", "user"],
    "grantType": "authorization_code",
    "pkce": false
  }
}
Basic Auth Credentials
{
  "type": "basic",
  "basic": {
    "username": "your-username",
    "password": "your-password",
    "serverURL": "https://api.example.com",
    "allowInsecure": false
  }
}
JWT Credentials
{
  "type": "jwt",
  "jwt": {
    "issuer": "your-issuer",
    "privateKey": "your-private-key",
    "signingMethod": "HS256"
  }
}

Supported signing methods: ES256, ES384, ES512, HS256, HS384, HS512

Header/Query Credentials
{
  "type": "headerquery",
  "headerquery": {
    "serverURL": "https://api.example.com",
    "header": {
      "Authorization": "Bearer your-token",
      "X-Custom-Header": "value"
    },
    "query": {
      "api_key": "your-api-key"
    }
  }
}

Usage

Creating an HTTP Client
package main

import (
    "context"
    "github.com/grokify/goauth"
)

func main() {
    ctx := context.Background()

    // From credentials file with account key
    client, err := goauth.NewClient(ctx, "credentials.json", "my-google-app")
    if err != nil {
        panic(err)
    }

    // Use client for API requests
    resp, err := client.Get("https://api.example.com/resource")
}
Loading Credentials Set
package main

import (
    "context"
    "github.com/grokify/goauth"
)

func main() {
    ctx := context.Background()

    // Load credentials set from file
    set, err := goauth.ReadFileCredentialsSet("credentials.json", true)
    if err != nil {
        panic(err)
    }

    // Get specific credentials
    creds, err := set.Get("my-google-app")
    if err != nil {
        panic(err)
    }

    // Create client from credentials
    client, err := creds.NewClient(ctx)
    if err != nil {
        panic(err)
    }

    // List all account keys
    accounts := set.Accounts()
}
CLI-based Token Retrieval

For authorization code flow without a web server:

package main

import (
    "context"
    "github.com/grokify/goauth"
)

func main() {
    ctx := context.Background()

    creds, _ := goauth.NewCredentialsFromSetFile("credentials.json", "my-app", false)

    // This will print the authorization URL and prompt for the code
    client, err := creds.NewClientCLI(ctx, "random-state")
    if err != nil {
        panic(err)
    }
}
Canonical User Information (SCIM)

GoAuth provides ClientUtil implementations that satisfy the OAuth2Util interface for retrieving canonical user information:

type OAuth2Util interface {
    SetClient(*http.Client)
    GetSCIMUser() (scim.User, error)
}
Google
import "github.com/grokify/goauth/google"

googleClientUtil := google.NewClientUtil(googleOAuth2HTTPClient)
scimUser, err := googleClientUtil.GetSCIMUser()
Facebook
import "github.com/grokify/goauth/facebook"

fbClientUtil := facebook.NewClientUtil(fbOAuth2HTTPClient)
scimUser, err := fbClientUtil.GetSCIMUser()
RingCentral
import "github.com/grokify/goauth/ringcentral"

rcClientUtil := ringcentral.NewClientUtil(rcOAuth2HTTPClient)
scimUser, err := rcClientUtil.GetSCIMUser()

Also available for: Aha, Zoom, Metabase, Zendesk, and Salesforce.

CLI Tools

GoAuth includes command-line tools for authentication tasks:

goauth

Main token retrieval tool supporting all authentication types:

go run cmd/goauth/main.go --credentials credentials.json --account my-app
goapi

Make authenticated API requests:

go run cmd/goapi/main.go --credentials credentials.json --account my-app --url https://api.example.com/resource

Package Structure

Package Description
goauth Core credentials management and client creation
authutil Low-level authentication utilities (BasicAuth, OAuth2, JWT, scope management)
endpoints Pre-configured OAuth 2.0 endpoints for 30+ services
scim SCIM schema user/group models for canonical user representation
multiservice Multi-provider OAuth2 management for applications
google Google-specific OAuth2 and GCP service account handling
ringcentral RingCentral API integration
facebook Facebook OAuth2 and user data retrieval
aha, zoom, metabase, zendesk, salesforce, hubspot Service-specific implementations

Test Redirect URL

This repo includes a generic test OAuth 2 redirect page for headless (no-UI) applications. Configure your OAuth 2 redirect URI to:

https://grokify.github.io/goauth/oauth2callback/

This page displays the Authorization Code which you can copy and paste into your CLI application.

Example Applications

  • Multi-Service OAuth Demo: github.com/grokify/beegoutil - Beego-based demo showing Google and Facebook authentication
  • Examples Directory: See examples/ and service-specific cmd/ directories for usage examples

Contributing

Contributions are welcome. Please submit pull requests or create issues for bugs and feature requests.

License

GoAuth is available under the MIT License.

Documentation

Index

Constants

View Source
const (
	TypeBasic        = "basic"
	TypeHeaderQuery  = "headerquery"
	TypeOAuth2       = "oauth2"
	TypeJWT          = "jwt"
	TypeGCPSA        = "gcpsa" // Google Cloud Platform Service Account
	TypeGoogleOAuth2 = "googleoauth2"
)
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")
)
View Source
var ErrsInclLocation = false

Functions

func NewClient added in v0.21.9

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

func NewClientCmd added in v0.23.15

func NewClientCmd(ctx context.Context, state 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 CLIRequest added in v0.23.6

type CLIRequest struct {
	Options
	Request httpsimple.CLI
}

CLIRequest will get a token using `goauth` and then execute the provided request parameters with the credential, e.g. OAuth 2.0 access token.

func (CLIRequest) Do added in v0.23.6

func (cli CLIRequest) Do(ctx context.Context, state string, w io.Writer) error

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"`
	GoogleOAuth2 *CredentialsGoogleOAuth2 `json:"googleoauth2,omitempty"`
	JWT          *CredentialsJWT          `json:"jwt,omitempty"`
	OAuth2       *CredentialsOAuth2       `json:"oauth2,omitempty"`
	Token        *oauth2.Token            `json:"token,omitempty"`
	Additional   url.Values               `json:"additional,omitempty"`
}

func NewCredentialsFromCLI added in v0.23.22

func NewCredentialsFromCLI(inclAccountsOnError bool) (Credentials, error)

func NewCredentialsFromJSON added in v0.23.22

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

func NewCredentialsFromSetFile added in v0.23.22

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

func (*Credentials) ExistingValidToken added in v0.23.0

func (creds *Credentials) ExistingValidToken() (*oauth2.Token, 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) NewOrExistingValidToken added in v0.23.0

func (creds *Credentials) NewOrExistingValidToken(ctx context.Context) (*oauth2.Token, 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"`
}

CredentialsGCP 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 CredentialsGoogleOAuth2 added in v0.23.0

type CredentialsGoogleOAuth2 struct {
	GoogleWebCredentials google.Credentials `json:"web,omitempty"` // "web"
	Scopes               []string           `json:"scopes,omitempty"`
	Token                *oauth2.Token      `json:"token,omitempty"`
}

func (CredentialsGoogleOAuth2) CredentialsOAuth2 added in v0.23.0

func (cgo CredentialsGoogleOAuth2) CredentialsOAuth2() CredentialsOAuth2

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(filename 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"`
	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, state string) (*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
get_token command
goauth command
jwt command
examples
jwt command
cmd/get_account command
examples/send_ics command
This package posts an ICS file to Gmail.
This package posts an ICS file to Gmail.
util
examples/get_me command

Jump to

Keyboard shortcuts

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