-
-
Notifications
You must be signed in to change notification settings - Fork 25
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
* add example * use timingSafeEqual
- Loading branch information
Showing
1 changed file
with
47 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,47 @@ | ||
'use strict' | ||
|
||
const fastify = require('fastify')() | ||
const crypto = require('crypto') | ||
const authenticate = { realm: 'Westeros' } | ||
|
||
const validUsername = 'Tyrion' | ||
const validPassword = 'wine' | ||
|
||
fastify.register(require('..'), { validate, authenticate }) | ||
|
||
// perform constant-time comparison to prevent timing attacks | ||
function compare (a, b) { | ||
a = Buffer.from(a) | ||
b = Buffer.from(b) | ||
if (a.length !== b.length) { | ||
// Delay return with cryptographically secure timing check. | ||
crypto.timingSafeEqual(a, a) | ||
return false | ||
} | ||
|
||
return crypto.timingSafeEqual(a, b) | ||
} | ||
|
||
// `this` inside validate is `fastify` | ||
function validate (username, password, req, reply, done) { | ||
let result = true | ||
result = compare(username, validUsername) && result | ||
result = compare(password, validPassword) && result | ||
if (result) { | ||
done() | ||
} else { | ||
done(new Error('Winter is coming')) | ||
} | ||
} | ||
|
||
fastify.after(() => { | ||
fastify.addHook('onRequest', fastify.basicAuth) | ||
|
||
fastify.get('/', (req, reply) => { | ||
reply.send({ hello: 'world' }) | ||
}) | ||
}) | ||
|
||
const basicAuthCredentials = Buffer.from(`${validUsername}:${validPassword}`).toString('base64') | ||
console.log(`curl -H "authorization: Basic ${basicAuthCredentials}" http://localhost:3000`) | ||
fastify.listen({ port: 3000 }) |