jackc/pgx · error

failed to obtain OAuth token

Error message

failed to obtain OAuth token: %w

What it means

The configured OAuthTokenProvider callback returned an error when pgx requested a bearer token during SASL/OAuth authentication. The provider's error is wrapped; pgx itself only propagates it.

Solutions

  1. Unwrap and inspect the token provider's error (expired credentials, unreachable issuer, etc.)
  2. Verify the OAuthTokenProvider implementation handles context cancellation properly
  3. Retry the connection once the token source is healthy
Defensive patterns

Strategy: retry

When it happens

Trigger: Thrown at pgconn/auth_oauth.go:19 when the library encounters an invalid state.

Common situations: See trigger scenarios.


AI-assisted analysis of jackc/pgx@ec1a0befd2 (2026-08-04). Data as JSON: /api/errors/8005dd364e4b9917. Report an issue: GitHub.

Appendix: source

Thrown at pgconn/auth_oauth.go:19

package pgconn

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"

	"github.com/jackc/pgx/v5/pgproto3"
)

func (c *PgConn) oauthAuth(ctx context.Context) error {
	if c.config.OAuthTokenProvider == nil {
		return errors.New("OAuth authentication required but no token provider configured")
	}

	token, err := c.config.OAuthTokenProvider(ctx)
	if err != nil {
		return fmt.Errorf("failed to obtain OAuth token: %w", err)
	}

	// https://www.rfc-editor.org/rfc/rfc7628.html#section-3.1
	initialResponse := []byte("n,,\x01auth=Bearer " + token + "\x01\x01")

	saslInitialResponse := &pgproto3.SASLInitialResponse{
		AuthMechanism: "OAUTHBEARER",
		Data:          initialResponse,
	}
	c.frontend.Send(saslInitialResponse)
	err = c.flushWithPotentialWriteReadDeadlock()
	if err != nil {
		return err
	}

	msg, err := c.receiveMessage()
	if err != nil {
		return err

View on GitHub (pinned to ec1a0befd2)