Skip to content

Instantly share code, notes, and snippets.

@ensean
Created July 10, 2023 07:01
Show Gist options
  • Save ensean/a814ac2cdbe0eaa0af536b7d3883f21e to your computer and use it in GitHub Desktop.
Save ensean/a814ac2cdbe0eaa0af536b7d3883f21e to your computer and use it in GitHub Desktop.
cloudfront function for request auth
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;
}
@ensean
Copy link
Author

ensean commented Jul 10, 2023

加盐+文件名+时间戳 取 md5实现CloudFront url防盗链。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment