Skip to content

Instantly share code, notes, and snippets.

@motyar
Last active March 6, 2022 07:53
Show Gist options
  • Save motyar/2f8e012ad187a76a1d78d3bb5f42fb63 to your computer and use it in GitHub Desktop.
Save motyar/2f8e012ad187a76a1d78d3bb5f42fb63 to your computer and use it in GitHub Desktop.
Signed url nodejs
var http, crypto, sharedSecret, query, signature;
http = require("http");
crypto = require("crypto");
sharedSecret = "super-secret";
query = "key=value";
signature = crypto.createHmac("sha256", sharedSecret).update(query).digest("hex");
http.get({
port: 1337,
path: "/?" + query,
headers: {
"X-Signature": signature
}
}, function (res) {
console.log(res.statusCode);
});
var http, url, crypto, sharedSecret;
http = require("http");
url = require("url");
crypto = require("crypto");
sharedSecret = "super-secret";
http.createServer(function (req, res) {
var retrievedSignature, parsedUrl, computedSignature;
// Deal with CORS.
res.setHeader("Access-Control-Allow-Origin", "*");
if (req.method === "OPTIONS") {
res.setHeader("Access-Control-Allow-Headers", "X-Signature");
res.writeHead(204);
res.end();
} else {
// Get signature.
retrievedSignature = req.headers["x-signature"];
// Recalculate signature.
parsedUrl = url.parse(req.url);
computedSignature = crypto.createHmac("sha256", sharedSecret).update(parsedUrl.query).digest("hex");
// Compare signatures.
if (computedSignature === retrievedSignature) {
res.writeHead(200, {
"Content-Type": "text/plain"
});
res.end("Hello World\n");
} else {
res.writeHead(403, {
"Content-Type": "text/plain"
});
res.end("Get Out\n");
}
}
}).listen(1337);
console.log("Server running on port 1337");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment