Skip to content

Instantly share code, notes, and snippets.

@rpless
Last active December 28, 2018 19:58
Show Gist options
  • Select an option

  • Save rpless/2f1f215f5a638a331c736ec71d4c4844 to your computer and use it in GitHub Desktop.

Select an option

Save rpless/2f1f215f5a638a331c736ec71d4c4844 to your computer and use it in GitHub Desktop.
An example of a web server that uses HAWK authentication with Payload Validation.

An example webserver that uses HAWK authentication with Payload validation. The Auth Key is key and the Auth Id is user.

{
"dependencies": {
"hawk": "^7.0.10"
}
}
const Http = require('http');
const Hawk = require('hawk');
// Credentials lookup function
const credentialsFunc = (id) => ({ key: 'key', algorithm: 'sha256', user: 'user' });
// Create HTTP server
const getBody = async (req) => {
return new Promise((resolve, request) => {
let body = [];
req
.on('data', (chunk) => { body.push(chunk) })
.on('end', () => {
const foo = Buffer.concat(body).toString()
if (foo.length == 0) resolve(undefined);
else resolve(foo);
});
});
}
const handler = async function (req, res) {
// Authenticate incoming request
let payload, status;
let headers = { 'Content-Type': 'text/plain' };
try {
const body = await getBody(req)
const authenticated = await Hawk.server.authenticate(req, credentialsFunc, { payload: body });
const { credentials, artifacts } = authenticated;
payload = `Hello ${credentials.user} ${artifacts.ext}`;
status = 200;
const header = Hawk.server.header(credentials, artifacts, { payload, contentType: headers['Content-Type'] });
headers['Server-Authorization'] = header;
} catch (error) {
console.error(error)
payload = 'Womp womp!';
status = 401;
}
// Send the response back
res.writeHead(status, headers);
res.end(payload);
};
// Start server
Http.createServer(handler).listen(3000, 'localhost');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment