Created
July 10, 2023 07:01
-
-
Save ensean/a814ac2cdbe0eaa0af536b7d3883f21e to your computer and use it in GitHub Desktop.
cloudfront function for request auth
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var crypto = require('crypto'); | |
//Update with your own key. | |
var magic_key = "Set_at_your_wish"; | |
// default validation is 12 hours, update it when necessary | |
var time_delta = 12 * 3600; | |
//Response when token ts does not match. | |
var response403 = { | |
statusCode: 403, | |
statusDescription: 'Unauthorized', | |
headers: { | |
'cache-control': { | |
'value': 'max-age=1296000' | |
} | |
} | |
}; | |
function is_valid_qs(token, ts, uri) { | |
var md5 = crypto.createHash('md5'); | |
var token_calc = md5.update(magic_key + uri + ts).digest('hex'); | |
// token mismatch or ts expired, invalid request | |
if( token_calc !== token || Date.now()/1000 > parseInt(ts) + time_delta){ | |
return false; | |
} | |
else | |
{ | |
return true; | |
} | |
}; | |
function handler(event) { | |
var request_ip = event.viewer.ip; | |
var request = event.request; | |
// ignore auth for prefetching request | |
if (request_ip === '127.0.0.1') { | |
// block previously cached prefetch urls | |
if (request.querystring.token){ | |
return response403; | |
} | |
else { | |
return request; | |
} | |
} | |
// If no token, then generate HTTP 403 response. | |
if(!request.querystring.token || !request.querystring.ts) { | |
console.log("Error: No token or ts in the querystring"); | |
return response403; | |
} | |
var token = request.querystring.token.value; | |
var ts = request.querystring.ts.value; | |
// If no token, then generate HTTP 403 response. | |
if(!token || !ts){ | |
return response403; | |
} | |
var uri = request.uri; | |
// invalid token, return 403 response | |
if (!is_valid_qs(token, ts, uri)){ | |
return response403; | |
} | |
return request; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
加盐+文件名+时间戳 取 md5实现CloudFront url防盗链。