GD- Ganesh Deshmukh
GD- Ganesh Deshmukh

Reputation: 1554

Can't access protected routes in nodejs using bearer token through postman

I am trying to make get request to my protected routes using bearer token and it returns unautorized, even after sending token through header.

I am using bearer token on nodejs, expressjs app using mlab remote database I registered new user, then I logged with that email and it sent me back a token(as expected).

When I sent this token through header of other route without login it returns Unautorized.

my steps are

1) registered with new email

first I registered

2) login request successful

login request 2nd

3) failed get request to route localhost:5000/api/users/current, and returns Unautorized.

unautho

user.js file has

// users.js for authentication and authorization

const express = require("express");
const router = express.Router();
const gravatar = require("gravatar");
const bcrypt = require("bcryptjs");
const keys = require("../../config/keys");
const jwt = require("jsonwebtoken");
const passport = require("passport");

// Load User Model to check existing email is used for registration or not?
const User = require("../../models/User");

// @route       GET request to api/users/test
// @description Tests users route
// @access      Public, without login
router.get("/test", (req, res) => res.json({ msg: "Users Works" }));

// @route       GET request to api/users/register
// @description new registration of user.
// @access      Public, without login first register

router.post("/register", (req, res) => {
  User.findOne({ email: req.body.email }).then(user => {
    if (user) {
      return res.status(400).json({ email: "Email value exists already." });
    } else {
      console.log("no user found of this email in DB");
      const avatar = gravatar.url(req.body.email, {
        s: "200", //Size of gravatar in pixels
        r: "pg", //rating,
        d: "mm" //default value= 'mm'
      });
      // create user
      const newUser = new User({
        name: req.body.name,
        email: req.body.email,
        avatar,
        password: req.body.password
      });

      // gensalt(noOfSalts_of_Iterations,(err,salt_result)=>{})
      bcrypt.genSalt(10, (err, salt) => {
        // hash(plaintext,salt,callback(err,resultant ciphertext))
        bcrypt.hash(newUser.password, salt, (err, hash) => {
          if (err) {
            console.log("error in bcrypt.hash()");
            throw err;
          }
          //assign salted hash to password
          newUser.password = hash;

          // Save new password in datebase, overriding plaintext;
          newUser
            .save()
            .then(user => res.json(user)) // if yes,then send it as argument in brackets.
            .catch(err =>
              console.log("Error occured in saving hash password in DB\n")
            );
        });
      });
    }
  });
});

// @route       GET request to api/users/login
// @description Login/signing-in registered user. return JWT token
// @access      Public

router.post("/login", (req, res) => {
  const email = req.body.email;
  const password = req.body.password;

  // find user to match it's password
  User.findOne({ email: req.body.email }).then(user => {
    //check if no user
    if (!user) {
      return res.status(404).json({ email: "User's email   found." });
    }

    // else if do this..

    // if user's email-id is found then match it's password-hash with local-database
    bcrypt.compare(password, user.password).then(isMatch => {
      if (isMatch) {
        // user pswd matched => then return JWT token back for authentication
        // res.json({ msg: "Success" });
        const payload = { it: user.id, name: user.name, avatar: user.avatar };

        // created JWT token
        // now sign token
        // jwt.sign(payload, secretKey, expire-time, callback );

        // jwt.sign

        jwt.sign(
          payload,
          keys.secretOrKey,
          { expiresIn: 3600 },
          (err, token) => {
            res.json({
              success: true,
              token: "bearer " + token
            });
          }
        );
      } else {
        // pswd doesn't matched
        return res.status(400).json({ password: "Password didn't match" });
      }
    });
  });
});

// @route       GET request to api/users/current  - current user with token
// @description Return current user
// @access      Private, can't go without login

router.get(
  "/current",
  passport.authenticate("jwt", { session: false }),
  (req, res) => {
    res.json({ msg: "Success" });
  }
);

module.exports = router;

data is stored succesfully at remote db mlab, but I can't figureout what's problem. screenshot

my Github repo of this project is this

Upvotes: 0

Views: 1006

Answers (1)

Vipul Pandey
Vipul Pandey

Reputation: 1738

Please Look at the Line of your code Users.js Line 88 the payload id is stored in 'it'

const payload = { it: user.id, name: user.name, avatar: user.avatar };

But in your passport.js

User.findById(jwt_payload.id)

you are extracting it by id so if you use here jwt_payload.it the you will get message success

Upvotes: 1

Related Questions