Webhook Verification
Every webhook Cas sends to your system is signed with the secret key of that webhook. You should verify the signature before processing the data, to make sure the request really comes from Cas and its content was not modified in transit.
Each webhook has its own secret key, which you can find on the webhook configuration page in Cas Console. Keep the secret key on your server and never ship it in client-side code.
Headers
Each webhook request carries the following 2 headers:
| Header | Description |
|---|---|
X-Cas-Timestamp | The time Cas sent the request, as a Unix timestamp in milliseconds. Example: 1732352400000 |
X-Cas-Signature | The HMAC-SHA512 signature of the request, as a lowercase hex string (128 characters) |
Verification steps
- Read
X-Cas-TimestampandX-Cas-Signaturefrom the headers. - Read the raw body of the request, i.e. the original JSON string you received.
- Build the message to sign in this format:
{X-Cas-Timestamp}.{raw body} - Compute the HMAC-SHA512 of that message using the secret key, hex-encoded.
- Compare the result with
X-Cas-Signature. If they match, the request is valid. - Recommended: reject requests whose
X-Cas-Timestampdiffers from your system clock by more than 5 minutes to prevent replay attacks.
Always compute the signature over the raw body. Do not parse the JSON and serialize it back to a string, because key order, whitespace or character escaping may change and the signature will no longer match.
- Each time a webhook is retried, Cas generates a new
X-Cas-TimestampandX-Cas-Signature. - Use a constant-time comparison function instead of
==when comparing signatures. - Keep your server clock synchronized (NTP) so the timestamp check works correctly.
Example
You can use the data below to test your signature function (skip the timestamp check):
| Value | |
|---|---|
| Secret key | b3c1f9a2-7d4e-4c8a-9f21-5e6d7c8b9a01 |
X-Cas-Timestamp | 1732352400000 |
| Raw body | {"environment":"dev","webhookType":"GRANT","webhookCode":"DEFAULT_UPDATE","grantId":"4c657924-13f3-11ee-a4bb-42010a40001b","error":null} |
Message to sign:
1732352400000.{"environment":"dev","webhookType":"GRANT","webhookCode":"DEFAULT_UPDATE","grantId":"4c657924-13f3-11ee-a4bb-42010a40001b","error":null}
Expected signature (X-Cas-Signature):
9031281e6559f0d801c242d2241f65747dfccf04faaef471162f61955e213118276f0916b882adae065e9be33c7b0660034437de60d272df9c7d4990338c558b
Sample code
- Node.js
- Java
- PHP
Example with Express. Use express.raw() to get the raw body, do not use express.json() for this route.
const crypto = require('crypto');
const express = require('express');
const app = express();
const WEBHOOK_SECRET = process.env.CAS_WEBHOOK_SECRET; // Webhook secret key
const TOLERANCE_MS = 5 * 60 * 1000; // 5 minutes
function verifyCasSignature(rawBody, timestamp, signature, secret) {
if (!timestamp || !signature) return false;
// Replay protection: reject requests whose timestamp is off by more than 5 minutes
const ts = Number(timestamp);
if (!Number.isFinite(ts) || Math.abs(Date.now() - ts) > TOLERANCE_MS) return false;
const expected = crypto
.createHmac('sha512', secret)
.update(`${timestamp}.${rawBody}`)
.digest('hex');
const a = Buffer.from(expected);
const b = Buffer.from(signature);
return a.length === b.length && crypto.timingSafeEqual(a, b);
}
app.post('/webhook', express.raw({ type: 'application/json' }), (req, res) => {
const rawBody = req.body.toString('utf8');
const isValid = verifyCasSignature(
rawBody,
req.get('X-Cas-Timestamp'),
req.get('X-Cas-Signature'),
WEBHOOK_SECRET,
);
if (!isValid) return res.status(401).send('Invalid signature');
const event = JSON.parse(rawBody);
// TODO: handle the event
return res.sendStatus(200);
});
app.listen(3000);
The verifier only uses the Java standard library (Java 8 or later):
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
public final class CasWebhookVerifier {
private static final long TOLERANCE_MS = 5 * 60 * 1000L; // 5 minutes
public static boolean verify(byte[] rawBody, String timestamp, String signature, String secret) {
if (timestamp == null || signature == null) return false;
try {
// Replay protection: reject requests whose timestamp is off by more than 5 minutes
long ts = Long.parseLong(timestamp);
if (Math.abs(System.currentTimeMillis() - ts) > TOLERANCE_MS) return false;
Mac mac = Mac.getInstance("HmacSHA512");
mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA512"));
mac.update((timestamp + ".").getBytes(StandardCharsets.UTF_8));
byte[] hash = mac.doFinal(rawBody);
StringBuilder expected = new StringBuilder();
for (byte b : hash) expected.append(String.format("%02x", b));
return MessageDigest.isEqual(
expected.toString().getBytes(StandardCharsets.UTF_8),
signature.getBytes(StandardCharsets.UTF_8));
} catch (Exception e) {
return false;
}
}
}
Usage in Spring Boot. Receive the body as byte[] to keep the raw body intact:
@RestController
public class CasWebhookController {
@Value("${cas.webhook-secret}")
private String webhookSecret; // Webhook secret key
@PostMapping("/webhook")
public ResponseEntity<String> handle(
@RequestBody byte[] rawBody,
@RequestHeader(value = "X-Cas-Timestamp", required = false) String timestamp,
@RequestHeader(value = "X-Cas-Signature", required = false) String signature) {
if (!CasWebhookVerifier.verify(rawBody, timestamp, signature, webhookSecret)) {
return ResponseEntity.status(401).body("Invalid signature");
}
// TODO: parse rawBody (JSON) and handle the event
return ResponseEntity.ok("OK");
}
}
Example with plain PHP. With Laravel, use $request->getContent() to get the raw body and $request->header('X-Cas-Signature') to read the header.
<?php
const TOLERANCE_MS = 5 * 60 * 1000; // 5 minutes
function verifyCasSignature(string $rawBody, ?string $timestamp, ?string $signature, string $secret): bool
{
if (empty($timestamp) || empty($signature) || !ctype_digit($timestamp)) {
return false;
}
// Replay protection: reject requests whose timestamp is off by more than 5 minutes
$nowMs = (int) floor(microtime(true) * 1000);
if (abs($nowMs - (int) $timestamp) > TOLERANCE_MS) {
return false;
}
$expected = hash_hmac('sha512', $timestamp . '.' . $rawBody, $secret);
return hash_equals($expected, $signature);
}
$rawBody = file_get_contents('php://input');
$timestamp = $_SERVER['HTTP_X_CAS_TIMESTAMP'] ?? null;
$signature = $_SERVER['HTTP_X_CAS_SIGNATURE'] ?? null;
$secret = getenv('CAS_WEBHOOK_SECRET'); // Webhook secret key
if (!verifyCasSignature($rawBody, $timestamp, $signature, $secret)) {
http_response_code(401);
exit('Invalid signature');
}
$event = json_decode($rawBody, true);
// TODO: handle the event
http_response_code(200);
echo 'OK';