An example webserver that uses HAWK authentication with Payload validation. The Auth Key is key and the Auth Id is user.
Last active
December 28, 2018 19:58
-
-
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.
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
| { | |
| "dependencies": { | |
| "hawk": "^7.0.10" | |
| } | |
| } |
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
| 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