Hapi Auth with JSON Web Tokens (JWT)
The simplest authentication scheme/plugin for
Hapi.js apps using JSON Web Tokens.

This node.js module (Hapi plugin) lets you use JSON Web Tokens (JWTs)
for authentication in your Hapi.js
web application.
If you are totally new to JWTs, we wrote an introductory post explaining
the concepts & benefits: https://github.com/docdis/learn-json-web-tokens
If you (or anyone on your team) are unfamiliar with Hapi.js we have a
quick guide for that too: https://github.com/nelsonic/learn-hapi
Usage
We have tried to make this plugin a user (developer) friendly as possible,
but if anything is unclear,
please submit any questions as issues on GitHub:
https://github.com/ideaq/hapi-auth-jwt2/issues
Install from NPM
npm install hapi-auth-jwt2 --save
Example
This basic usage example should get started:
var Hapi = require('hapi');
var people = {
1: {
id: 1,
name: 'Jen Jones'
}
};
var validate = function (decoded, request, callback) {
if (!people[decoded.id]) {
return callback(null, false);
}
else {
return callback(null, true);
}
};
var server = new Hapi.Server();
server.connection({ port: 8000 });
server.register(require('hapi-auth-jwt2'), function (err) {
if(err){
console.log(err);
}
server.auth.strategy('jwt', 'jwt', true,
{ key: 'NeverShareYourSecret',
validateFunc: validate
});
server.route([
{
method: "GET", path: "/", config: { auth: false },
handler: function(request, reply) {
reply({text: 'Token not required'});
}
},
{
method: 'GET', path: '/restricted', config: { auth: 'jwt' },
handler: function(request, reply) {
reply({text: 'You used a Token!'})
.header("Authorization", request.headers.authorization);
}
}
]);
});
server.start();
Run the server with: node example/server.js
Now use curl to access the two routes:
No Token Required
curl -v http://localhost:8000/
Token Required
Try to access the /restricted content without supplying a Token
(expect to see a 401 error):
curl -v http://localhost:8000/restricted
Now access the url using the following format:
curl -H "Authorization: <TOKEN>" http://localhost:8000/restricted
A here's a valid token you can use (copy-paste this command):
curl -v -H "Authorization: eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6MSwibmFtZSI6IkFudGhvbnkgVmFsaWQgVXNlciIsImlhdCI6MTQyNTQ3MzUzNX0.KA68l60mjiC8EXaC2odnjFwdIDxE__iDu5RwLdN1F2A" \
http://localhost:8000/restricted
That's it.
Write your own validateFunc
with what ever checks you want to perform
on the decoded token before allowing the visitor to proceed.
Real World Example ?
If you would like to see a "real world example" of this plugin in use
in a production web app (API)
please see: https://github.com/ideaq/time/tree/master/api/lib
If you have any questions on this please post an issue/question on GitHub:
https://github.com/ideaq/hapi-auth-jwt2/issues
(we are here to help get you started on your journey to hapiness!)
Documentation
validateFunc
- (required) a the function which is run once the Token has been decoded
signature function(decoded, request, callback)
where:
decoded
- (required) is the decoded JWT received from the client in request.headers.authorizationrequest
- (required) is the original request received from the clientcallback
- (required) a callback function with the signature function(err, isValid)
where:
err
- an internal error.valid
- true
if the JWT was valid, otherwise false
.
verifyOptions let you define how to Verify the Tokens (Optional)
While registering the hapi-auth-jwt2 plugin you can define
the following verifyOptions:
ignoreExpiration
- ignore expired tokensaudience
- do not enforce token audienceissuer
- do not require the issuer to be valid
example:
server.auth.strategy('jwt', 'jwt', true,
{ key: 'NeverShareYourSecret',
validateFunc: validate,
verifyOptions: { ignoreExpiration: true }
});
Read more about this at: jsonwebtoken verify options
If you prefer not to use any of these verifyOptions simply
do not set them when registering the plugin with your app;
they are all optional.
This feature was requested in: issues/29
Frequently Asked Questions (FAQ)
- Do I need to include jsonwebtoken in my project? asked in hapi-auth-jwt2/issues/32
Q: Must I include the jsonwebtoken package in my project
[given that hapi-auth-jwt2 plugin already includes it] ?
A: Yes, you need to manually install the jsonwebtoken
node module from NPM with npm install jsonwebtoken --save
if you want to sign JWTs in your app.
Even though hapi-auth-jwt2 includes it
as a dependency your app does not know where to find it in the node_modules tree for your project.
unless you include it via relative path e.g:
var JWT = require('./node_modules/hapi-auth-jwt2/node_modules/jsonwebtoken');
we recommend including it in your package.json explicitly as a dependency for your project.
If you have a question, please post an issue/question on GitHub:
https://github.com/ideaq/hapi-auth-jwt2/issues
Motivation
While making Time we want to ensure
our app (and API) is as simple as possible to use.
This lead us to using JSON Web Tokens for Stateless Authentication.
We did a extensive research
into existing modules that might solve our problem; there are many on NPM:

but they were invariably too complicated, poorly documented and
had useless (non-real-world) "examples"!
Also, none of the existing modules exposed the request object
to the validateFunc which we thought might be handy.
So we decided to write our own module addressing all these issues.
Don't take our word for it, do your own homework and decide which module you prefer.
Guiding Principal
"perfection is attained not when there is nothing more to add,
but when there is nothing more to remove" ~
Antoine de Saint-Exupéry
Why hapi-auth-jwt2 ?
The name we wanted was taken.
Think of our module as the "new, simplified and actively maintained version"
Useful Links
For more background on JWT see our post:
https://github.com/docdis/learn-json-web-tokens
Hapi.js Auth
We borrowed code from the following: