Home > Software design >  why do i need to check if the password has not been changed after the JWT is issued
why do i need to check if the password has not been changed after the JWT is issued

Time:12-21

I don't get it why do i need to check if the password has not been changed after the JWT is issued. I have a piece of code right here and i have to carry out authorization of user and i don't know why i have to check this issue. Could you explain me why do i need to do this ?

I tried to figure out of this but still i don't get it.

exports.protect = catchAsync(async (req,res,next)=>{
    let token;
    if(req.headers.authorization && req.headers.authorization.startsWith('Bearer')){
        token = req.headers.authorization.split(' ')[1];
    }
    
    if(!token){
        return next(new AppError('You are not log in , please log in to get the access!',401));
    }
    
   const decoded = await promisify(jwt.verify)(token, process.env.TOKEN_PASSWORD);
   
   const freshUser = await User.findById(decoded.id);
   if(!freshUser){
    return next(new AppError('The user belonging to this token does no longer exist',401));
   }

   if(freshUser.changedPasswordAfter(decoded.iat)){
    return next(new AppError('User recently changed the password, Please log in again',401)); 

   }  // <--- this piece is not understandable

   console.log(decoded);

   req.user = freshUser;

   next();
});
Schema.methods.changedPasswordAfter = function(JWTTimestamp)
{   
    if(this.passwordDateAt)
    {
        const changeTimeStamp = parseInt(this.passwordDateAt / 1000 , 10);

        return JWTTimestamp < changeTimeStamp;
    }
    return false;
}

CodePudding user response:

If the password has been changed, you generally don't want to allow any previously issued JWTs to be used because it's possible that the reason the password was changed is that the old password was compromised and thus the user is changing their password to prevent any access using the old password.

But, if you allow an existing JWT (from the old password) to still be used, then you won't be blocking use of that compromised password.

  • Related