oauth

package
v0.1.4 Latest Latest
Warning

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

Go to latest
Published: Jan 9, 2026 License: MIT Imports: 13 Imported by: 0

Documentation

Overview

Package oauth provides OAuth 2.0 authentication with PKCE (Proof Key for Code Exchange).

This package implements the OAuth 2.0 Authorization Code Flow with PKCE for secure authentication without client secrets. It includes:

  • Code verifier generation (cryptographically random, 43-128 characters)
  • Code challenge generation (SHA-256 hash, base64url encoded)
  • Authorization URL construction
  • Local callback server for authorization code receipt
  • Token exchange (authorization code for access/refresh tokens)
  • Token storage in OS keychain

OAuth 2.0 PKCE Flow:

  1. Generate random code verifier (43-128 chars)
  2. Create code challenge: BASE64URL(SHA256(code_verifier))
  3. Redirect user to authorization URL with challenge
  4. User authorizes on provider's site
  5. Provider redirects to callback URL with authorization code
  6. Exchange code + verifier for access/refresh tokens
  7. Store tokens securely in OS keychain

Example usage:

import "github.com/AINative-studio/ainative-code/internal/auth/oauth"

// Create OAuth client
client := oauth.NewClient(oauth.Config{
    AuthURL:      "https://auth.example.com/authorize",
    TokenURL:     "https://auth.example.com/token",
    ClientID:     "your-client-id",
    RedirectURL:  "http://localhost:8080/callback",
    Scopes:       []string{"read", "write"},
})

// Start authentication flow
tokens, err := client.Authenticate(ctx)
if err != nil {
    log.Fatal(err)
}

// Tokens are automatically stored in OS keychain
fmt.Printf("Access token: %s\n", tokens.AccessToken)

Index

Constants

View Source
const (
	// DefaultCallbackPort is the default port for the OAuth callback server
	DefaultCallbackPort = 8080

	// DefaultTimeout is the default timeout for HTTP requests
	DefaultTimeout = 30 * time.Second

	// DefaultCallbackPath is the default path for the OAuth callback
	DefaultCallbackPath = "/callback"
)
View Source
const (
	// PKCECodeVerifierLength is the length of the code verifier (43-128 characters per RFC 7636)
	PKCECodeVerifierLength = 64

	// PKCECodeVerifierMinLength is the minimum length for a code verifier
	PKCECodeVerifierMinLength = 43

	// PKCECodeVerifierMaxLength is the maximum length for a code verifier
	PKCECodeVerifierMaxLength = 128

	// PKCEChallengeMethod is the method used to generate the code challenge
	PKCEChallengeMethod = "S256" // SHA-256
)

Variables

This section is empty.

Functions

func ValidateCodeVerifier

func ValidateCodeVerifier(verifier string) error

ValidateCodeVerifier validates that a code verifier meets PKCE requirements.

func VerifyCodeChallenge

func VerifyCodeChallenge(verifier, challenge string) bool

VerifyCodeChallenge verifies that a challenge matches a verifier.

Types

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client is an OAuth 2.0 client with PKCE support.

func NewClient

func NewClient(config Config) *Client

NewClient creates a new OAuth client with PKCE support.

func (*Client) Authenticate

func (c *Client) Authenticate(ctx context.Context) (*jwt.TokenPair, error)

Authenticate performs the OAuth 2.0 authorization code flow with PKCE.

This method:

  1. Generates PKCE code verifier and challenge
  2. Builds authorization URL and opens it in browser
  3. Starts local callback server to receive authorization code
  4. Exchanges authorization code for tokens
  5. Returns the token pair

The user must authorize the application in their browser.

func (*Client) ExchangeCode

func (c *Client) ExchangeCode(ctx context.Context, code, codeVerifier string) (*jwt.TokenPair, error)

ExchangeCode exchanges an authorization code for tokens (for manual flow).

func (*Client) GetAuthorizationURL

func (c *Client) GetAuthorizationURL() (string, *PKCECodePair, string, error)

GetAuthorizationURL returns the authorization URL for manual flow.

func (*Client) RefreshToken

func (c *Client) RefreshToken(ctx context.Context, refreshToken string) (*jwt.TokenPair, error)

RefreshToken refreshes an access token using a refresh token.

type Config

type Config struct {
	// AuthURL is the authorization endpoint URL
	AuthURL string

	// TokenURL is the token endpoint URL
	TokenURL string

	// ClientID is the OAuth client identifier
	ClientID string

	// RedirectURL is the callback URL (e.g., http://localhost:8080/callback)
	RedirectURL string

	// Scopes are the requested OAuth scopes
	Scopes []string

	// CallbackPort is the port for the local callback server (default: 8080)
	CallbackPort int

	// HTTPClient is the HTTP client for token requests (optional)
	HTTPClient *http.Client
}

Config represents the OAuth client configuration.

type PKCECodePair

type PKCECodePair struct {
	Verifier        string
	Challenge       string
	ChallengeMethod string
}

PKCECodePair represents a code verifier and its corresponding challenge.

func GeneratePKCECodePair

func GeneratePKCECodePair() (*PKCECodePair, error)

GeneratePKCECodePair generates a code verifier and challenge for PKCE.

The code verifier is a cryptographically random string of 43-128 characters using the characters [A-Z], [a-z], [0-9], "-", ".", "_", and "~".

The code challenge is the Base64URL-encoded SHA-256 hash of the verifier.

See RFC 7636 for PKCE specification.

func GeneratePKCECodePairWithLength

func GeneratePKCECodePairWithLength(length int) (*PKCECodePair, error)

GeneratePKCECodePairWithLength generates a PKCE code pair with custom verifier length.

type TokenResponse

type TokenResponse struct {
	AccessToken  string `json:"access_token"`
	RefreshToken string `json:"refresh_token"`
	TokenType    string `json:"token_type"`
	ExpiresIn    int64  `json:"expires_in"`
	Scope        string `json:"scope,omitempty"`
}

TokenResponse represents the OAuth token endpoint response.

Jump to

Keyboard shortcuts

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