Jatin verma
Jatin verma

Reputation: 71

How to logout with JWT

I am using JWT for authentication and authorization. But I don't know what to write in logout route. I have searched a lot but could not get what to fill in logout route. This is my code. Please help.

const jwt=require("jsonwebtoken");
const jwtKey="My_admin_is_safe";
app.get('/admin',(req,res)=>{
res.render('LoginAdmin',{erru:"",errp:""});
 });

 app.post('/admin/login',(req,res)=>{
  Admin.findOne({username:req.body.id},(function(err,result){
    if(!result)
        res.render('LoginAdmin',{erru:"Username not found",errp:""});
    else if(!passwordHash.verify(req.body.password,result.password))
        res.render('LoginAdmin',{erru:"",errp:"Incorrect Password"});
    else 
        {   const user=result.username;
            const token = jwt.sign({ user }, jwtKey, {
            algorithm: "HS256",
            })
            console.log("token:", token);

     // set the cookie as the token string, with a similar max age as the token
     // here, the max age is in milliseconds, so we multiply by 1000
                res.cookie("token", token);
                res.render('Main');
           }
           }))
           });

Upvotes: 0

Views: 1635

Answers (1)

Luca Mattia Ferrari
Luca Mattia Ferrari

Reputation: 357

First of all, if I got your code right, I'm not seeing any signature mechanism applied to the JWT, which in general is considered best practice.

As you said correctly, you couldn't find any example of JWT logout because in fact there isn't any: once a valid JWT is handed to the client, it is considered valid for all the established TTL. What you can do though, is adding some stateful logic to JWT token and memorize those in a Key-Value database (like Redis) and start building a blacklist and whitelist of published token. So that when you receive a request with a token you also verify if this hasn't been blacklisted before authorizing the client.

Upvotes: 1

Related Questions