Authenticate incoming requests in AdonisJs

Here, we are going to see how to authenticate incoming PUT / PATCH / DELETE / GET requests in AdonisJs?
Submitted by Radib Kar, on February 14, 2021

With context to our todo app,

Each of the GET / PUT / PATCH / REQUEST for the project model has to have an authentication token included in its header. Because a project can only belong to a user. Thus when a request is incoming, it must hold something to prove that it belongs to a user. That's why we collected the jwt token for each logged in/ registered user. This jwt tokens would be sent in the header for each request from the collection.

Thus in the controller to we need to have support to authenticate the incoming request.

We can find the user out of the request via auth.

"auth" has a dedicated method to find user which is getUser().

const user = await auth.getUser();

So, add the above in each of the controller methods,

index(), store(), show(), update, delete()

And log this user to see whether you are getting correct user or not.

Below is an example, where I have sent post request for a user. I have included jwt token for this user in the header of the request.

authenticate incoming requests (1)

Here, you can see I have included Authorization in the header and the value is {{auth}} which is nothing but an environment variable stored in postman with value same as jwt token of a registered user.

authenticate incoming requests (2)

Upon sending the POST request below is the output where you can see the user object is printed in the console.

authenticate incoming requests (3)

Please test for all other methods as well with different users.

Now say we are sending GET/:id or PATCH or DELETE request for the project.

Here, we need to check whether the project belongs to the user sending this request.

So, first find the user via auth same way and then grab the project from its id. check whether project.user_id is same as user; is or not.

const user = await auth.getUser();

const project = await Project.find(id);

if(!project){
return response.status(404).json({
message: 'resource not found'
});
}
else if (project.user_id !== user.id) {
return response.status(403).json({
message: 'forbidden access'
});
}

We will test this in our future articles, where we will have our database ready with the project. Till now we haven't created any instance in the database, in our next article, we will create a project for a user.

Comments and Discussions!

Load comments ↻





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