In this exercise, we're going to secure all the /todo/* routes that we created so that no unauthenticated user can access them. In the Exercise 21: Implementing Authorization, we will differentiate between an unauthenticated and an unauthorized user:
- We will first start by installing a Hapi.js plugin for JWT, hapi-auth-jwt. Go to the Terminal and run:
npm install hapi-auth-jwt --save
Use the Code/Lesson-3/exercise-b for your reference.
- We will modify the routes array that we get from ./routes/todo.js in the server.js file:
- First, begin by requiring the installed hapi-auth-jwt at the top of the file:
const hapiAuthJwt = require('hapi-auth-jwt');
-
- Then, replace the old line, server.route(routes.todo), with this:
server.register(hapiAuthJwt, (err) =>
{
server.auth.strategy('token', 'jwt',
{
key: 'secretkey-hash',
verifyOptions:
{
algorithms: [ 'HS256' ],
...
// add auth config on all routes
...
});
You can find the complete code from the server.js file at Code/Lesson-3/exercise-b.
- Now, try accessing any of the routes, for example, GET: /todo; you should get this: