DZone
Web Dev Zone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
  • Refcardz
  • Trend Reports
  • Webinars
  • Zones
  • |
    • Agile
    • AI
    • Big Data
    • Cloud
    • Database
    • DevOps
    • Integration
    • IoT
    • Java
    • Microservices
    • Open Source
    • Performance
    • Security
    • Web Dev
DZone > Web Dev Zone > Enabling JWT Authentication for Plugin Routes in HapiJS APIs

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.

Abishek Baskaran user avatar by
Abishek Baskaran
·
Nov. 12, 16 · Web Dev Zone · Tutorial
Like (0)
Save
Tweet
5.38K Views

Join the DZone community and get the full member experience.

Join For Free

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}`);
});
JWT (JSON Web Token) authentication

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

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • What Is Kafka? Everything You Need to Know
  • Which Backend Frameworks Are Impacting Web App Development Immensely?
  • Open Source Monitoring and Metrics Landscape
  • Monolith vs Microservices Architecture: To Split or Not to Split?

Comments

Web Dev Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • MVB Program
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends:

DZone.com is powered by 

AnswerHub logo