通过时间戳进行请求防盗链。
示例代码
/*
示例url:https://ctyun.cn/timestamp?time=1622531831755&token=abcabc
*/
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
async function handleRequest(request){
//401表示鉴权不通过
let statuscode = 401
let result = 'TimeStamp verification failed!'
try {
if(verifyTimeStamp(request.url) == true){
statuscode = 200
result = "TimeStamp verification succeeded!"
// 返回请求内容
}
} catch (error) {
result = error
}
return new Response(result, { "status": statuscode })
}
function verifyTimeStamp(url){
//"url": "https://ctyun.cn/timestamp?time=1622531831755&token=abcabc",
let currentTime = new Date().getTime()
let myURL = new URL(url)
let searchParams = new URLSearchParams(myURL.search)
let timeStamp = parseInt(searchParams.get('time'))
let token = searchParams.get('token')
// 校验时间戳:如果时间戳距离当前时间没有过期,则进行 token 检查
if (currentTime - timeStamp < 60000) {
// 校验token
return tokenCheck(token)
}
return false
}
function tokenCheck(token){
// 此处可替换为自定义的复杂加解密算法
return token == "abcabc"
}
示例预览
访问请求传入未过期时间、鉴权token,鉴权通过。