Ala Eddine Menai
Ala Eddine Menai

Reputation: 2870

How to send/extract JWT token in nodejs with passport-jwt?

I've tried to check if they're online examples of how to use JWT extractors to get the token from the request but I failed to understand how to send the token with the request after the user logins.

When I use Postman, there's a tab called Authorization where I can choose the type Bearer Token which enabled me to add the token with the Authorization and the request http://localhost:5000/profile went successfully.

However, the browser stills showing me only Unauthorized when I try to access the profile http://localhost:5000/profile after successful login.

POSTMAN SCREEN-SHOT:

POSTMAN-SCREENSHOT

BROWSER SCREEN-SHOT:

BROWSER-SCREENSHOT

I've followed the passpot-jwt documentation configuration:


passport.use(
  new JWTStrategy(
    {
      jwtFromRequest: ExtractJWT.fromAuthHeaderAsBearerToken(),
      secretOrKey: "mysecret",
    },
    function (jwtPayload, done) {
      return User.findOne({ username: jwtPayload.username })
        .then((user) => {
          return done(null, user);
        })
        .catch((err) => {
          return done(err);
        });
    }
  )
);

And my login route looks like :

Router.post("/", (req, res, next) => {
  passport.authenticate("local", { session: false }, (err, user, info) => {
    if (err) return next(err);
    if (!user) {
      return res.redirect("/login?info=" + info);
    }
    req.logIn(user, { session: false }, (err) => {
      if (err) return next(err);
      const token = jwt.sign({ username: user.username }, "mysecret");
      res.json({ user, token: `Bearer ${token}` });
    });
  })(req, res, next);
});

Upvotes: 1

Views: 2263

Answers (2)

Abhishek Aarya
Abhishek Aarya

Reputation: 51

After login, you can send Authorization Token in headers

(function () {
  fetch("http://localhost:5000/profile", {
    method: "GET",
    headers: {
      "Content-Type": "text/plain",
      "X-My-Custom-Header": "value-v",
      Authorization:
        "Bearer " + Token,
    },
  });
})();

Hope you got some idea.

Upvotes: 0

Ala Eddine Menai
Ala Eddine Menai

Reputation: 2870

The issue is:

I was trying to access the profile without adding the Authorization in the header from the server itself. The Authorization contains the generated token.

With Postman I was able to do that with the UI as explained above. However, in the code, I needed to create a middleware before accessing the profile route.

    app.use(
      "/profile",
      (req, res, next) => {
        req.headers.authorization = `Bearer ` + req.cookies["authentication-token"];
        next();
      },
      profileRouter
    );

Upvotes: 1

Related Questions