How to handle JWT token on the client site in Node.js application?

Viewed 2245

I am implementing JWT tokens for authentication.

I am not using any client-site framework like Angular or React. It is just EJS.

Step 1. I have an API developed that on successful login returns the token as shown on the picture below(I am using Postman for testing API):

API response with JSON

Step 2. I am then accessing the restricted route and passing along the Authorization header with token value, by inputing it manually in the Postman and it works just fine.

My question is WHERE and HOW do I save the returned token from the step 1 on the client, so that it is sent in the header on step 2.

I am novice to web-development and following the tutorials, but all the tutorials I found about implementing the JWT token are written for Angular or React when it comes to the client site.

Any help would be greatly appreciated.

Thank you!

2 Answers

First you must create the token with JWT :

const token=jwt.sign({
                userId: user._id
                },config.secret, {expiresIn: '24h'});
                res.json({success:true,message:'Success', token:token, user: {username:user.username}});

Then in your front youcan save it into the localStorage

This will generate a unique key that you can implement in your header

After that in your routes when you want to check if there's a JWT in the header just make :

router.use((req,res,next)=>{
        const token=req.headers['authorization'];
        if(!token){
            res.json({success:false, message:"No token provided"});
        }
        else{
            jwt.verify(token, config.secret, (err,decoded)=>{
                if(err){
                    res.json({success:false,message:"Token invalid: " + err});
                }
                else{
                    req.decoded=decoded;
                    next();
                }
            });
        }
    });

This is a middleware that will check if there's a JWT key in "authorization" header

Note that every route coming after this one are going to run this middleware.

Here You 'll find every details about JSON Web Tokens

EDIT

Here's how you could do with an AJAX request:

$("submit").click(function(){

    $.ajax({
       url : 'api/login,',
       type : 'POST',
       data : {login: $('#login').val(),password:$('#password').val()}
       dataType : 'JSON',
       success : function(data, statut){
           localStorage.setItem('token',data.token) // assuming you send a json token
       },

       error : function(resultat, statut, erreur){
         // whatever code you want
       },

       complete : function(resultat, statut){

       }

    });

});

Have an object where you store the token, if you want to keep the token after the user leaves so that he will remain connected as long as the token is valid, you can save it in the localStorage.

And when doing AJAX requests on client side, retrieve the token from your object of from localStorage and set the token in the Authorization header.

Related