OAuth2 client implementation for Go providing support for various OAuth 2.0 flows including authorization code flow, client credentials, device authorization, JWT flows, and specialized Google authentication. The package implements RFC 6749 with Bearer JWT support and includes built-in endpoint configurations for 30+ popular OAuth providers.
go get golang.org/x/oauth2import (
"golang.org/x/oauth2"
"golang.org/x/oauth2/clientcredentials"
"golang.org/x/oauth2/google"
"golang.org/x/oauth2/jwt"
)import (
"context"
"fmt"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
)
func main() {
ctx := context.Background()
// Configure OAuth2
conf := &oauth2.Config{
ClientID: "your-client-id",
ClientSecret: "your-client-secret",
Scopes: []string{"profile", "email"},
Endpoint: google.Endpoint,
RedirectURL: "http://localhost:8080/callback",
}
// Generate authorization URL with PKCE
verifier := oauth2.GenerateVerifier()
url := conf.AuthCodeURL("state", oauth2.S256ChallengeOption(verifier))
fmt.Println("Visit the URL:", url)
// Exchange authorization code for token
// (code obtained from callback)
token, err := conf.Exchange(ctx, code, oauth2.VerifierOption(verifier))
if err != nil {
panic(err)
}
// Create authenticated HTTP client
client := conf.Client(ctx, token)
// Use client for API requests
resp, err := client.Get("https://www.googleapis.com/oauth2/v2/userinfo")
// ...
}Standard 3-legged OAuth2 flow with PKCE support for web and mobile applications.
type Config struct {
ClientID string
ClientSecret string
Endpoint Endpoint
RedirectURL string
Scopes []string
}
func (c *Config) AuthCodeURL(state string, opts ...AuthCodeOption) string
func (c *Config) Exchange(ctx context.Context, code string, opts ...AuthCodeOption) (*Token, error)
func (c *Config) Client(ctx context.Context, t *Token) *http.Client
func GenerateVerifier() string
func S256ChallengeOption(verifier string) AuthCodeOption
func VerifierOption(verifier string) AuthCodeOption2-legged OAuth2 flow for server-to-server authentication without user involvement.
import "golang.org/x/oauth2/clientcredentials"
type Config struct {
ClientID string
ClientSecret string
TokenURL string
Scopes []string
AuthStyle oauth2.AuthStyle
}
func (c *Config) Client(ctx context.Context) *http.Client
func (c *Config) Token(ctx context.Context) (*oauth2.Token, error)OAuth2 flow for devices with limited input capabilities (TVs, game consoles, IoT devices).
type DeviceAuthResponse struct {
DeviceCode string `json:"device_code"`
UserCode string `json:"user_code"`
VerificationURI string `json:"verification_uri"`
VerificationURIComplete string `json:"verification_uri_complete,omitempty"`
Expiry time.Time `json:"expires_in,omitempty"`
Interval int64 `json:"interval,omitempty"`
}
func (c *Config) DeviceAuth(ctx context.Context, opts ...AuthCodeOption) (*DeviceAuthResponse, error)
func (c *Config) DeviceAccessToken(ctx context.Context, da *DeviceAuthResponse, opts ...AuthCodeOption) (*Token, error)JSON Web Token and JSON Web Signature support for 2-legged OAuth2 flows.
import "golang.org/x/oauth2/jwt"
type Config struct {
Email string
PrivateKey []byte
PrivateKeyID string
Subject string
Scopes []string
TokenURL string
Expires time.Duration
Audience string
}
func (c *Config) Client(ctx context.Context) *http.Client
func (c *Config) TokenSource(ctx context.Context) oauth2.TokenSourceComprehensive Google Cloud Platform authentication including Application Default Credentials, service accounts, and workload identity federation.
import "golang.org/x/oauth2/google"
func DefaultClient(ctx context.Context, scope ...string) (*http.Client, error)
func DefaultTokenSource(ctx context.Context, scope ...string) (oauth2.TokenSource, error)
func FindDefaultCredentials(ctx context.Context, scopes ...string) (*Credentials, error)
func JWTConfigFromJSON(jsonKey []byte, scope ...string) (*jwt.Config, error)
func ComputeTokenSource(account string, scope ...string) oauth2.TokenSource
type Credentials struct {
ProjectID string
TokenSource oauth2.TokenSource
JSON []byte
UniverseDomainProvider func() (string, error)
}Create downscoped tokens with restricted permissions for Google Cloud Storage.
import "golang.org/x/oauth2/google/downscope"
type DownscopingConfig struct {
RootSource oauth2.TokenSource
Rules []AccessBoundaryRule
UniverseDomain string
}
type AccessBoundaryRule struct {
AvailableResource string `json:"availableResource"`
AvailablePermissions []string `json:"availablePermissions"`
Condition *AvailabilityCondition `json:"availabilityCondition,omitempty"`
}
func NewTokenSource(ctx context.Context, conf DownscopingConfig) (oauth2.TokenSource, error)Workload and workforce identity federation for accessing Google Cloud from external identity providers.
import "golang.org/x/oauth2/google/externalaccount"
type Config struct {
Audience string
SubjectTokenType string
TokenURL string
ServiceAccountImpersonationURL string
ClientID string
ClientSecret string
CredentialSource *CredentialSource
Scopes []string
SubjectTokenSupplier SubjectTokenSupplier
AwsSecurityCredentialsSupplier AwsSecurityCredentialsSupplier
}
func NewTokenSource(ctx context.Context, conf Config) (oauth2.TokenSource, error)Token types, validation, and automatic refresh capabilities.
type Token struct {
AccessToken string `json:"access_token"`
TokenType string `json:"token_type,omitempty"`
RefreshToken string `json:"refresh_token,omitempty"`
Expiry time.Time `json:"expiry,omitempty"`
ExpiresIn int64 `json:"expires_in,omitempty"`
}
func (t *Token) Valid() bool
func (t *Token) Type() string
func (t *Token) Extra(key string) any
func (t *Token) SetAuthHeader(r *http.Request)
type TokenSource interface {
Token() (*Token, error)
}
func StaticTokenSource(t *Token) TokenSource
func ReuseTokenSource(t *Token, src TokenSource) TokenSource
func ReuseTokenSourceWithExpiry(t *Token, src TokenSource, earlyExpiry time.Duration) TokenSourceLow-level HTTP transport with automatic OAuth2 token injection.
type Transport struct {
Source TokenSource
Base http.RoundTripper
}
func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error)
func NewClient(ctx context.Context, src TokenSource) *http.ClientCustom authorization handlers for 3-legged OAuth with PKCE support.
import "golang.org/x/oauth2/authhandler"
type AuthorizationHandler func(authCodeURL string) (code string, state string, err error)
type PKCEParams struct {
Challenge string
ChallengeMethod string
Verifier string
}
func TokenSource(ctx context.Context, config *oauth2.Config, state string, authHandler AuthorizationHandler) oauth2.TokenSource
func TokenSourceWithPKCE(ctx context.Context, config *oauth2.Config, state string, authHandler AuthorizationHandler, pkce *PKCEParams) oauth2.TokenSourcePre-configured OAuth2 endpoints for 30+ popular services including Google, GitHub, Microsoft, Facebook, and more.
import "golang.org/x/oauth2/endpoints"
var Google = oauth2.Endpoint{
AuthURL: "https://accounts.google.com/o/oauth2/auth",
TokenURL: "https://oauth2.googleapis.com/token",
DeviceAuthURL: "https://oauth2.googleapis.com/device/code",
}
var GitHub = oauth2.Endpoint{
AuthURL: "https://github.com/login/oauth/authorize",
TokenURL: "https://github.com/login/oauth/access_token",
DeviceAuthURL: "https://github.com/login/device/code",
}
func AzureAD(tenant string) oauth2.Endpoint
func AWSCognito(domain string) oauth2.EndpointSpecialized OAuth2 support for JIRA and Confluence with JWT claim sets.
import "golang.org/x/oauth2/jira"
type Config struct {
BaseURL string
Subject string
oauth2.Config
}
type ClaimSet struct {
Issuer string `json:"iss"`
Subject string `json:"sub"`
InstalledURL string `json:"tnt"`
AuthURL string `json:"aud"`
ExpiresIn int64 `json:"exp"`
IssuedAt int64 `json:"iat"`
}
func (c *Config) Client(ctx context.Context) *http.Client
func (c *Config) TokenSource(ctx context.Context) oauth2.TokenSourcetype Endpoint struct {
AuthURL string
DeviceAuthURL string
TokenURL string
AuthStyle AuthStyle
}
type AuthStyle int
const (
AuthStyleAutoDetect AuthStyle = 0
AuthStyleInParams AuthStyle = 1
AuthStyleInHeader AuthStyle = 2
)
type RetrieveError struct {
Response *http.Response
Body []byte
ErrorCode string
ErrorDescription string
ErrorURI string
}
func (r *RetrieveError) Error() stringtype AuthCodeOption interface {
// Has unexported methods
}
var AccessTypeOnline AuthCodeOption
var AccessTypeOffline AuthCodeOption
var ApprovalForce AuthCodeOption
func SetAuthURLParam(key, value string) AuthCodeOptionvar HTTPClient internal.ContextKey
var NoContext = context.TODO() // Deprecated: Use context.Background or context.TODOfunc RegisterBrokenAuthHeaderProvider(tokenURL string) // Deprecated: no-op
func S256ChallengeFromVerifier(verifier string) string