> For the complete documentation index, see [llms.txt](https://dev.strixlab.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://dev.strixlab.io/http-and-websocket-api/authentication.md).

# Authentication

Public endpoints — events, order books, candles, the activity feed — need no credentials at all. Everything that trades or reads an account needs **HMAC API keys**.

{% hint style="info" %}
Using [`strix-sdk`](/get-started/installation.md)? Signing is handled for you — pass the three credentials to the constructor and skip this page. Read on if you're integrating from another language.
{% endhint %}

### Getting credentials

In the app: **Settings → API Keys → Generate Keys**.

<table><thead><tr><th width="200">Credential</th><th>Notes</th></tr></thead><tbody><tr><td><code>apiKey</code></td><td>Public identifier. Visible in settings at any time.</td></tr><tr><td><code>apiSecret</code></td><td>Signing secret. Shown <strong>once</strong> — store it immediately.</td></tr><tr><td><code>apiPassphrase</code></td><td>Sent with every request. Shown <strong>once</strong>.</td></tr></tbody></table>

{% hint style="warning" %}
Regenerating credentials invalidates the old ones **immediately**, including live WebSocket sessions. Handle `401` by reloading credentials rather than retrying blindly.
{% endhint %}

### Headers

Every authenticated request carries four:

<table><thead><tr><th width="230">Header</th><th>Value</th></tr></thead><tbody><tr><td><code>STRIX-API-KEY</code></td><td>Your <code>apiKey</code> — <strong>not</strong> your wallet address.</td></tr><tr><td><code>STRIX-TIMESTAMP</code></td><td>Current Unix time in <strong>seconds</strong>.</td></tr><tr><td><code>STRIX-PASSPHRASE</code></td><td>Your passphrase, in plain text.</td></tr><tr><td><code>STRIX-SIGNATURE</code></td><td>Base64 HMAC-SHA256, built below.</td></tr></tbody></table>

### The signature

```
message   = timestamp + METHOD + path + body
signature = base64( HMAC-SHA256(apiSecret, message) )
```

<table><thead><tr><th width="170">Part</th><th>Rule</th></tr></thead><tbody><tr><td><code>timestamp</code></td><td>The same value you put in <code>STRIX-TIMESTAMP</code>. Unix <strong>seconds</strong>, as a string.</td></tr><tr><td><code>METHOD</code></td><td>Uppercase verb — <code>GET</code>, <code>POST</code>, <code>DELETE</code>.</td></tr><tr><td><code>path</code></td><td>The path <strong>without</strong> the <code>/api</code> prefix, <strong>including</strong> the query string.</td></tr><tr><td><code>body</code></td><td>The exact JSON string you send, byte for byte. Empty string when there is no body.</td></tr></tbody></table>

{% hint style="danger" %}
**The `/api` prefix is not part of the signed path.** The server verifies against the path *inside* its router, which is mounted at `/api`. So a request to `https://api.strixlab.io/api/orders?marketId=abc` signs:

```
/orders?marketId=abc
```

Signing `/api/orders` produces a perfectly valid-looking signature that fails **every** request with `invalid_signature`. This is the single most common integration bug.
{% endhint %}

Two more rules that trip people up:

* **Sign the exact bytes you send.** Re-serialising the body after signing (a different key order, different whitespace) invalidates the signature.
* **Timestamps older than 30 seconds are rejected.** Keep the host clock NTP-synced; check drift against `GET /api/time` at startup.

### Examples

{% tabs %}
{% tab title="TypeScript" %}
{% code title="sign.ts" %}

```ts
import crypto from 'node:crypto';

const BASE_URL   = 'https://api.strixlab.io/api';
const API_KEY    = process.env.STRIX_API_KEY!;
const API_SECRET = process.env.STRIX_API_SECRET!;
const PASSPHRASE = process.env.STRIX_API_PASSPHRASE!;

function sign(method: string, path: string, body = '') {
  const ts  = Math.floor(Date.now() / 1000).toString();
  const msg = ts + method.toUpperCase() + path + body;      // path WITHOUT /api
  return {
    'STRIX-API-KEY':    API_KEY,
    'STRIX-TIMESTAMP':  ts,
    'STRIX-PASSPHRASE': PASSPHRASE,
    'STRIX-SIGNATURE':  crypto.createHmac('sha256', API_SECRET).update(msg).digest('base64'),
    'Content-Type':     'application/json',
  };
}

// GET with a query string — the query is part of the signed path
const orders = await fetch(`${BASE_URL}/orders?marketId=mkt_abc`, {
  headers: sign('GET', '/orders?marketId=mkt_abc'),
});

// POST — sign the exact body string you send
const body = JSON.stringify({ tokenId: '0x1a2b', side: 'BUY', price: 0.55, quantity: 100 });
const placed = await fetch(`${BASE_URL}/orders`, {
  method: 'POST',
  headers: sign('POST', '/orders', body),
  body,
});
```

{% endcode %}
{% endtab %}

{% tab title="Python" %}
{% code title="sign.py" %}

```python
import base64, hashlib, hmac, json, os, time
import requests

BASE_URL   = "https://api.strixlab.io/api"
API_KEY    = os.environ["STRIX_API_KEY"]
API_SECRET = os.environ["STRIX_API_SECRET"]
PASSPHRASE = os.environ["STRIX_API_PASSPHRASE"]

def sign(method: str, path: str, body: str = "") -> dict:
    ts  = str(int(time.time()))
    msg = ts + method.upper() + path + body          # path WITHOUT /api
    sig = base64.b64encode(
        hmac.new(API_SECRET.encode(), msg.encode(), hashlib.sha256).digest()
    ).decode()
    return {
        "STRIX-API-KEY":    API_KEY,
        "STRIX-TIMESTAMP":  ts,
        "STRIX-PASSPHRASE": PASSPHRASE,
        "STRIX-SIGNATURE":  sig,
        "Content-Type":     "application/json",
    }

body = json.dumps({"tokenId": "0x1a2b", "side": "BUY", "price": 0.55, "quantity": 100})
res  = requests.post(f"{BASE_URL}/orders", headers=sign("POST", "/orders", body), data=body)
print(res.json())
```

{% endcode %}
{% endtab %}

{% tab title="Go" %}
{% code title="sign.go" %}

```go
package main

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/base64"
	"net/http"
	"os"
	"strconv"
	"strings"
	"time"
)

func sign(req *http.Request, path, body string) {
	secret := os.Getenv("STRIX_API_SECRET")
	ts := strconv.FormatInt(time.Now().Unix(), 10)

	mac := hmac.New(sha256.New, []byte(secret))
	mac.Write([]byte(ts + strings.ToUpper(req.Method) + path + body)) // path WITHOUT /api

	req.Header.Set("STRIX-API-KEY", os.Getenv("STRIX_API_KEY"))
	req.Header.Set("STRIX-TIMESTAMP", ts)
	req.Header.Set("STRIX-PASSPHRASE", os.Getenv("STRIX_API_PASSPHRASE"))
	req.Header.Set("STRIX-SIGNATURE", base64.StdEncoding.EncodeToString(mac.Sum(nil)))
	req.Header.Set("Content-Type", "application/json")
}
```

{% endcode %}
{% endtab %}

{% tab title="curl" %}
{% code title="sign.sh" %}

```bash
#!/usr/bin/env bash
API_KEY="$STRIX_API_KEY"; SECRET="$STRIX_API_SECRET"; PASS="$STRIX_API_PASSPHRASE"

TS=$(date +%s)
METHOD="GET"
PATH_="/orders"                                   # no /api prefix
BODY=""

SIG=$(printf '%s' "${TS}${METHOD}${PATH_}${BODY}" \
  | openssl dgst -sha256 -hmac "$SECRET" -binary \
  | base64)

curl -s "https://api.strixlab.io/api${PATH_}" \
  -H "STRIX-API-KEY: $API_KEY" \
  -H "STRIX-TIMESTAMP: $TS" \
  -H "STRIX-PASSPHRASE: $PASS" \
  -H "STRIX-SIGNATURE: $SIG"
```

{% endcode %}
{% endtab %}
{% endtabs %}

### WebSocket authentication

The socket uses the same secret with a fixed message: `timestamp + "GET" + "/ws"`.

```jsonc
{
  "type":       "auth",
  "apiKey":     "your_api_key",
  "passphrase": "your_passphrase",
  "timestamp":  "1716000000",
  "signature":  "<base64 HMAC-SHA256(apiSecret, timestamp + 'GET' + '/ws')>"
}
```

The server replies with an `authenticated` frame, after which your account's events stream automatically — there is no further subscribe step. A failed auth arrives as an `error` frame, **not** a socket close, so handle it explicitly.

If you're on the SDK, the helpers are exported:

```ts
import { buildSignature, buildWsSignature, buildTimestamp } from 'strix-sdk';
```

### Debugging a 401

{% stepper %}
{% step %}

#### Is the path right?

Sign `/orders`, not `/api/orders`. Include the query string exactly as sent.
{% endstep %}

{% step %}

#### Is the body identical?

Sign the serialized string, then send that same string. Don't rebuild it.
{% endstep %}

{% step %}

#### Is the clock right?

`GET /api/time` returns server Unix seconds. More than 30 seconds out and every request fails.
{% endstep %}

{% step %}

#### Is it the right credential?

`STRIX-API-KEY` carries the **apiKey**, not the wallet address. And check the key hasn't been regenerated since you last stored it.
{% endstep %}
{% endstepper %}

### Browser sessions

Frontends holding a Privy session can pass the identity token instead:

```
Authorization: Bearer <privy_identity_token>
```

{% hint style="warning" %}
Bearer tokens expire and are unsuitable for long-running bots. Use HMAC for anything automated — and never ship an `apiSecret` to a browser.
{% endhint %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://dev.strixlab.io/http-and-websocket-api/authentication.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
