简体   繁体   中英

How to send and verify refresh token after expiration of jwt token without refreshing page

What I have to do: when the user logs in, the page should stay as it is, until and unless the user logs out

Problem: I have generated JWT token with expiry of 30 seconds. I get the access to secure page but after 30 seconds after refreshing the page gets closed because JWT expires. I have created a function for refresh token which produces and set cookie to JWT token, but how do I fire the endpoint automatically without touching URL bar or refresh button What I mean is the refresh token should keep setting new cookie JWT without hitting other endpoint of refresh button

I saw the tutorial related it but I am not using react so not useful. I am using handlebars

Controller code

const {Registeration}=require('../database/model');
const bcrypt=require('bcryptjs') ;
const jwt = require('jsonwebtoken');

exports.signUp=async(req,res)=>{
    const User=new Registeration();
    User.name=req.body.name,
    User.email=req.body.email
    if(req.body.password===req.body.confirmPassword){
        User.password=req.body.password;
    }
    else{
        throw new Error('ircorrect password');
    }
    try{
        await User.save();
        res.redirect('/login');
        // res.status(201).send({message:"usser data saved"});
    }
    catch(err){
        console.log(err); 
        res.send(err);
    }
}

exports.login=async(req,res)=>{
    const User=new Registeration();
    const userData=await Registeration.findOne({email:req.body.email});
    console.log(userData);
    // console.log("isMatcch = "+isMatch);
    if(userData==={}){
        res.status(404).send({message:"user not found"});
    }
    else{
        const isMatch=await bcrypt.compare(req.body.password,userData.password);
        if(!isMatch){
            res.status(400).send({message:"wrong password"}); 
        }
        else{
            const token=await userData.generateAuthToken()
            console.log(token);
            res.cookie("jwt",token,{
                path:'/',
                expires:new Date(Date.now()+1000*30),
                httpOnly:true,
                sameSite:"lax"
            });
            res.redirect('/user');
            // res.status(201).send({message:"user logged in",user:userData,token:token});
        }
    }
}
exports.verifyToken=async(req,res,next)=>{
    // const token=req.header('Authorization').replace('Bearer ','');
    const token =req.cookies.jwt;
    console.log(token);    
    const user=jwt.verify(token,"helloworld");
    if(!user){
        res.status(404).send({message:'invalid token'});
    }
    else{
        console.log(user)
        req.id=user._id
        // res.status(201).send({message:"token matched"});
    }
    next();
}
exports.getUser=async(req,res)=>{
    const user= await Registeration.findOne({_id:req.id});
    if(!user){
        res.status(404).send({message:"user not found"});
    }
    else{
        res.render('user',{
            data:user
        })
        // res.status(201).send({message:"user found",user:user});
    }
}
exports.refreshToken=async(req,res)=>{
    const token =req.cookies.jwt;
    if(!token){
        res.status(404).send({message:"couldnt find token"});
    }
    else{
        const user=jwt.verify(token,"helloworld");
    if(!user){
        res.status(404).send({message:'invalid token'});
    }
    else{
        res.clearCookie('jwt');
        req.cookie.jwt=" ";
        const token=jwt.sign({_id:user._id.toString()},'helloworld',{
            expiresIn:"30s"
        });
        res.cookie("jwt",token,{
            path:'/',
            expires:new Date(Date.now()+1000*30),
            httpOnly:true,
            sameSite:"lax"
        });
        req.id=user.id
        next();
    }
    }
}
exports.renderIndexPage=(req,res)=>{
    res.render('index');
}
exports.renderLoginPage=(req,res)=>{
    res.render('login');
}
exports.renderRegisterPage=(req,res)=>{
    res.render('register');
}

Routes

    const express=require('express');
const router=express.Router();
const {signUp, login, verifyToken, getUser, renderIndexPage,renderLoginPage,renderRegisterPage,refreshToken}=require('../controller/signup and login controller');
const cookieParser=require('cookie-parser');

router.use(express.urlencoded({extended: true}));
router.use(express.json())
router.use(cookieParser());

router.get('/',(req,res)=>{
    res.send('homepage');
})
router.post('/register/data/recorded',signUp);
router.post('/login/data/recorded',login);
router.get('/user',verifyToken,getUser);
router.get('/index',renderIndexPage);
router.get('/register',renderRegisterPage);
router.get('/login',renderLoginPage);
//router.get('/refresh',refreshToken,verifyToken,getUser);// not working showing error
module.exports=router

From my understanding of this question what you're describing is impossible.

The HTTP(S) communication is closed after the user logs in / registers, meaning your user is no longer connected to your server, and cannot fire another request handler.

WHAY YOU CAN DO HOWEVER is adding logic to your frontend code that does another request to to refresh the token (you do another request after a delay on page load & on login (presumably the delay in what time it is until the token expires))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM