Express Router()和Passport Authenticate()

时间:2017-11-27 00:53:48

标签: node.js express jwt passport.js

我正在使用Express(v4.15),Passport(v0.4.0)和Passport-JWT(v3.0.1)。我使用的是Node版本8.9.0。

我似乎无法让Express.Router()和我的passport.authenticate()调用正常工作。我在这里做错了什么?

./路由/ user.js的:

var express = require('express');
var router = express.Router();

router.get('/user', function (req, res) {
  res.send('Secured Page: user account settings');
});

module.exports = router;

./ app.js:

var app = require('express')();
var passport = require('passport');
var passportJWT = require('passport-jwt');
var jwt = require('jwt-simple');
var Strategy = passportJWT.Strategy;
var ExtractJWT = passportJWT.ExtractJwt;

var userDB = require('./userdb');
var config = require('./config/config');
var params = {
  secretOrKeyProvider: function (req, rawJWT, done) { done(null, config.jwtSecret); },
  jwtFromRequest: ExtractJWT.fromAuthHeaderAsBearerToken()
};

var user = require('./routes/user');

// ...

var strategy = new Strategy(params, function jwtVerify (payload, done) {
  console.log('payload recieved', payload);
  // usually this would be a database call
  var user = userDB[_.findIndex(userDB, {id: payload.id})];
  if (user) {
    done(null, user);
  } else {
    done(new Error('User not found'), false);
  }
});

passport.use(strategy);

//...

app.use('/user', passport.authenticate('jwt', {session: false}), user);

这是我在Postman中得到的: 404 Error In Postman

1 个答案:

答案 0 :(得分:0)

我发现了我的问题。

router.get('/user', function (req, res) {

应该是:

router.get('/', function (req, res) {

这导致最终路线为' / user / user'