Search code examples
node.jsexpressjwtpassport.jspassport-jwt

is it possible to change the `JWT` string with `JwtStrategy`?


I downloaded a Node / Ionic project from internet, then...

on the authorization controller file I have the following:

...
exports.login = function(req, res, next) {
    var userInfo = getUserInfo(req.user);
    res.status(200).json({
        token: 'JWT ' + generateToken(userInfo),
        userInfo: userInfo
    });
}
...

on other configuration file I have the following:

...
passport.use(
    new JwtStrategy({
            secretOrKey: credentials.secret,
            jwtFromRequest: ExtractJwt.fromAuthHeader(),
        },
        function(payload, done) {
            User.findById(
                payload._id,
                function(err, user) {
                    if (err) {
                        return done(err, false);
                    }
                    if (user) {
                        return done(null, user);
                    } else {
                        return done(null, false);
                    }
                }
            );
        }
    )
);
...

on the routes file I have the following:

...
app.get(
    '/api/auth/check',
    passport.authenticate('jwt', { session: false }),
    function(req, res) {
        var user = req.user;
        res.send({ content: 'Success', user: user });
    }
...

Then, I have one specific question about this:

What is the 'JWT' for on the authorization controller file?

...
token: 'JWT ' + generateToken(userInfo),
...

what about if instead of JWT I wanna use ABCDEF?. Actually, I tried other strings different than: JWT and it seems to keep working, don't understand why. I went to the documentation but it is not clear about this.


Solution

  • The documentation is clear on how to do that:

    • jwtFromRequest (REQUIRED) Function that accepts a request as the only parameter and returns either the JWT as a string or null. See Extracting the JWT from the request for more details.

    You're doing:

    new JwtStrategy({
        secretOrKey: credentials.secret,
        jwtFromRequest: ExtractJwt.fromAuthHeader()
    }, ...)
    

    You have two options here:

    1. Write your own function that extracts the JWT:

      function myExtractor(req) {
          const jwt = req.header('ABCDEF')
          // ... do work
          return 'extractedJwtToken from work.'
      }
      
    2. Use the provided extractor that allows you to specify a custom scheme:

      new JwtStrategy({
          secretOrKey: credentials.secret,
          jwtFromRequest: ExtractJwt.fromAuthHeaderWithScheme('ABCDEF')
      }, ...)