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

# Identity Verification

> Prove that events from your apps come from the customer they name, so a copied write key cannot change a customer's data or take over their push.

Your write key ships inside your app, so anyone can copy it. With the key alone, someone could send events in any customer's name: change their traits, unsubscribe them, or register their own phone to receive that customer's push.

Identity verification closes that gap. Your backend signs a short-lived **identity token** for the customer who is signed in. Your app hands it to the Tranthor SDK, and Tranthor checks it before it accepts the customer's events.

> [!NOTE]
>
> Identity verification proves **who** an event is about. To stop your key working in other apps and websites, also [restrict your write key](https://docs.tranthor.com/guide/write-key-restrictions.md). The two work together.

## How it works

1. You create an **identity secret** in Tranthor and store it on your backend.
2. When a customer signs in, your backend signs a token for their user id with that secret.
3. Your app passes the token to the SDK. The SDK sends it with that customer's events and asks your backend for a new one before it expires.
4. Tranthor checks the token. What happens next depends on the workspace's **verification mode**.

| Mode | What Tranthor does |
| - | - |
| **Off** | Accepts everything. Tokens aren't checked. This is the default. |
| **Monitor** | Accepts everything, and counts how many events carry a valid token. Use it to roll out. |
| **Required** | Refuses events that name a customer without a valid token. |

Modes apply to events sent with the write key: the SDKs and direct calls to the [public API](https://docs.tranthor.com/integrations/sources/api.md). Events from server integrations, such as Shopify, imports and the Admin API, are not affected.

## 1. Create an identity secret

1. In Tranthor, open **Settings > API keys** and find **Identity verification**.
2. Select **Create secret**. Tranthor shows the secret once. Copy it now.
3. Store it on your backend, for example as the `TRANTHOR_IDENTITY_SECRET` environment variable.

Only Owners and Admins can manage identity verification.

> [!WARNING]
>
> The identity secret lets anyone sign tokens for any of your customers. Keep it on your servers. Never put it in an app, a website or a repository.

A workspace can have two active secrets, so you can rotate one without downtime: create a second secret, move your backend to it, then **Revoke** the old one. Tranthor accepts tokens signed with either secret while both are active. Changes take effect within 30 seconds.

## 2. Sign tokens on your backend

An identity token is a JWT signed with HS256, using the whole identity secret (including its `tr_idsec_` prefix) as the key.

| Claim | Required | Value |
| - | - | - |
| `sub` | Yes | The customer's user id, exactly as your app passes it to `identify`. |
| `iat` | Yes | When the token was issued, in seconds. |
| `exp` | Yes | When it expires, in seconds. At most 7 days after `iat`. 24 hours is a good default. |
| `aud` | No | Limits the token to one app: its app ID on mobile, or its origin on the web. Leave it out to accept the token from any of your apps. |

Sign the token in the request that signs the customer in, and in an endpoint your app can call to renew it.

```javascript Node.js theme={null}
import { SignJWT } from "jose"; // npm install jose

const secret = new TextEncoder().encode(process.env.TRANTHOR_IDENTITY_SECRET);

export function identityToken(userId) {
  return new SignJWT()
    .setProtectedHeader({ alg: "HS256" })
    .setSubject(userId)
    .setIssuedAt()
    .setExpirationTime("24h")
    .sign(secret);
}
```

```python Python theme={null}
import os, time
import jwt  # pip install pyjwt

SECRET = os.environ["TRANTHOR_IDENTITY_SECRET"]

def identity_token(user_id: str) -> str:
    now = int(time.time())
    return jwt.encode(
        {"sub": user_id, "iat": now, "exp": now + 24 * 3600},
        SECRET,
        algorithm="HS256",
    )
```

```ruby Ruby theme={null}
require "jwt" # gem install jwt

SECRET = ENV.fetch("TRANTHOR_IDENTITY_SECRET")

def identity_token(user_id)
  now = Time.now.to_i
  JWT.encode({ sub: user_id, iat: now, exp: now + 24 * 3600 }, SECRET, "HS256")
end
```

```go Go theme={null}
import (
	"os"
	"time"

	"github.com/golang-jwt/jwt/v5" // go get github.com/golang-jwt/jwt/v5
)

var secret = []byte(os.Getenv("TRANTHOR_IDENTITY_SECRET"))

func identityToken(userID string) (string, error) {
	now := time.Now()
	claims := jwt.MapClaims{
		"sub": userID,
		"iat": now.Unix(),
		"exp": now.Add(24 * time.Hour).Unix(),
	}
	return jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString(secret)
}
```

```php PHP theme={null}
<?php
require 'vendor/autoload.php'; // composer require firebase/php-jwt

use Firebase\JWT\JWT;

function identityToken(string $userId): string
{
    $now = time();
    return JWT::encode(
        ['sub' => $userId, 'iat' => $now, 'exp' => $now + 24 * 3600],
        getenv('TRANTHOR_IDENTITY_SECRET'),
        'HS256'
    );
}
```

Only sign a token for the customer your backend has signed in. A token is proof that your backend vouches for that user id.

### Or let Tranthor sign it

If you would rather not write signing code, your backend can ask Tranthor for a token with the [mint endpoint](https://docs.tranthor.com/api-reference/endpoints/sdk-identity/mint-token.md). It needs an Admin API key, so call it from your backend only.

```bash theme={null}
curl -X POST "https://api.tranthor.com/api/admin/sdk-identity/tokens" \
  -H "Authorization: Bearer <ADMIN_API_KEY>" \
  -H "Content-Type: application/json" \
  -d '{ "workspaceId": "<WORKSPACE_ID>", "userId": "cus_123" }'
```

## 3. Pass tokens to the SDK

Give the SDK a token when the customer signs in, and a provider it can call for a new one. The provider receives a user id and returns a token for it, or `nil`/`null` if it has none. The SDK calls it when a token is about to expire or was refused, and waits for it at most 20 seconds.

```swift iOS theme={null}
let sdk = try await TranthorSDK.configure(Configuration(
    writeKey: "<your write key>",
    identityTokenProvider: { userId in try await MyBackend.identityToken(for: userId) }
))

try await sdk.identify(userId: "cus_123", identityToken: tokenFromSignIn)
```

```kotlin Android theme={null}
val config = Configuration(
    writeKey = "<your write key>",
    identityTokenProvider = { userId -> myBackend.identityTokenFor(userId) },
)
val sdk = TranthorSDK.configure(applicationContext, config)
sdk.identify(userId = "cus_123", identityToken = tokenFromSignIn)
```

You need iOS SDK 0.3.0 or later, or Android SDK 0.3.0 or later. The [iOS](https://docs.tranthor.com/integrations/sdks/ios.md#identity-verification) and [Android](https://docs.tranthor.com/integrations/sdks/android.md#identity-verification) pages explain how the SDK stores, renews and retries tokens.

The SDK never holds your identity secret and never checks a token itself. A provider that fails never holds back events in Off or Monitor: the SDK sends what it has and lets Tranthor decide.

### Calling the API directly

If you send events to the [public API](https://docs.tranthor.com/integrations/sources/api.md) yourself, send the token in the `x-tranthor-identity-token` header. For `/batch`, you can instead list the tokens in an `identityTokens` array in the body, one per customer in the batch. Tranthor checks at most 50 tokens per request.

```bash theme={null}
curl -X POST "https://api.tranthor.com/api/public/apps/track" \
  -H "Authorization: <WRITE_KEY>" \
  -H "x-tranthor-identity-token: <TOKEN>" \
  -H "Content-Type: application/json" \
  -d '{ "userId": "cus_123", "event": "Order Viewed", "messageId": "<UUID>" }'
```

> [!WARNING]
>
> The Web SDK and the Node SDK cannot send identity tokens yet. In Required mode, Tranthor refuses their events for signed-in customers. If you use either one, stay in Monitor for now.

## 4. Roll out with Monitor

Switch to Required only when you know your apps send valid tokens. Otherwise older app versions lose events.

1. Ship app versions that pass tokens to the SDK.
2. Select **Monitor**. Nothing is refused. The **Identity verification** section reports, for the last 7 days, the share of identified events that carried a valid token, broken down by SDK and version, and how many phones are verified.
3. Wait until at least **99% of identified events have been verified for 7 days**, and the verified phones cover the customers you care about.
4. Select **Required**. Tranthor shows the report again and asks you to confirm.

You can switch back to Monitor or Off at any time. The change applies within 30 seconds and loses nothing. Required may not be available in your workspace yet; until it is, the option says **Not available yet**.

## What Required changes

* **Events for a customer without a valid token are refused.** The whole request is refused with `403` and nothing in it is stored. The SDK asks your provider for a new token and sends the batch again, so nothing is lost when your backend can supply one.
* **Some events from customers who are not signed in are dropped.** These are anonymous `identify` calls (traits) and anonymous push and subscription events (`Installation Registered`, `Installation Removed`, `TRSubscriptionChange`, `Push Received`, `Push Opened`, `Push Dismissed`). Other anonymous events, such as `track`, `page` and `screen`, are still accepted. So identify the customer, with a token, before you send traits or register push.
* **Push goes only to verified phones.** A phone becomes verified when it registers with a valid token. In every mode, Tranthor sends to verified phones first. See [Who a phone belongs to](https://docs.tranthor.com/integrations/channels/mobile-push.md#who-a-phone-belongs-to).

## Troubleshooting

In Required, a refused request answers `403` with this body:

```json theme={null}
{
  "message": "Identity token missing or invalid for 1 user.",
  "code": "identity_not_verified",
  "reason": "expired",
  "userIds": ["cus_123"]
}
```

In Monitor, the response carries an `x-tranthor-unverified-events` header with the number of events that had no valid token. The SDKs report both through `onNotice`.

| `reason` | What it means | What to do |
| - | - | - |
| `missing` | No token was sent for this user id. | Pass a token to `identify`, or configure the provider. |
| `expired` | The token's `exp` is in the past. | Renew it. The provider handles this. |
| `signature` | The token was not signed with an active identity secret. | Check that your backend uses the current secret, whole, as the HMAC key. |
| `unknown_key` | The token names a secret (`kid`) that is not active. | Remove `kid`, or use the id of an active secret. |
| `lifetime` | `exp` is more than 7 days after `iat`. | Use a shorter lifetime. |
| `not_yet_valid` | `iat` is more than 2 minutes in the future. | Check your server's clock. |
| `audience` | `aud` does not match the app ID or origin that sent the request. | Fix `aud`, or leave it out. |
| `workspace` | The token has a `wid` claim that is not this workspace's id. | Remove `wid`, or fix it. |
| `malformed` | The token is not a valid HS256 JWT, or lacks `sub`, `iat` or `exp`. | Check your signing code. |

Renewing a token fixes only `missing` and `expired`. Every other reason means the code that signs your tokens needs fixing.


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