---
title: "React, Vue or Angular: receive webhooks"
description: "Close the session in your app when the user closes it from Block-Auth."
url: "/sdk-integration-spa-webhooks/"
language: "en"
guide: "React, Vue, Angular (+ backend)"
step: "More options, optional"
---

# Receive webhooks

Optional, recommended for production. Login works without it, but if the user signs out from Block-Auth (Identity, the extension or another device), your app won’t know.

> How you add the backend login routes: this page covers “With the Block-Auth package” or “My own implementation”. Both variants are written out below, each one marked. Follow only the one that matches the app.

## Receive webhooks

Block-Auth calls your backend when a user signs out of your app from Block-Auth (`signout`) or unlinks your app (`account.unlinked`), so you can close their session too.

This is how a sign-out made in Block-Auth (Identity, the extension or another device) reaches your page:

1. Block-Auth: The user signs out
2. Block-Auth → Your backend: `POST /webhook · signout`
3. Your backend: Saves the sign-out
4. Your frontend → Your backend: GET /me on focus or every 60 s
5. Your backend → Your frontend: `401`
6. Your frontend: Shows the user signed out

<!---->

1. In the Dashboard, open your application's **Authentication** settings. In the third URL field, shown as **"When user fails to log in"**, type the path `/auth/blockauth/webhook` (your domain is already filled in).

### How you add the backend login routes: With the Block-Auth package.

2. Add these options to the `BlockAuthRoutes` from [step 2](/sdk-integration-spa-backend.md#add-to-server), so the package knows how to remember a sign-out and check it. `POST /webhook` is already there: it verifies the request and calls `onSignout` or `onUnlinked`. Then `isRevoked` closes every session that started before that sign-out:

**Node.js · Your server · the BlockAuthRoutes from step 2**

```javascript
export const routes = new BlockAuthRoutes({
  apiKey: process.env.BLOCKAUTH_API_KEY,
  apiSecret: process.env.BLOCKAUTH_API_SECRET,
  appUrl: process.env.APP_URL,
  onSignout: (event) => saveSignout(event.address, event.iat),
  onUnlinked: async (event) => {
    await saveSignout(event.address, event.iat)
    await removeLink(event.externalId)
  },
  isRevoked: async (user) => ((await lastSignout(user.address.toLowerCase())) ?? -1) >= user.loggedInAt,
})
```

**PHP · Your PHP · the BlockAuthRoutes from step 2**

```php
$routes = new BlockAuthRoutes(getenv('BLOCKAUTH_API_KEY'), getenv('BLOCKAUTH_API_SECRET'), [
    'appUrl' => getenv('APP_URL'),
    'onSignout' => fn (array $event) => saveSignout($event['address'], $event['iat']),
    'onUnlinked' => function (array $event): void {
        saveSignout($event['address'], $event['iat']);
        removeLink($event['externalId']);
    },
    'isRevoked' => fn (array $user): bool => (lastSignout(strtolower($user['address'])) ?? -1) >= $user['loggedInAt'],
]);
```

**Python · Your app · the BlockAuthRoutes from step 2**

```python
def on_unlinked(event):
    save_signout(event["address"], event["iat"])
    remove_link(event["externalId"])

routes = BlockAuthRoutes(
    os.environ["BLOCKAUTH_API_KEY"],
    os.environ["BLOCKAUTH_API_SECRET"],
    app_url=os.environ["APP_URL"],
    on_signout=lambda event: save_signout(event["address"], event["iat"]),
    on_unlinked=on_unlinked,
    is_revoked=lambda user: (last_signout(user["address"].lower()) or -1) >= user["loggedInAt"],
)
```

**.NET · Program.cs · the AddBlockAuth from step 2**

```csharp
builder.Services.AddBlockAuth(options =>
{
    options.ApiKey = builder.Configuration["BLOCKAUTH_API_KEY"]!;
    options.ApiSecret = builder.Configuration["BLOCKAUTH_API_SECRET"]!;
    options.AppUrl = builder.Configuration["APP_URL"];
    options.OnSignout = payload => SaveSignoutAsync(payload.Address, payload.Iat);
    options.OnUnlinked = async payload =>
    {
        await SaveSignoutAsync(payload.Address, payload.Iat);
        await RemoveLinkAsync(payload.ExternalId);
    };
    options.IsRevoked = async user => (await LastSignoutAsync(user.Address.ToLowerInvariant()) ?? -1) >= user.LoggedInAt;
});
```

> **Placeholders in this code:**
>
> - `saveSignout`, `lastSignout`, `removeLink` are yours: replace them with your app’s own functions (your database, your cache…).
> - `save_signout`, `last_signout`, `remove_link` are yours: replace them with your app’s own functions (your database, your cache…).
> - `SaveSignoutAsync`, `LastSignoutAsync`, `RemoveLinkAsync` are yours: replace them with your app’s own functions (your database, your cache…).

`saveSignout`, `lastSignout` and `removeLink` are yours: keep them in your database or a shared cache such as Redis, so every server instance sees them. `address` arrives in lowercase and `iat` and `loggedInAt` are Unix seconds.

- `isRevoked` runs on every `GET /me` and every time you read the user. The widget asks `/me` when the tab gets focus and every minute, so the page signs out by itself.
- To reject a repeated delivery, add `isReplay(jti)` and return `true` if you already saw that `jti`.

### How you add the backend login routes: My own implementation.

2. Add the route. It checks the signature (headers `X-BlockAuth-Timestamp` and `X-BlockAuth-Signature`), checks that the `apiKey` is yours and ignores repeated `jti`:

**Body · What your server receives (not code to copy) (example only, not to copy)**

```json
{
  "event": "account.unlinked",
  "apiKey": "your_api_key",
  "address": "0x8f2a…c41d",
  "externalId": "42",
  "iat": 1762790400,
  "jti": "5c1e2b7a-…"
}
```

> **Placeholders in this code:**
>
> - Replace `your_api_key` with your API Key, or fill in your data in the SDK Quickstart and it is filled in for you.

**Node.js · server.js · next to your Block-Auth routes**

```javascript
const seen = new Map()

app.post('/auth/blockauth/webhook', express.raw({ type: '*/*' }), (req, res) => {
  const body = req.body.toString('utf8')
  const timestamp = req.get('X-BlockAuth-Timestamp') ?? ''
  const signature = req.get('X-BlockAuth-Signature') ?? ''
  const expected = `v1=${crypto.createHmac('sha256', API_SECRET_HASH).update(`${timestamp}.${body}`).digest('hex')}`
  const fresh = Math.abs(Date.now() / 1000 - Number(timestamp)) <= 300
  const valid =
    signature.length === expected.length && crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected))
  if (!fresh || !valid) return res.status(401).end()

  const event = JSON.parse(body)
  if (event.apiKey !== BLOCKAUTH_API_KEY || seen.has(event.jti)) return res.status(409).end()
  seen.set(event.jti, Date.now())

  endSessionsOf(event.address)
  if (event.event === 'account.unlinked') markUnlinked(event.externalId)
  res.json({ ok: true })
})
```

**PHP · public/index.php · next to your Block-Auth routes**

```php
if ($route === 'POST /auth/blockauth/webhook') {
    try {
        $event = $blockauth->verifyWebhook(
            file_get_contents('php://input'),
            $_SERVER['HTTP_X_BLOCKAUTH_TIMESTAMP'] ?? '',
            $_SERVER['HTTP_X_BLOCKAUTH_SIGNATURE'] ?? ''
        );
    } catch (BlockAuthException $e) {
        json(401, ['ok' => false]);
    }
    if (($event['apiKey'] ?? null) !== getenv('BLOCKAUTH_API_KEY') || alreadyProcessed($event['jti'])) {
        json(409, ['ok' => false]);
    }
    endSessionsOf($event['address']);
    if ($event['event'] === 'account.unlinked') {
        markUnlinked($event['externalId']);
    }
    json(200, ['ok' => true]);
}
```

**Python · app.py · next to your Block-Auth routes**

```python
@app.post("/auth/blockauth/webhook")
def webhook():
    try:
        event = blockauth.verify_webhook(
            request.get_data(),
            request.headers.get("X-BlockAuth-Timestamp", ""),
            request.headers.get("X-BlockAuth-Signature", ""),
        )
    except BlockAuthError:
        return jsonify(ok=False), 401
    if event.get("apiKey") != os.environ["BLOCKAUTH_API_KEY"] or already_processed(event["jti"]):
        return jsonify(ok=False), 409
    end_sessions_of(event["address"])
    if event["event"] == "account.unlinked":
        mark_unlinked(event.get("externalId"))
    return jsonify(ok=True)
```

**.NET · Program.cs · next to your Block-Auth routes**

```csharp
app.MapPost("/auth/blockauth/webhook", async (HttpRequest request, AuthCodeClient blockauth) =>
{
    using var reader = new StreamReader(request.Body);
    var raw = await reader.ReadToEndAsync();
    try
    {
        var evt = blockauth.VerifyWebhook(
            raw,
            request.Headers["X-BlockAuth-Timestamp"],
            request.Headers["X-BlockAuth-Signature"]);
        if (AlreadyProcessed(evt.Jti)) return Results.Conflict();
        EndSessionsOf(evt.Address);
        if (evt.Event == "account.unlinked") MarkUnlinked(evt.ExternalId);
        return Results.Ok(new { ok = true });
    }
    catch (BlockAuthException)
    {
        return Results.Unauthorized();
    }
});
```

> **Placeholders in this code:**
>
> - `endSessionsOf`, `markUnlinked` are yours: replace them with your app’s own functions (your database, your cache…).
> - `endSessionsOf`, `markUnlinked`, `alreadyProcessed` are yours: replace them with your app’s own functions (your database, your cache…).
> - `end_sessions_of`, `mark_unlinked`, `already_processed` are yours: replace them with your app’s own functions (your database, your cache…).
> - `EndSessionsOf`, `MarkUnlinked`, `AlreadyProcessed` are yours: replace them with your app’s own functions (your database, your cache…).

`endSessionsOf`, `markUnlinked` and `alreadyProcessed` are yours: they depend on how your app stores sessions and users.
