DZone
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
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
  1. DZone
  2. Software Design and Architecture
  3. Security
  4. 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 · Tutorial
Like (0)
Save
Tweet
Share
5.53K 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

  • Top 10 Best Practices for Web Application Testing
  • When to Choose Redpanda Instead of Apache Kafka
  • [DZone Survey] Share Your Expertise and Take our 2023 Web, Mobile, and Low-Code Apps Survey
  • Comparing Map.of() and New HashMap() in Java

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • 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: