After logging in with jwt and getting access to protected page and closing tab and opening new tab hitting protected endpnt am getting access to protected page

What my code should do : In login Page , after logging in I am getting access to protected page but after deleting current the tab and opening new tab and hitting endpoint of protected page I shouldn’t get access to that protected page

Problem or Issue : After logging in I am getting access to protected page ,but when I the close tab and opening new tab and hitting the endpoint of protected page I am getting access to protected page even the JWT is not stored in cookie , an the JWT of last logged in user is getting access in console

Code for validating credential and generating JWT when logging in :

    app.post('/login/recorded',async(req,res)=>{
    // const loginUser= new RegistrationModel();
    const findData=await RegisterationModel.findOne({email:req.body.email});
    try{
        console.log(findData);
        if(findData==={}){
            res.send("not found");
        }
        if(findData.email===req.body.email && findData.password===req.body.password){
            const token = await findData.generateAuthToken();
            res.cookie('jwt',token,{
                httpOnly:true // you cant delete manually
            });
            // console.log(`cookie : ${req.cookies.jwt}`);
            res.redirect('/index');
            console.log(token)
            // res.send("you are logged in");
        }
        else{
            res.send("invalid");
            
        }
    }
    catch(error){
        console.log(error);

    }
})

Code for authenticating the JWT when generated during logging and stored in cookie :

    const auth =async(req,res,next)=>{
    try{
        console.log("auth")
        // console.log(token);
    const token=req.cookies.jwt;
    const verifyUser=jwt.verify(token,'helloworld');
    const user=await RegisterationModel.findOne({_id:verifyUser._id});
    // console.log(user);
    console.log(verifyUser);
    res.cookie('jwt',' ',{maxAge:1});
    next();
    }
    catch(error){
        res.status(401).send(error);
        console.log(error)
    }
}

code for secret page route :

app.get('/secretpage',auth,(req,res)=>{
res.render('secret');

})

code for index .hbs

<html>
<head>
    <title>Index Filee</title>
</head>
<body>
    <ul>
        <li><a href="/secretpage">Secret Page</a></li>
        <li><a href="/login">Login</a></li>
        <li><a href="/register">Register</a></li>
        </ul>
</body>
</html>

After hitting the protected endpoint in new tab , the JWT token is not stored in cookie and getting token of last logged in user in console

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.