iLyas
iLyas

Reputation: 1091

How to implement JSON web token in client side - Node.js

I am working on a Node.js express application using JWT for authentication to access my admin page. I tested my routes with Postman and it works very well, the problem is in client side. I'll simplify my code and my question to make the question very clair.

My question is how can I get redirected to my admin page after the token has been stored locally with localStorage ?

I already try to solve this problem with ajax but the page still the same. I also tried window.location='/admin' but in this one I can't send a header that contain the token.

First my Server Side :

app.get('/admin', verifyToken, function(req, res, next) {
    res.render('views/admin');
});

function verifyToken(req, res, next) {
    var token = req.headers['access-token'];
    if (!token)
      return res.status(401).send({ auth: false, message: 'NO TOKEN PROVIDED' });        

      jwt.verify(token, config.secret_key, function(err, decoded) {
      if (err)
      return res.status(500).send({ auth: false, message: 'Failed to authenticate token.' });

      console.log("Token is valid");
      next();
    });
  }

Client Side :

function login(event) {
            event.preventDefault();
            let formData = new FormData(event.target);

            fetch("/admin/login", {
                    method: 'POST',
                    body: formData 
            }).then(function (response) {          
                    return response.json();
                }).then(function (result) {
                    if (result.auth === true) {
                        localStorage.token = result.token;
                    //HERE IS THE PROBLEM
                       $.ajax({ 
                         type : "GET", 
                         url : "/admin", 
                         beforeSend: function(xhr){
                        xhr.setRequestHeader('access-token', localStorage.token);
                                    },
                success : function(result) { 
                         //HERE IS THE PROBLEM                
                       window.location='/admin';
                         }
                        }); 
                    } else {
                        console.log("Incorrect username or password.");
                    }
                });       
        }

So how do I send the token in the headers like I did in Postman in client side and get redirected automatically, is there any method ? Many thanks.

Upvotes: 1

Views: 4584

Answers (3)

iLyas
iLyas

Reputation: 1091

I noticed that using this method isn't a good practice. In my example, making redirect in client side isn't good, it would be better to do it in server side and more than that I used less secure method with localStorage to store my token.

So I told myself why not to do the redirection in my server side and for this I used cookie-parser middleware to check if the cookie created contain my token, if it's true then make a redirection to admin page.

Cookie or localStorage are both not secure, but the cookie is a good option to store my token because web storage does not enforce any secure standards during transfer whether with HTTP or HTTPS.

My Server side

app.get('/admin', verifyToken, function(req, res,next) {
    res.render('views/admin');
});

app.get('/admin/login', function(req, res){
      if(req.cookies.myToken)//Make redirection
   return res.redirect('/admin');
    res.render('views/login');
});

function verifyToken(req, res, next) {
    var token = req.cookies.myToken;
    if (!token)
      return res.status(401).send({ auth: false, message: 'No Token Provided!'});

      jwt.verify(token, config.secret_key, function(err, decoded) {
      if (err)
      return res.status(500).send({ auth: false, message: 'Failed to authenticate token.' });
      req.userId = decoded.id;
      next();
    });
  }

Client side :

fetch("/admin/login", {
                    method: 'POST',
                    body: formData,
                    credentials: 'include',
            }).then(function (response) {
                    return response.json();
                }).then(function (result) {
                    console.log(result);
                    if (result.auth === true) {
                        window.location="/admin";                            
                    } else {
                       console.log("Incorrect username or password.");
                  }
                })

Upvotes: 1

daddykom
daddykom

Reputation: 220

If you work with jwt you have send the token with every request.

Usually this will be done with a framwork like jquery or angular, you use a middleware which adds the token to every request.

Here the sample for jquery.

$.ajaxPrefilter(function( options ) {
    if (options.beforeSend) {
        options.beforeSend = function (xhr) {
            xhr.setRequestHeader('Authorization',   
                 'Bearer'+localStorage.getItem('token'));
        }
    }
});

If you have that, you can use your code:

function login(event) {
            event.preventDefault();
            let formData = new FormData(event.target);

            fetch("/admin/login", {
                    method: 'POST',
                    body: formData 
            }).then(function (response) {          
                    return response.json();
                }).then(function (result) {
                    if (result.auth === true) {
                        localStorage.token = result.token;
                        window.location='/admin';
                         }
                        }); 
                    } else {
                        console.log("Incorrect username or password.");
                    }
                });       
        }

Upvotes: 0

Oleksandr Poshtaruk
Oleksandr Poshtaruk

Reputation: 2166

If your admin page is rendered as full page, then just do document.write(result) in /admin ajax request success handler

success : function(result) {                 
                   document.write(result)
                     }

Upvotes: 1

Related Questions