0

I'm testing an API on Postman. When the user logins, I sent a JWT as the response.

The payload consists of the UserID from the database.

const token = jwt.sign(
      {
        _id: user._id,
      },
      "jwtPrivateKey"
);
return res.status(200).json({ message: "Login Successful!", token: token });

Next when the user wants to fetch some data, I want to know which user is trying to fetch it.

How can I do that?

Karan Singh
  • 1,114
  • 1
  • 13
  • 30
  • https://stackoverflow.com/questions/38552003/how-to-decode-jwt-token-in-javascript-without-using-a-library#38552302 – codingwithmanny Jul 21 '20 at 19:36
  • I know how to decode, but what I cannot understand is how to send this information from the user. – Karan Singh Jul 21 '20 at 19:37
  • You need to somehow store the JWT on the client and when the user makes a request, include this information with it. There are multiple options to do this. Store it in browser's local storage (not exactly secure) and then include it in subsequent requests in an http header or as a query string parameter. Another option is to use cookie as a transport mechanism and store the JWT inside, that way the browser will automatically send the cookie (also, it is more secure if implemented correctly but has its own drawbacks) – Matus Dubrava Jul 21 '20 at 19:42
  • @MatusDubrava How can I do this on postman? – Karan Singh Jul 21 '20 at 19:43
  • Postman will automatically send back the cookie if it receives one, the same way browser does but you would first need to implement that logic on your backend (cookie creation etc...). If you just want to include it in a header then you can do it manually by inspecting the response that contains the JWT and copy it into authentication header which you can also create manually but then you will need to implement the corresponding header parsing on your backend as well. – Matus Dubrava Jul 21 '20 at 19:46
  • If it's not a cookie, you could store the token as a environment variable with postman. – codingwithmanny Jul 21 '20 at 21:07

0 Answers0