CoderLee
CoderLee

Reputation: 3469

How to get JWT token decoded from get request in node api

I'm sending JWT tokens accross requests for authorization, however I can't seem to get the token decode each time. It works with one method but not the other. The first snippet gives a "decoded" token result from the server side, however the second one doesn't.

public async getAllUsers(req: Request, res: Response) {
    try {
      const payload = req["decoded"]; // gives the token decoded
      if (payload) {
        let users: ILoginResult = await UserData.getAllUsers(payload);
        res.status(users.status).send(users.result);
      }
    } catch (e) {
      res.status(500).send({ error: e.toString() });
    }
  }
  public async getAccountDetails(req: Request, res: Response) {
    try {
      const user = req["decoded"]; // always undefined
      let details: IDetails = await AccountData.getAccountDetails(name);
      res.status(200).send(details);
    } catch (e) {
      let err = e.toString();
      res.status(500).send({ error: err });
    }
  }

The request from postman are included a bearer token which is provided at login and used throughout other parts of the app. Not sure why it works in the one but not the other. Would really appreciate if someone could better explain what's going on here and/or provide tips, advice, suggestions.

edit - adding request details

get request to: http://localhost:5000/api/v1/account with a token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyIjoiYWRtaW4iLCJpYXQiOjE1Nzc5OTUwMjUsImV4cCI6MTU3ODE2NzgyNSwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdCJ9.--msLba1VPs4Nv_B9YL6fk2DFHkQCgiVvDJFPt_UnDk

The decoded property was used in a tutorial I was following that seemed to be added from the server side but was poorly explained and I haven't found a good alternative/explanation. I don't think it has any middleware either. Very much open to alt methods.

Upvotes: 4

Views: 1133

Answers (1)

CoderLee
CoderLee

Reputation: 3469

Thanks to the suggestions from the comments I was able to find a missing piece in the route that creates the decoded property which is being used here. By adding the middleware to the router the request works as expected:

import express from "express";
import UserController from "../controllers/UserController";
import valid from "../utils/ValidateToken";

export default (router: express.Router) => {
  router
    .route("/users")
    .post(UserController.addUser)
    .get(valid.validateToken, UserController.getAllUsers);

  router.route("/login").post(UserController.loginUser);
  router.route("/account").get(valid.validateToken, UserController.getAccountDetails);
};

The valid.validateToken was missing which is the bit that generates the decoded object from the JWT being passed. Moral of the story, always double check everything. Thanks to all who commented/answered!

Upvotes: 2

Related Questions