根据标头中的已知预共享密钥允许或拒绝请求。
示例代码
/**
* @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"
async function handleRequest(request) {
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(request)
}
// Incorrect key supplied. Reject the request.
return new Response("Sorry, you have supplied an invalid key.", {
status: 403,
})
}
addEventListener("fetch", event => {
event.respondWith(handleRequest(event.request))
})
示例预览
在请求过程中不带密钥访问,请求被拒绝。
相关参考
- 运行时API:addEventListener
- 运行时API:FetchEvent
- 运行时API:Web Standards
- 运行时API:Response
- 运行时API:Fetch