> ## Documentation Index
> Fetch the complete documentation index at: /docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Verify account ownership with OAuth delegation

> Send a user through PostSyncer to sign in to a social network, and get back a signed proof of which account they own.

OAuth delegation proves that a user of your app owns a social account. You send them to PostSyncer, they sign in on the network's own page, and they come back to your app with the network's ID for that account, its handle and a signature you check with your secret.

It's for apps that need to know who owns an account, such as a creator marketplace checking a creator's TikTok. It doesn't connect the account to a PostSyncer workspace, and nothing in the proof lets you post as it. To post for your users, use [connect links](/docs/guides/connect-accounts.md) and the API.

> [!NOTE]
>
> PostSyncer keeps nothing from the sign-in: not the account, its tokens or the person's details. The proof carries the account's ID and handle, read from the network at sign-in.

## Before you start

1. **An API key with `accounts:create`**, the same permission as connect links. Keys made with "All permissions" have it. Make one in [Settings → API](https://app.postsyncer.com/settings/api). The key's person must be active in PostSyncer.
2. **A signing secret on that key.** In **Settings → API**, open the key's menu (⋯) and choose **Generate signing secret**. Copy it: it's shown once.

Keep the key and the secret on your server. The key never goes to the browser: you start each session from your backend. Anyone with the secret could make proofs that pass your check.

To replace a leaked secret, choose **Regenerate signing secret**. Sessions started after that sign with the new secret. A session already started keeps the old one until it ends, up to 35 minutes later.

## Networks

`platform` is one of these:

| `platform` | Network | The proof names |
| - | - | - |
| `twitter` | X | The X account that signed in |
| `instagram` | Instagram | The Instagram account that signed in |
| `facebook` | Facebook | The person's Facebook login, not a Page they manage. `handle` is usually empty. |
| `linkedin` | LinkedIn | The person's LinkedIn profile, not a Page. `handle` is their profile's short name, or empty. |
| `tiktok` | TikTok | The TikTok account that signed in |
| `youtube` | YouTube | The channel. `handle` is its @handle, or empty when the channel has none. |
| `pinterest` | Pinterest | The Pinterest account that signed in |
| `threads` | Threads | The Threads account that signed in |
| `google_business` | Google Business Profile | The Google login that signed in, not a business listing. `platform_id` is its Google account ID and `handle` is its name. |

Bluesky and Telegram don't sign in with OAuth, and Mastodon signs in on each server, so none of the three can be used: a session for them is refused with `unsupported_platform`.

## How it works

```mermaid theme={null}
sequenceDiagram
  participant S as Your server
  participant P as PostSyncer
  participant B as User's browser
  participant N as Network
  S->>P: 1. POST /api/oauth/delegate/sessions (your key)
  P-->>S: authorize_url (one use, 15 minutes)
  S->>B: 2. Send the user to authorize_url
  B->>N: Sign in and allow
  N-->>P: Signed-in account
  P-->>B: 3. Back to your callback_url with the signed proof
  B->>S: Your callback
  S->>S: 4. Check state, expires and sig
```

## 1. Start a session

From your server:

```text theme={null}
POST https://postsyncer.com/api/oauth/delegate/sessions
```

**Authorization** `string` *required*

`Bearer YOUR_API_KEY`. The key needs `accounts:create` and a signing secret.

**platform** `string` *required*

The network, from the table above, such as `tiktok`. Up to 64 characters.

**callback\_url** `string` *required*

The absolute URL in your app the user comes back to. Up to 2,048 characters. It may have its own query string: PostSyncer adds its values after it.

**state** `string` *required*

A random value you make for this session, up to 512 characters. Keep it on your server, tied to the user who started. It comes back unchanged.

```bash cURL theme={null}
curl -X POST "https://postsyncer.com/api/oauth/delegate/sessions" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "platform": "tiktok",
    "callback_url": "https://app.example.com/postsyncer/callback",
    "state": "9f2b6c1e4a7d4c0b8e3f5a2d6b9c1e7f"
  }'
```

```javascript Node.js theme={null}
import crypto from "crypto";

const state = crypto.randomBytes(16).toString("hex");
// Save `state` with the user's session, so you can check it on the way back.

const res = await fetch("https://postsyncer.com/api/oauth/delegate/sessions", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.POSTSYNCER_API_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    platform: "tiktok",
    callback_url: "https://app.example.com/postsyncer/callback",
    state,
  }),
});

const { authorize_url } = await res.json();
```

It answers `200`:

```json theme={null}
{
  "authorize_url": "https://app.postsyncer.com/oauth/delegate?request=psd_Xk2q...",
  "expires_in": 900
}
```

`authorize_url` works once, within `expires_in` seconds (15 minutes). It carries only a request token: no key, network or callback.

### When starting fails

The key is checked first, then the body. Every error except the validation one has the same shape:

```json 403 theme={null}
{
  "success": false,
  "code": "missing_permission",
  "message": "This API key does not have the \"accounts:create\" permission. Edit the key in PostSyncer under Settings → API to grant it."
}
```

| Status | `code` | `message` | Why |
| - | - | - | - |
| `401` | `missing_api_key` | `Provide your PostSyncer API key in the Authorization header.` | No `Authorization: Bearer` header. |
| `401` | `invalid_api_key` | `The provided API key is invalid or expired.` | The key is wrong, deleted or past its expiry date. |
| `403` | `account_inactive` | `Your account is inactive.` | The key's person can't use PostSyncer right now. |
| `403` | `missing_permission` | As above. | The key lacks `accounts:create`. |
| `422` | `unsupported_platform` | `The platform "bluesky" is not supported for delegation.` | That network can't be used. |
| `422` | `no_signing_secret` | `This API key has no signing secret yet. In PostSyncer, open Settings → API, click the “Generate signing key” (shield) button on this key’s row, then copy the secret and use it for OAuth delegation.` | Make a signing secret for the key first. |

A missing or invalid `platform`, `callback_url` or `state` answers the usual validation `422` instead, with `message` and `errors` and no `code`. See [Error handling](/docs/essentials/error-handling.md#oauth-delegation).

## 2. Send the user to `authorize_url`

Redirect the user's browser to `authorize_url`. PostSyncer sends them on to the network's sign-in page.

* The network asks the user to allow the same access as when an account is connected to PostSyncer, which can include posting. PostSyncer reads the account's ID and handle and keeps nothing.
* The sign-in must be finished within 20 minutes of opening the link.
* On X, the user must finish in the same browser they started in.
* The user doesn't need a PostSyncer account.

## 3. The user comes back

### With a proof

When the sign-in works, the user lands on your `callback_url` with six values added to its query:

**platform** `string`

The network you asked for.

**platform\_id** `string`

The network's own ID for the account. It doesn't change, so it's the value to store and match on.

**handle** `string`

The account's username at sign-in, without a leading `@`. For showing only: people change handles. It can be empty, as the network table says.

**state** `string`

Your `state`, unchanged.

**expires** `integer`

A Unix time 5 minutes after the sign-in. Refuse the proof after it.

**sig** `string`

The HMAC-SHA256 of `platform={platform}&platform_id={platform_id}&handle={handle}&state={state}&expires={expires}` with your signing secret, in lowercase hex.

```text Example callback theme={null}
https://app.example.com/postsyncer/callback
  ?platform=tiktok
  &platform_id=_000HaldenCoffee
  &handle=haldencoffee
  &state=9f2b6c1e4a7d4c0b8e3f5a2d6b9c1e7f
  &expires=1899795600
  &sig=4d6c...e1
```

The values are URL-encoded in the query. The signature is made over the decoded values, as your framework hands them to you.

### With an error

When something goes wrong, the user lands on your `callback_url` with `error`, `error_description` and your `state`, and no `sig`. Treat any callback with `error` as a failed check, and offer to start again with a new session.

| `error` | When |
| - | - |
| `expired_request` | The `authorize_url` was opened again after it was used, or after its 15 minutes. |
| `unsupported_platform` | The network can't be used for delegation. |
| `redirect_failed` | PostSyncer couldn't start the network's sign-in. |
| The network's own code, such as `access_denied` | The user said no, or the network refused. `error_description` is the network's own text. LinkedIn, for example, sends `user_cancelled_login`. |
| `invalid_state` | The sign-in took more than 20 minutes, or its return was already used. |
| `provider_mismatch` | The user came back from a different network than the one asked for. |
| `missing_platform_id` | The network didn't return an ID for the account. |
| `connection_failed` | PostSyncer couldn't finish the sign-in with the network. |

### Accept the first answer for a `state`

A user can come back more than once for the same session: with the Back button, a reload, or a second tab. After a proof, a second return for the same `state` arrives with `error=invalid_state`. Act on the first answer you get for a `state`, and once you've accepted a proof for it, ignore every later one.

### When PostSyncer can't send the user back

For a link PostSyncer never issued, or one more than about a day old, PostSyncer no longer knows your `callback_url`. The user then sees PostSyncer's own page at `/oauth/delegate?error=...`, which says the link has expired, or that their account couldn't be connected, and to go back to the app that sent them and start again. Your server gets nothing in that case, so let users start again from your side.

## 4. Check the proof

On your server, before you trust `platform_id`:

1. **`state`** is one you issued for this user and haven't used. Mark it used.
2. **`expires`** is in the future.
3. **`sig`** matches the HMAC you work out over the exact base string. Compare in constant time.

Only when all three pass is `platform_id` the account the user owns.

```javascript Node.js theme={null}
import crypto from "crypto";

function verifyDelegation(query, signingSecret, expectedState) {
  const { platform, platform_id, handle = "", state, expires, sig } = query;

  // 1. Your state, for this user, used once
  if (!state || state !== expectedState) return false;

  // 2. Still fresh
  if (!expires || Number(expires) < Math.floor(Date.now() / 1000)) return false;

  // 3. The signature
  const base =
    `platform=${platform}&platform_id=${platform_id}` +
    `&handle=${handle}&state=${state}&expires=${expires}`;
  const expected = crypto.createHmac("sha256", signingSecret).update(base).digest("hex");

  const given = Buffer.from(String(sig || ""));
  const wanted = Buffer.from(expected);
  return given.length === wanted.length && crypto.timingSafeEqual(given, wanted);
}
```

```php PHP theme={null}
<?php

function verifyDelegation(array $query, string $signingSecret, string $expectedState): bool
{
    // A value sent twice (?sig[]=…) arrives as an array: treat it as missing.
    $get = fn (string $key): string => is_string($query[$key] ?? null) ? $query[$key] : '';

    $platform   = $get('platform');
    $platformId = $get('platform_id');
    $handle     = $get('handle');
    $state      = $get('state');
    $expires    = $get('expires');
    $sig        = $get('sig');

    // 1. Your state, for this user, used once
    if ($state === '' || ! hash_equals($expectedState, $state)) {
        return false;
    }

    // 2. Still fresh
    if (! ctype_digit($expires) || (int) $expires < time()) {
        return false;
    }

    // 3. The signature
    $base = "platform={$platform}&platform_id={$platformId}&handle={$handle}&state={$state}&expires={$expires}";
    $expected = hash_hmac('sha256', $base, $signingSecret);

    return hash_equals($expected, $sig);
}
```

```python Python theme={null}
import hashlib
import hmac
import time

def verify_delegation(query, signing_secret, expected_state):
    platform = query.get("platform", "")
    platform_id = query.get("platform_id", "")
    handle = query.get("handle", "")
    state = query.get("state", "")
    expires = query.get("expires", "")
    sig = query.get("sig", "")

    # 1. Your state, for this user, used once (bytes, so any text compares safely)
    if not state or not hmac.compare_digest(state.encode(), expected_state.encode()):
        return False

    # 2. Still fresh
    if not (expires.isascii() and expires.isdigit()) or int(expires) < int(time.time()):
        return False

    # 3. The signature
    base = f"platform={platform}&platform_id={platform_id}&handle={handle}&state={state}&expires={expires}"
    expected = hmac.new(signing_secret.encode(), base.encode(), hashlib.sha256).hexdigest()

    return hmac.compare_digest(expected.encode(), sig.encode())
```

## Limits

* The delegation endpoints take 120 requests a minute from one IP address. See [Rate limits](/docs/rate-limits.md).
* Delegation works on every plan, Free included. Sessions don't count as posts or as connected accounts.

## Related

> [card] [Authentication](/docs/essentials/authentication.md)
>
> Make the key and choose its permissions.

> [card] [Error handling](/docs/essentials/error-handling.md#oauth-delegation)
>
> Every delegation error, with the API's others.

> [card] [Connect social accounts](/docs/guides/connect-accounts.md)
>
> Connect an account to post with it.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.