Home > Software design >  User is not authenticated jswtoken
User is not authenticated jswtoken

Time:01-09

I have created a login page and a about page the user will only access the about page if the user is logged in. I am trying to authenticate the user by using the tokens generated while signing in, but the token is not getting authenticated even after signing in with the correct credentials. I don't know what is the problem?

This is code to my sign-in and token generating method

const express = require("express");
const { default: mongoose } = require("mongoose");
const router = express.Router();
const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");
require("../db/conn");
const User = require("../model/userSchema");
const cookieParser = require('cookie-parser');
const Authenticate = require("../middleware/authenticate");

router.use(cookieParser());

  //LOgin route
  router.post("/signin", (req, res)=>{
    if(!req.body.email || !req.body.password){
      return res.status(400).json({error: "Plz fill the required data"});
   }else{
    bcrypt.hash(req.body.password, 12, function (err, hash) { 
      User.findOne({email: req.body.email}, function (err, foundUser) {
        if(err){
          console.log(err);
        }else{
          if(foundUser){
            bcrypt.compare(req.body.password, foundUser.password, function (err, result) {
                  if(result){
                    return res.json({message: "successfully log in"})
                  }else{
                    return res.json({message: "incorrect password"});
                  }
              });
              const email = req.body.email;
              const token = jwt.sign(
                { user_id: foundUser._id, email },
                process.env.TOKEN_KEY,
                {
                  expiresIn: "720h",
                }
              );
              foundUser.tokens = foundUser.tokens.concat({token: token});
              foundUser.save();
              
              // res.status(200).json(foundUser);
              console.log(foundUser);
          }else{
            return res.status(400).json({message: "user not found"});
          };
        }
      })
    })
  }
  });

  //about us page
  router.get("/about", Authenticate, function (req, res) {
    console.log("about running");
    res.send(req.rootUser);
  });

module.exports = router;

this is the code to authenticate the user

require("dotenv").config({path: "./config.env"});  
const jwt = require("jsonwebtoken");
const User = require("../model/userSchema");



const Authenticate = async(req, res, next) =>{
    try {
        const token = req.cookies.jwtoken;
        const verifyToken = jwt.verify(token, process.env.TOKEN_KEY);
        const rootUser = await User.findOne({ _id: verifyToken._id, "tokens.token": token});
        if(!rootUser) {
            throw new Error("User not found")
        }
        req.token = token;
        req.rootUser = rootUser;
        req.userID = rootUser._id;
        next();
    } catch (err) {
        console.log(err);
        return res.status(401).send("Unauthorized: No token provided");
    }

}

module.exports = Authenticate;

This is react based code of: About-page to display it or not based on user's authenticity.

 const navigate = useNavigate();
    const callAboutPage = async() =>{
        try {
            const res = await fetch("/about",{
                method: "GET",
                headers: {
                    Accept: "application/json",
                    "Content-Type" : "application/json"

                },
                credentials: "include"
            });
            const data = await res.json();
            console.log(data);
            if(!res.status === 200){
                const error = new Error(res.error);
                throw error;
            }

        } catch (err) {
            console.log(err);
            navigate("/login");
        } 
    }

CodePudding user response:

router.use(cookieParser());

Try to use cookieParser with app.use instead. (app from express instense) Expample:

const app = express();
app.use(cookieParser());

and try to put it before server listening in index.js or app.js file. Hope it help.

CodePudding user response:

As said in the comment looks like there is a issue on the process for setting up the jwtoken, and when you sign in, you just need to find the user and compare the password, there is no need to do the hash with Bcrypt, since you're not registing new user, for example, i will use Async/await instead of callback function, in order for you to read it much more easier:

//Login route
router.post("/signin", async (req, res)=> {
        const { reqEmail, reqPassword } = req.body; //destructuring so less thing to write at the next step
    if(!reqEmail || !reqPassword) {
        return res.status(400).json({message: "Plz fill the required data"});
    } 
    try {
        const foundUser = await User.findOne({email: reqEmail})
            if(!foundUser) {
                return res.status(400).json({message: "Wrong username or password!"})
            }
        const result = await bcrypt.compare(reqPassword, foundUser.password);
            if(!result){
                return res.json({message: "Wrong username or password!"})
            } else {
               const accessToken = jwt.sign(
                    { user_id: foundUser._id, email: foundUser.email},
                     process.env.TOKEN_KEY,
                    { expiresIn: "720h",}
               );

 // I am confuse what are you trying to do here, in your place I would set up on the cookie since you do that on your authentification.
                res.cookie("jwt", accessToken, {
                    maxAge: 60000,  // 60 sec for testing
                    httpOnly: true,
                    sameSite: false,  //false only for dev
                    secure: false,   //false only for dev
                })
                res.status(200).json(foundUser);
            };
    } catch (error) {
        return res.status(500).json({message: `${error}`})
    }

Than the authentification middleware :

// ...
const Authenticate = (req, res, next) => {
    const accessToken = req.cookies.jwt

    if(!accessToken) {
        return res.status(401).json({error: "Unauthorized: No token provided"});
    }
        try {
            const user = jwt.verify(accessToken, process.env.TOKEN_KEY)
            if(user) {
                req.user = user
                return next();
            }
        } catch (error) {
            return res.status(403).json({error: "Forbidden token error"})
        }
} 
  • Related