Exercise 21: Implementing Authorization

In this exercise, we are going to refine our API to make sure that users are only authorized to access their todos and todo items:

  1. Let's first fix the flaw that we came across in Exercise 20: Adding User Authentication, step 12. So, we will modify the GET: /todo/<id> item route object in /routes/todo.js, by first checking if the todo belongs to the user before they can access its items:
{
method: 'GET',
path: '/todo/{id}/item',
handler: async (request, reply) =>
{
const todoId = request.params.id;
...
return reply(items);
},
},

You can find the complete code from the todo.js file at Code/Lesson-3/exercise-b/routes.
  1. Now, when we go back to access GET: /todo/1/item, we get the right error message:
  1. You can add extra authorization logic for the following routes:
    • POST: /todo/<id>/item, to make sure that a user cannot add items to a todo that does not belong to them.
    • PATCH: /todo/<id>, that a user cannot patch a todo that does not belong to them.
    • PATCH: /todo/<todoId>/item/<id>, that a user cannot patch a todo item that does not belong to them.
    • DELETE: /todo/<id>, that a user cannot delete a todo that does not belong to them.
    • DELETE: /todo/<todoId>/item/<id>, that a user cannot patch a todo item that does not belong to them.

Cross-Origin Resource Sharing (CORS) is a mechanism that uses additional HTTP headers to let a user agent (browser) gain permission to access selected resources from a server on a different origin (domain) than the site currently in use. For instance, when you are hosting a web application frontend on another domain, because of browser restriction, you will not be able to access the API.
We therefore need to explicitly state that our API will allow cross-origin requests. We will modify the server.js file, at the place we were initializing the server connection, to enable CORS:

server.connection(
{
host: 'localhost',
port: process.argv[2] || 8000,
routes:
{
cors: true,
}
});
..................Content has been hidden....................

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