Skip to main content

Authentication with Header

An example of allowing or blocking a request based on a pre-shared key.

This sample is not designed to replace the WebCrypto API.

warning

Be careful for use in the production environment!

This code is an example and is not suitable for operational and production environments without protection against timing attacks.

The sample code has a public header key and a value of X-Custom-PSK and mypresharedkey. To further protect your resources, change the header key and its value before saving the code.

addEventListener("fetch", (event) => {
event.respondWith(handleRequest(event.request));
});


async function handleRequest(request) {
/**
* @param {string} PRESHARED_AUTH_HEADER_KEY Custom header to check for key
* @param {string} PRESHARED_AUTH_HEADER_VALUE Hard coded key value
*/
const PRESHARED_AUTH_HEADER_KEY = "X-Custom-PSK";
const PRESHARED_AUTH_HEADER_VALUE = "mypresharedkey";
const psk = request.headers.get(PRESHARED_AUTH_HEADER_KEY);

if (psk === PRESHARED_AUTH_HEADER_VALUE) {
// Correct preshared header key supplied. Fetch request from origin.
return fetch(req);
}

// Incorrect key supplied. Reject the request.
return new Response("Sorry, you have supplied an invalid key.", {
status: 403,
});
}