Enabling JWT authentication for plugin routes in HapiJS APIs

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 – lets say 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}`);
});
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s