How to get express route to go through passport for authentification

时间:2018-07-25 04:56:09

标签: javascript node.js express express-jwt passport-jwt

I'm recently changing a boilerplate I made in es6 to a slightly older version es5. I had to recreate the export, require instead of using imports and the routing is functional now.

I have a structure like this:

index.js (app)
api/index.js (/api endpoint)
api/auth.js (/api/auth endpoint)
api/protected.js (/api/protected endpoint)

In my auth route I have the login and register functionning and generating a token:

const token = jwt.sign({id: req.body.username},  config.jwtSecret)

In my protected.js I have the following:

const express = require('express');
const router = express.Router();
const passport = require('../config/passport');
router.use(passport.initialize({ session: false }));
router.use(passport.session());
router.get('/test', passport.authenticate('jwt') , (req, res) => {
    res.status(200).json({ message: 'Hello sweetie', auth: req.isAuthenticated(), user: req.session.passport.user})
});
module.exports = router;

And in my passport.js

const
  passport = require('passport'),
  config = require('./../config'),
  passportJwt = require('passport-jwt'),
  JwtStrategy = passportJwt.Strategy,
  ExtractJwt = passportJwt.ExtractJwt,
  userSchema = require('./../schemas/userSchema');

passport.serializeUser(function(user, done) {
    console.log(JSON.stringify(user));
    done(null, user[0].username);
});

passport.deserializeUser(function(username, done) {
    console.log('DESER -- '+username);
    userSchema.checkUsername(username)
    .then(user => {
        console.log(user[0]);
        done(null, user[0]);
    })
    .catch(err =>{
        console.log(JSON.stringify(err));
    });
});

const jwtOptions = {
    secretOrKey: config.jwtSecret,
    jwtFromRequest: ExtractJwt.fromHeader('authorization'),
}

passport.use('jwt', new JwtStrategy(jwtOptions, function(jwt_payload, done) {
    console.log('Strategy: '+ jwt_payload.id);
    userSchema.checkUsername(jwt_payload.id)
    .then(user => {
        console.log(user[0].username);
        if(user[0]) return done(null, user)
        else return done(null, false)
    })
    .catch(err =>{
        console.log(JSON.stringify(err));
    });
}));

module.exports = passport;

The problem is when I try to access: 127.0.0.1:8080/api/protected/test with the token I got on login it give me a: Unauthorized

Furthermore the console.log inside the:

  • serializeUser
  • deserializeUser
  • jwt Strategy

Are never shown and thus I think the passport middleware isn't used.

How could I get the /protected routes to use the passport middleware?

Edit: I have tried printing the passport object and I can see my jwt strategy is indeed defined. So I don't see why it doesn't want to go through it.

There si a strategy

1 个答案:

答案 0 :(得分:5)

问题是您的护照正在寻找authorization标题而不是Authorization标题。

更改您的

jwtFromRequest: ExtractJwt.fromHeader('authorization')

ExtractJwt.fromAuthHeaderAsBearerToken()

所以您的选择看起来像

const jwtOptions = {
    secretOrKey: config.jwtSecret,
    jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
}

现在这是护照的操作,将查找具有值Authorization的{​​{1}}标题。 https://www.npmjs.com/package/passport-jwt