通过UA进行黑白名单限制。
示例代码
//放行User-Agent:Mozilla/5.0的请求
function ua_verify(ua){
let regex = /Mozilla\/5.0/
return regex.test(ua)
}
async function handle(request) {
//401表示鉴权不通过
let statuscode = 401
let result = 'Verification failed!'
try {
//解析Request对象中的UA
let myHeaders = new Headers(request.headers)
//封禁空UA
if(!myHeaders.get('User-Agent')){
throw new Error('UA is empty!')
}
//精确匹配,不忽略大小写
if(ua_verify(myHeaders.get('User-Agent'))){
statuscode = 200
result = "Verification succeeded!"
}
} catch (error) {
result = result + error
}
return new Response(result, { "status": statuscode });
}
addEventListener('fetch', event => {
event.respondWith(handle(event.request))
})
示例预览
通过火狐浏览器访问,返回鉴权成功。
相关参考
- 运行时API:addEventListener
- 运行时API:FetchEvent
- 运行时API:Web Standards
- 运行时API:Response
- 运行时API:Fetch