Middlewares and Auth Middleware in AdonisJs

Here, we are going to learn about the Middlewares and Auth Middleware in AdonisJs.
Submitted by Radib Kar, on January 26, 2021

In our last tutorial, we created the controller boilerplate and checked out the different standard functions to handle the incoming requests. In this article, we are going to see a new concept named middleware and usage of authentication through middleware.

Let's first get to know what is middleware?

Middlewares are something that hooks into the lifecycle of a request you are sending. There will be a couple of steps that will be executed in sequence & the request life cycle ahs to go through that if middlewares are used.

You can create your middleware and you can register that. I am not going deep into that since that's not at the basic level. Rather we will be talking about 'auth' middleware, which we will use throughout our implementation to implement authorization.

Types of Middleware

Middleware can be of three types

  1. server
  2. global
  3. Named

'auth' is a named middleware & if you want to use auth middleware for any request, then you need to mention that at your route.js file.

If you have followed my past tutorials you should have already created the route.js file to steer the requests of project & task

So, if we want to include auth middleware in the life cycle of the requests, we need to append ".middleware('auth')" for each one.

Route.get('projects', 'ProjectController.index').middleware('auth');
Route.put('projects', 'ProjectController.store').middleware('auth');
Route.get('projects/:id', 'ProjectController.show').middleware('auth');
Route.post('projects/:id', 'ProjectController.update').middleware('auth');
Route.delete('projects/:id', 'ProjectController.destroy').middleware('auth');

In this way, all requests from your project endpoints have to go through the auth middleware.

Now let's come to the points why do we need to add auth middleware?

The answer is to add authorization. Now, what is authorization? On simple language authorization means access. Say a project belongs to some particular user. While sending request for that project, we have to check that the current user who is sending request has authorization for the project or authorization to send the request. Otherwise, anybody will access any project from the database without any authorization. So in case of such case, we need to handle that and need to send back an appropriate response like 'forbidden access'

Now to implement all these features we will be using auth middleware.

That's it for this tutorial, from the next tutorial we will be using auth middleware while handling requests.

Comments and Discussions!

Load comments ↻

Copyright © 2024 www.includehelp.com. All rights reserved.