1

I have a login route that verifies a user then generates a token and redirects to the home page. I have some middleware set up but when I try to access the token in the middleware I get undefined. The token is being set up and is in the header if I don't redirect but when I do redirect I seem to loose the token from the headers. This is my first time working with tokens any help appreciated. Here is a reduced version of what I am working with:

router.post('/login', function(req, res) {
    var token = admin.generateToken('authentication');
    if(token) {
        //doing this I get the token in the header in postman
        //res.header('Auth', token).send('token in header');

        //lose the token doing this
        res.header('Auth', token).redirect('/');
     } else {
         res.send('IS ADMIN NO TOKEN GENERATED');
     }
});

router.get('/', middleware.requireAuthentication, function(req, res, next) {
    //Can't reach here because of undefined token
});

middlware.js

module.exports = function(db) {

    return {
        requireAuthentication: function (req, res, next) {
            var token = req.get('Auth');

            console.log('TOKEN: ' + token ); //undefined
    }
}
};
nasoj1100
  • 528
  • 9
  • 15

2 Answers2

1

Not sure if I am helping but I had something similar. It turns out I had to pass the other middlewares as an object when creating my routes.

So something like:

require('./routes/routes.js')(express, app, passport, mongoose, request, siteName);

Sean
  • 1,151
  • 3
  • 15
  • 37
1

It seems I needed sessions to persist the token value. Found this answered already here

Community
  • 1
  • 1
nasoj1100
  • 528
  • 9
  • 15
  • How were you able to persist the token value? I am facing the same problem. My web client sends an OAuth2 token to the web server by using a redirect. I tried headers, but the `res.redirect()` command resets the headers. I also tried saving the token in `req.session.accesstoken`, but the on the server side, this value is not maintained. – Umair47 Feb 21 '17 at 12:35