Avnology ID
SDKsGo SDKOAuth 2.1

Client Credentials

Machine-to-machine authentication with client credentials in the Go SDK.

Client Credentials

Obtain access tokens for service-to-service communication without user interaction.

ClientCredentials()

func (o *OAuthService) ClientCredentials(ctx context.Context, params *ClientCredentialsParams) (*TokenSet, error)

Parameters

FieldTypeRequiredDescription
Scopes[]stringyesRequested scopes
AudiencestringnoTarget API audience

Basic usage

client, err := avnologyid.NewClient(
    avnologyid.WithBaseURL("https://api.id.avnology.com"),
    avnologyid.WithClientCredentials("app_backend", "sk_live_..."),
)
if err != nil {
    log.Fatal(err)
}

tokens, err := client.OAuth.ClientCredentials(ctx, &avnologyid.ClientCredentialsParams{
    Scopes: []string{"users:read", "organizations:read"},
})
if err != nil {
    log.Fatal(err)
}

fmt.Println("Access token:", tokens.AccessToken)
fmt.Println("Expires in:", tokens.ExpiresIn, "seconds")

Token caching

type tokenCache struct {
    mu     sync.Mutex
    token  *avnologyid.TokenSet
    client *avnologyid.Client
}

func (c *tokenCache) GetToken(ctx context.Context, scopes []string) (string, error) {
    c.mu.Lock()
    defer c.mu.Unlock()

    if c.token != nil && time.Now().Before(c.token.ExpiresAt) {
        return c.token.AccessToken, nil
    }

    token, err := c.client.OAuth.ClientCredentials(ctx, &avnologyid.ClientCredentialsParams{
        Scopes: scopes,
    })
    if err != nil {
        return "", err
    }

    c.token = token
    return token.AccessToken, nil
}

See also

On this page