How to work with JWT authentication header in Adonisjs?

Asked

Viewed 650 times

0

To get to the point, I want to know how to work correctly with JWT on Adonisjs (I’m learning to use the framework and I’ve never worked with JWT before). My problem now is that I don’t want to keep picking up the Bearer Token generated there in my Postman and setting it in the header so I can access my routes that need authentication. So, I first need to understand how I pass the token to the header directly to test in the browser. I’m doing it today, but I don’t know if it’s right:

"use strict";

class SessionController {
  async authenticate({ request, auth, response }) {
    const { email, password } = request.all();

    const token = await auth.attempt(email, password);

    response.response.setHeader("Authorization", `Bearer ${token.token}`);
  }
}

module.exports = SessionController;

In the above example I already have the user registered in the database, only Gero for him the token. I want this token to be persisted in the browser, I do not know if I am being clear on this, the idea is that from the answer of this function above, it can already access the routes that require authentication.

below the user input controller:

"use strict";

const User = use("App/Models/User");

class UserController {
  async register({ request }) {
    const data = request.only(["username", "password", "email"]);

    const user = await User.create(data);

    return user;
  }
}
module.exports = UserController;

now, at last, my routes:

"use strict";

/** @type {typeof import('@adonisjs/framework/src/Route/Manager')} */
const Route = use("Route");

Route.post("/register", "UserController.register");
Route.post("/authenticate", "SessionController.authenticate");
Route.post("/test", "WorkerController.store").middleware(["auth"]);

As you can see, I have a TEST route that calls the store function of the Worker class, I will show it, but I already say that this route is basically to see if the authentication is passing... ie, if after I authenticate there on my route /authenticate, i can already access the /test by the browser (hence the need to leave the authorization header persisted in the browser)

"use strict";

class WorkerController {
  async store({ request, response, auth }) {
    console.log(auth.user.email);
  }
}

module.exports = WorkerController;

  • The authentication middleware is clear in what it does: it will only let you access the routes if you have the header authorization with a valid token. You want to change this behavior?

  • Good night Luiz, in the browser, after I do a post on the authentication route, he returns me the header with Authorization: bearer + token, only if I try to already hit a /test in the url, it returns 401 unauthorized

  • that wouldn’t already be my valid token?

  • It returns 401 because you probably didn’t set the header Authorization: Bearer <token> in his request to the server. Read more about this on documentation. You should always set this header in your request. Using tools like Postman, for example, you have a "header" section to insert this data.

  • The documentation just says you should do this, it doesn’t show how, maybe that’s the problem. Can you show me how I would do that?! I don’t want to keep putting this in Postman, I said in the question introduction. I’d like to understand how to do this directly through the browser.

  • "My problem now is that I don’t want to keep picking up the Bearer Token generated there in my Postman and setting it in the header so I can access my routes that need authentication. So, I first need to understand how I pass the token to the header directly to test in the browser."

  • If you are using Postman, you will always have to do this manually. I don’t know how to automate this process.

  • The idea is just to make a login system? In case, an API to be consumed in a frontend?

  • Yes, Victor... I am making the api to consume in React js/ React Native. Agree with me that I have no way to manually set header authorization when consuming? know how to help me?

Show 4 more comments

2 answers

1

The Bearer Authentication (means authentication to the Bearer):

Bearer authentication (also called authentication by token) is an authentication scheme HTTP that involves tokens so-called security tokens bearer. The name "bearer authentication" may be understood as "giving access to the bearer of that token". The token carrier is a cryptic string, usually generated by the server in response to a login request. The client must send this token in the header Authorization when making requests for protected resources.

Soon, clarified on the Bearer and taking into consideration that you know how the JWT, let’s ask your questions:

"My problem now is that I don’t want to keep picking up the Bearer Token generated there in my Postman and setting it in the header so I can access my routes that need authentication."

R: The Technology of JWT and Bearer Authentication is quite clear about this. Briefly it is necessary that you possess the Token authentication received from the JWT, and even more necessary that you spend the same on header (header) Authorization prefixed Bearer, thus: Authorization: Bearer <token>.

So with this, it’s extremely important that you contain the token authentication JWT and spend the same on header (header) to be able to access your routes among other resources that require it.

So I need to first understand how I pass the token to the header directly to test in the browser.

R: It usually occurs as follows, using a simple login example. Having the following pages:

  • Login
  • Authentication
  • Index

When entering the "login" page the user will make a request to the server with its data (username, password, etc), but this request is made on the "authentication" page. Soon afterwards if those data are true (ai depends on your logic), will be forwarded as a response token user (remembering that it will come from the "authentication" page), as soon as you receive the token, you should forward a request with it in the header to the "index page".

As I said, it all depends on your logic and how it is in your backend, for example.. Above I gave an example of getting the token from the backend, manipulating it on the frontend in conjunction with your backend, but you could manipulate it right from your backend.

  • Good night, Thiago! I can generate my token normally, adonisjs helps me a lot in this. My problem is really the code to pass the token to the header, which function to use in Adonis, this is not clear in the documentation. I tried Response.Headers() and nothing... Sponse.response.header(), no way I can pass the blessed to the header...

0

If by chance someone has this same question as me, below follows the code I used to set the Authorization + token in the header, and then capture the data of the token user:

setting the header:

"use strict";

class SessionController {
  async authenticate({ request, auth, response }) {
    try {
      const { email, password } = request.all();
      const token = await auth.attempt(email, password);

      if (token) {
        return response.response.setHeader(
          "Authorization",
          `Bearer ${token.token}`
        );
      }
    } catch (error) {
      console.log("email ou senha inválidos");
    }
  }
}

module.exports = SessionController;

picking up data (writing email on console and returning id)

"use strict";

class WorkerController {
  async store({ request, response, auth }) {
    console.log(auth.user.email);

    const id = auth.user.id;

    return id;
  }
}

module.exports = WorkerController;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.