Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Enabling JWT Authentication for Plugin Routes in HapiJS APIs

DZone's Guide to

Enabling JWT Authentication for Plugin Routes in HapiJS APIs

Securing HapiJS routes is a pretty straight forward affair, but what happens if you need a route from a plugin? Read on to find out how to address this.

· Web Dev Zone
Free Resource

Get the senior executive’s handbook of important trends, tips, and strategies to compete and win in the digital economy.

If you are using securing your HapiJS APIs using JWT, below is the code snippet most tutorials suggest:

server.register([
{ register: require('hapi-auth-jwt') },
{ register: require('./routes/test-route') }
], 
(err) => {
            if (err) {
              console.error('Failed to load a plugin:', err);
            } else {
//For JWT 
server.auth.strategy('token', 'jwt', {
key: new Buffer(process.env.AUTH_CLIENT_SECRET,'base64'),
verifyOptions: {
algorithms:['HS256'],
audience: process.env.AUTH_CLIENT_ID
}
});

//For testing
server.route({
method: 'GET',
path: '/',
config: { auth: 'token' },
handler: function (request, reply) {
reply('API server running happi and secure!');
}
});
            }
        }
);

//Server start
server.start((err) => {
if (err) {
throw err;
}
console.log(`Server running at: ${server.info.uri}`);
});

In the GET / route, the config auth: ‘token’ specifies that the token JWT auth strategy should be applied.  However, a problem might arise when you want to include a route from a plugin. Let's say that a GET /test route needs to be added from ./routes/test-route.js. In the test-route.js, when I added config: {auth: ‘token’} under GET /test, Hapi complains Error: Unknown authentication strategy token in /test. This is because the auth strategy token is defined externally in server.js (if that’s your entry point).

The solution is to specify server.auth.default(‘token’); in your entry point or server.js. With this configuration, we don’t need to specify config: {auth: ‘token’} under each route. If we want to exclude a route from authenticating, we can specify config: {auth: false} under that route.

The solution looks like this:

server.register([
{ register: require('hapi-auth-jwt') },
{ register: require('./routes/test-route') }
], 
(err) => {
            if (err) {
              console.error('Failed to load a plugin:', err);
            } else {
//For JWT 
server.auth.strategy('token', 'jwt', {
key: new Buffer(process.env.AUTH_CLIENT_SECRET,'base64'),
verifyOptions: {
algorithms:['HS256'],
audience: process.env.AUTH_CLIENT_ID
}
});

//This enables auth for routes under plugins too.
server.auth.default('token');

//For testing - auth included by default
server.route({
method: 'GET',
path: '/',
handler: function (request, reply) {
reply('API server running hapi and secure!');
}
});

//For testing - auth excluded through config
server.route({
method: 'GET',
path: '/',
config: { auth: false },
handler: function (request, reply) {
reply('API server running hapi!');
}
});
            }
        }
);

//Server start
server.start((err) => {
if (err) {
throw err;
}
console.log(`Server running at: ${server.info.uri}`);
});

Read this guide to learn everything you need to know about RPA, and how it can help you manage and automate your processes.

Topics:
jwt ,apis ,web dev ,hapijs

Published at DZone with permission of Abishek Baskaran, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}