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

# Identity verification

> Stop anyone with your public key from sending events as one of your users.

## The problem

Your public key (`mq_live_…`) sits in your web page. Anyone can copy it and send `track` calls that name any `userId`. That can change a person's profile or start a journey that emails them.

## The fix

Your server signs a short-lived token that says "this call is for `u_42`". Maqetin checks the signature before it accepts a call that names that user. Only your server holds the private key, so only your server can make a valid token.

```mermaid theme={null}
sequenceDiagram
  participant B as Browser
  participant S as Your server
  participant M as Maqetin
  B->>S: I am signed in as u_42
  S->>B: A token for u_42, signed with your private key
  B->>M: track for u_42, with the token in a header
  M->>M: Check the signature with your public key
  M-->>B: 202 accepted, or 401 and a reason
```

## Set it up

**1. Create a signing key**

In the console, open **Developers**, then **Identity tokens**, and choose **Create signing key**. Only the owner can.

Copy the private key now. Maqetin keeps only the public half and cannot show the private key again. Store it in your server's secrets, never in a web page.

**2. Sign a token on your server**

Sign one for each signed-in person, and give it to your page. Any JWT library that signs ES256 works. The private key is the PEM you copied, and `kid` is the key id shown in the console.

```js Node.js theme={null}
import { createPrivateKey, sign } from 'node:crypto';

const privateKey = createPrivateKey(process.env.MAQETIN_IDENTITY_KEY);
const kid = process.env.MAQETIN_IDENTITY_KID; // the key id shown in the console
const b64url = (v) => Buffer.from(JSON.stringify(v)).toString('base64url');

export function identityToken(userId) {
  const now = Math.floor(Date.now() / 1000);
  const header = b64url({ alg: 'ES256', typ: 'JWT', kid });
  const claims = b64url({ sub: userId, iat: now, exp: now + 3600, aud: 'maqetin' });
  const signature = sign('sha256', Buffer.from(`${header}.${claims}`), {
    key: privateKey,
    dsaEncoding: 'ieee-p1363',
  });
  return `${header}.${claims}.${signature.toString('base64url')}`;
}
```

```python Python theme={null}
import os
import time

import jwt  # pip install pyjwt cryptography


def identity_token(user_id: str) -> str:
    now = int(time.time())
    return jwt.encode(
        {"sub": user_id, "iat": now, "exp": now + 3600, "aud": "maqetin"},
        os.environ["MAQETIN_IDENTITY_KEY"],
        algorithm="ES256",
        headers={"kid": os.environ["MAQETIN_IDENTITY_KID"]},
    )
```

```go Go theme={null}
package main

import (
	"fmt"
	"os"
	"time"

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

func identityToken(userID string) (string, error) {
	key, err := jwt.ParseECPrivateKeyFromPEM([]byte(os.Getenv("MAQETIN_IDENTITY_KEY")))
	if err != nil {
		return "", err
	}
	now := time.Now()
	token := jwt.NewWithClaims(jwt.SigningMethodES256, jwt.MapClaims{
		"sub": userID,
		"iat": now.Unix(),
		"exp": now.Add(time.Hour).Unix(),
		"aud": "maqetin",
	})
	token.Header["kid"] = os.Getenv("MAQETIN_IDENTITY_KID")
	return token.SignedString(key)
}
```

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

use Firebase\JWT\JWT;

function identityToken(string $userId): string
{
    $now = time();
    $claims = [
        'sub' => $userId,
        'iat' => $now,
        'exp' => $now + 3600,
        'aud' => 'maqetin',
    ];

    return JWT::encode(
        $claims,
        getenv('MAQETIN_IDENTITY_KEY'),
        'ES256',
        getenv('MAQETIN_IDENTITY_KID')
    );
}
```

```rust Rust theme={null}
use std::time::{SystemTime, UNIX_EPOCH};

use jsonwebtoken::{encode, Algorithm, EncodingKey, Header}; // cargo add jsonwebtoken serde --features serde/derive
use serde::Serialize;

#[derive(Serialize)]
struct Claims {
    sub: String,
    iat: u64,
    exp: u64,
    aud: &'static str,
}

fn identity_token(user_id: &str) -> Result<String, jsonwebtoken::errors::Error> {
    let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs();
    let claims = Claims { sub: user_id.to_string(), iat: now, exp: now + 3600, aud: "maqetin" };

    let mut header = Header::new(Algorithm::ES256);
    header.kid = Some(std::env::var("MAQETIN_IDENTITY_KID").unwrap());

    let pem = std::env::var("MAQETIN_IDENTITY_KEY").unwrap();
    encode(&header, &claims, &EncodingKey::from_ec_pem(pem.as_bytes())?)
}
```

**3. Send it with the call**

The call carries the token in the `Maqetin-Identity-Token` header. The SDK does it for you.

```ts JavaScript SDK theme={null}
import { MaqetinClient } from '@maqetin/sdk-js';

const mq = new MaqetinClient({
  publicKey: 'mq_live_…',
  // Asked before the token expires, when there is none, and when Maqetin refuses it.
  onIdentityTokenExpiring: async ({ userId, reason }) => {
    const res = await fetch('/api/maqetin-token'); // your server signs the token
    return res.text();
  },
});

mq.identify('u_42', { email: 'ada@example.com' }, { token: tokenFromYourServer });
mq.track('checkout.completed', { total: 12.5 }); // sent with the token
```

```sh curl theme={null}
curl https://in.maqetin.com/v1/track \
  -H 'Authorization: Bearer mq_live_…' \
  -H 'Maqetin-Identity-Token: eyJhbGciOiJFUzI1NiIs…' \
  -H 'Content-Type: application/json' \
  -d '{ "userId": "u_42", "event": "checkout.completed", "channel": "rest" }'
```

The SDK's token options need a version of `@maqetin/sdk-js` newer than 0.2.0. See [Identity token](https://docs.maqetin.com/sdk/javascript.md#identity-token).

**4. Turn it on**

Open **Developers**, then **Identity tokens**. Under **Identity check**, pick a mode and choose **Save mode**.

## Modes

| Mode | A call that names a user |
| - | - |
| **Disabled** | Accepted. Tokens are ignored. |
| **Optional** | Accepted. A token that comes is checked and the result is logged. |
| **Required** | Accepted only with a valid token for that user. Otherwise `401`. |

A workspace that has not chosen a mode is in **Required** mode. Only the owner changes the mode, and choosing **Required** asks for a confirmation.

Roll it out in order: create a key, set **Optional**, start sending tokens, then set **Required** once every call carries one.

## What the token holds

| Part | Value |
| - | - |
| Header `alg` | `ES256` |
| Header `kid` | The key id of the signing key |
| `sub` | The person's `userId`, exactly as your app sends it |
| `exp` | Required. At most 24 hours ahead. A minute of clock difference is allowed |
| `aud` | Optional. If you set it, it must be `maqetin` |

Every `userId` in the call must equal `sub`. Calls that carry only an `anonymousId` need no token, and neither does a secret key sending to `/v1/batch`. An hour is a good lifetime.

## If a call is refused

A refused token is a `401` whose body names the reason, for example `{ "error": "token_expired" }`.

| `error` | Fix |
| - | - |
| `token_required` | The mode is **Required** and the call had no token. Send one. |
| `token_expired` | Sign a new token. |
| `exp_required` | Add `exp`, and keep it within 24 hours. |
| `invalid_signature` | The token is malformed, is not ES256, has no `sub`, has the wrong `aud`, or was signed with another key. |
| `no_matching_key` | No live key has the token's `kid`. It may be revoked. |
| `sub_mismatch` | A `userId` in the call differs from `sub`. |

In **Optional** mode none of these refuse the call. See [Errors](https://docs.maqetin.com/api-reference/errors.md#identity-token) for the rest.

## Rotate and revoke keys

A workspace has up to three live keys. In the **Signing keys** list:

* **Rotate** makes a new key with the same name. The old one stays live, so deploy the new key first.
* **Revoke** stops a key within a minute and cannot be undone. Move your server to another live key first.


## Related topics

- [Quickstart](https://docs.maqetin.com/quickstart.md)
- [JavaScript SDK](https://docs.maqetin.com/sdk/javascript.md)
- [Identify](https://docs.maqetin.com/api-reference/identify.md)
- [Batch](https://docs.maqetin.com/api-reference/batch.md)
- [Track](https://docs.maqetin.com/api-reference/track.md)


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