Policies
HMAC Auth
This example policy demonstrates how to use a shared secret to create an HMAC signature to sign a payload (in this case the body). When the request is sent, the signature is sent in the request header. The policy can then verify that the signature matches the payload - thus ensuring that the sender had the same shared secret.
This policy is configured with the value of the secret
. Normally, you would
store this as an environment variable secret. Additionally, the policy option
headerName
is used to set the header that will be used by the client to send
the signature.
Configuration#
{
"name": "my-hmac-auth-inbound-policy",
"policyType": "hmac-auth-inbound",
"handler": {
"export": "default",
"module": "$import(./modules/YOUR_MODULE)",
"options": {
"secret": "$env(MY_SECRET)",
"headerName": "signed-request"
}
}
}
Options#
name
the name of your policy instance. This is used as a reference in your routes.policyType
the identifier of the policy. This is used by the Zuplo UI. Value should behmac-auth-inbound
.handler/export
The name of the exported type. Value should bedefault
.handler/module
the module containing the policy. Value should be$import(./modules/YOUR_MODULE)
.handler/options
The options for this policy:secret
The secret to use for HMAC authentication
headerName
The header where the HMAC signature is send
Signing a Value
The example below demonstrates how you could sign a value in order to create an HMAC signature for use with this policy.
const token = await sign("my data", environment.MY_SECRET);
async function sign(
key: string | ArrayBuffer,
val: string,
): Promise<ArrayBuffer> {
const encoder = new TextEncoder();
const cryptoKey = await crypto.subtle.importKey(
"raw",
typeof key === "string" ? encoder.encode(key) : key,
{ name: "HMAC", hash: { name: "SHA-256" } },
false,
["sign"],
);
const token = await crypto.subtle.sign(
"HMAC",
cryptoKey,
encoder.encode(val),
);
return Array.prototype.map
.call(new Uint8Array(token), (x) => ("0" + x.toString(16)).slice(-2))
.join("");
}