Client Credentials Flow

The canonical second-party flow — exchange the keys a business issued you for an access token, server-to-server, no user click.

Client Credentials Flow

The client_credentials grant is the second-party flow. A business generated a client_id + client_secret for you in their Securely portal and handed you the credentials. Those keys are scoped to that one business. Your backend exchanges them for an access token and calls the resource API on the business's behalf — no user click, no consent screen, no PKCE.

If you're third-party (you registered one set of keys to serve many businesses), this grant is not allowed. Use PKCE + consent instead.

Who uses it

Party typeClient typeAllowed?
SECOND_PARTYCONFIDENTIAL✓ — canonical flow
THIRD_PARTYany✗ — must go through consent
anyPUBLIC✗ — no client_secret to authenticate with

Public clients can't authenticate with a secret, by definition. And third-party can never use client_credentials because there's no user-to-business consent step embedded in the grant — third-party must always go through Business Consent.

When to use it

  • Always, if you're a second-party integration. Whether you're processing transactions, creating payment links, or running a scheduled report, client_credentials is your path.
  • The business has issued you a key. You don't need a user click. You just authenticate and start calling the API.

The request

curl -X POST https://auth.securely.io/oauth/token \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "grant_type=client_credentials" \
  -d "client_id=YOUR_CLIENT_ID" \
  -d "client_secret=YOUR_CLIENT_SECRET"
const params = new URLSearchParams({
  grant_type: 'client_credentials',
  client_id: process.env.SECURELY_CLIENT_ID,
  client_secret: process.env.SECURELY_CLIENT_SECRET,
});

const res = await fetch('https://auth.securely.io/oauth/token', {
  method: 'POST',
  headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
  body: params,
});

if (!res.ok) {
  throw new Error(`token request failed: ${res.status}`);
}
const tokens = await res.json();
using System.Net.Http.Json;

using var http = new HttpClient();
var body = new FormUrlEncodedContent(new Dictionary<string, string> {
    ["grant_type"]    = "client_credentials",
    ["client_id"]     = Environment.GetEnvironmentVariable("SECURELY_CLIENT_ID")!,
    ["client_secret"] = Environment.GetEnvironmentVariable("SECURELY_CLIENT_SECRET")!,
});

var res = await http.PostAsync("https://auth.securely.io/oauth/token", body);
res.EnsureSuccessStatusCode();
var tokens = await res.Content.ReadFromJsonAsync<TokenResponse>();

public record TokenResponse(
    string AccessToken,
    string TokenType,
    int ExpiresIn,
    string? RefreshToken
);
package main

import (
    "encoding/json"
    "net/http"
    "net/url"
    "os"
    "strings"
)

type tokenResponse struct {
    AccessToken string `json:"access_token"`
    TokenType   string `json:"token_type"`
    ExpiresIn   int    `json:"expires_in"`
}

func fetchToken() (*tokenResponse, error) {
    form := url.Values{
        "grant_type":    {"client_credentials"},
        "client_id":     {os.Getenv("SECURELY_CLIENT_ID")},
        "client_secret": {os.Getenv("SECURELY_CLIENT_SECRET")},
    }

    res, err := http.Post(
        "https://auth.securely.io/oauth/token",
        "application/x-www-form-urlencoded",
        strings.NewReader(form.Encode()),
    )
    if err != nil { return nil, err }
    defer res.Body.Close()

    var t tokenResponse
    if err := json.NewDecoder(res.Body).Decode(&t); err != nil {
        return nil, err
    }
    return &t, nil
}

The response

{
  "access_token": "eyJhbGciOiJSUzI1NiIs...",
  "token_type": "Bearer",
  "expires_in": 3600
}
📘

No refresh token

client_credentials responses do not include a refresh_token. When the access token expires, just call /oauth/token again with your credentials. There's no flow to "refresh" because there was never a user-bound session to keep alive.

Claims in a client_credentials token

A token from this grant carries:

ClaimValue
subYour client ID
client_idSame as sub
party_type2 (SECOND_PARTY)
merchant_idSet — pinned to the merchant the keys were issued for
business_idSet — pinned to the business the keys were issued for

The merchant_id and business_id are baked into your keys at the time the business generated them. They're not chosen at request time — you literally cannot use these keys to access a different business.

Caching the access token

Don't request a new token for every API call. Cache it in memory (or a fast shared store like Redis if you scale horizontally) until it's near expiration:

let cached = null;

async function getAccessToken() {
  if (cached && cached.expiresAt > Date.now() + 30_000) {
    return cached.accessToken;
  }

  const tokens = await fetchToken();
  cached = {
    accessToken: tokens.access_token,
    expiresAt: Date.now() + tokens.expires_in * 1000,
  };
  return cached.accessToken;
}

The 30-second buffer avoids racing against expiration mid-flight.

Managing keys across many businesses

If you're a second-party developer building the same integration for multiple businesses, each business will generate their own client_id + client_secret. You'll end up managing one credential pair per business. Two patterns work:

  1. Per-business client in a key vault. Store each business's credentials by business identifier in your secret store; load on demand.
  2. Per-business process / tenant. Run one tenanted instance of your integration per business with its credentials supplied as environment variables.

If you find yourself wanting to manage one set of keys for many businesses, you're describing the third-party pattern. Stop and re-read Second-Party vs Third-Party — you may have registered the wrong kind of client.

Securing your client_secret

The whole premise of client_credentials is that you can keep a secret. Treat it accordingly:

  • Vault it. Use Azure Key Vault, AWS Secrets Manager, Doppler, or your secret store of choice. Don't commit it.
  • Rotate it on the schedule your security policy dictates (Securely supports rotation via /clients/{id}/rotate-secret).
  • Never log it. Scrub it from request logs. Most HTTP libraries can be configured to redact specific form fields.
  • One leak ≠ all blasts. Because each business generates its own keys, a leaked key only compromises that one business. Keep that boundary clean.
🚧

If your secret leaks

Rotate it immediately. Any token issued before rotation continues to work until it expires (max 1 hour), so monitor traffic during that window for anomalies.

Making API calls

Once you have an access token, every resource API call looks the same:

curl https://api.securely.io/v2/merchants/123/payment-links \
  -H "Authorization: Bearer eyJhbGciOiJSUzI1NiIs..."

Next



Did this page help you?