I am trying to set up an authentication via token for my web app. I am using nodejs for the back end and the jwt-simple module to encode/decode the tokens.
I manage to create and handle the tokens from the server to the client. However I struggle to handle the token from the client to the server.
For example, I have a page called profile for which I handle the requests the following way:
  app.get('/profile', [bodyParser(), jwtauth], function(req, res) {
    res.render('profile.ejs', {
      user : req.user // get the user out of session and pass to template
    });
  });
Where jwtauth is the following:
var jwt = require('jwt-simple');
var User = require('../server/models/user');
 
module.exports = function(req, res, next) {
  var token = (req.user && req.user.access_token) || (req.body && req.body.access_token) || (req.query && req.query.access_token) || req.headers['x-access-token'];
  if (!token)
    return next('invalid or no token');
  try {
    var decoded = jwt.decode(token, app.get('jwtTokenSecret'));
    if (decoded.exp <= Date.now())
      return res.end('Access token has expired', 400);
    User.findOne({ _id: decoded.id }, function(err, user) {
      req.user = user;
    });
    return next();
  } catch (err) {
    return next('couldn\'t decode token');
  }
};
On the client side I attached the token once the user is logged in the following way:
$(document).ready(function() {
  var token = __token;
  if (token) {
    $.ajaxSetup({
      headers: {
        'x-access-token': token
      }
    });
  }
});
But if I try to get the url '/profile' in my browser there is no 'x-access-token' in the headers and I get the 'invalid or no token' message.
How can I set the token on the client side so that it is attached to every request to my server?
Many thanks
 
     
    