Exercise 19: Securing All the Routes

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:

  1. 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.
  1. We will modify the routes array that we get from ./routes/todo.js in the server.js file:
    1. First, begin by requiring the installed hapi-auth-jwt at the top of the file:
const hapiAuthJwt = require('hapi-auth-jwt');
    1. 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.
  1. Now, try accessing any of the routes, for example, GET: /todo; you should get this:
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset