护照js反序列化用户永远不会被召唤

时间:2018-10-31 14:48:15

标签: node.js express authentication passport.js

我正在使用护照js构建一个快速应用程序,用于实施本地策略的身份验证

我正在使用邮递员来测试代码,我能够收到登录和注销请求的成功响应,

但是当我使用有效的凭据登录后尝试访问任何受保护的路由时,会收到未授权的错误消息

我发现未经授权的消息的原因是passport.session()不会在随后的请求中触发deserializeUser(),从而导致拒绝访问

这是我的应用程序的结构。请有人指出我错了

我有这样的app.js设置,我在其中导入所有内容并进行初始化

app.js

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var cors = require('cors');
var bodyParser = require('body-parser');
var passport = require('passport');
var session = require('express-session');

require('./config/passport')(passport);

var authRouter = require('./routes/authRouter')(passport);
var studentRouter = require('./routes/studentRouter');
var facultyRouter = require('./routes/facultyRouter');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
app.use(session({
   secret: 'keyboard cat',
   resave: false,
   saveUninitialized: true,
}))
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(passport.initialize());
app.use(passport.session());
app.use(cors());

app.use('/', authRouter);
app.use('/student', studentRouter);
app.use('/faculty', facultyRouter);

到目前为止,我仅使用本地策略进行身份验证,以添加更多策略并使其与其他策略一起使用。我已经在一个单独的模块中实现了护照js的配置并使用了它

/config/passport.js

var LocalStrategy = require('passport-local').Strategy;
var db = require('../services/dbConnection');

module.exports = function(passport) {
  passport.serializeUser(function(id, done) {
    console.log("id", id);
    done(null, id["student_id"]);
  });

  passport.deserializeUser(function(id, done) {
    console.log("deserialize", id);
    db.query("SELECT * FROM students WHERE student_id = ?", [id], function(
      err,
      data,
      fields
    ) {
      done(err, data[0]);
    });
  });

  passport.use(new LocalStrategy({passReqToCallback:true},
    function(req,username,password,done){
      console.log(username,password,req.body.role);
      db.query("SELECT * FROM students WHERE student_id = ?",[username],function(err,data,fields){
        if(err){
          return done(err);
        }
        if(data.length === 0){
          return done(null,false);
        }
        if(data[0]['password'] !== password){
          return done(null,false);
        }
        data[0]['role']=req.body.role;
        return done(null,data[0]);
      })
    }
  ));

};

与身份验证相关的路由已放置在单独的路由文件中

/routes/authRouter.js

var express = require("express");
var router = express.Router();
var response = require("../services/responseFormat");
var statusCodes = require("../constants/httpStatusCodes");

module.exports = function(passport) {

  router.post("/signup", function(req, res, next) {});

  router.post("/login", passport.authenticate("local"), function(
    req,
    res,
    next
  ) {
    message = {
      success: true
    };
    response.sendSuccessResponse(res, statusCodes.OK, message);
  });

  router.get("/logout", function(req, res, next) {
    req.logout();
    message = {
      success: true
    };
    response.sendSuccessResponse(res, statusCodes.OK, message);
  });
  return router;
};

我在其他模块和控制器中分别设置了其他路由,每个模块都包含各自的功能

/routes/studentRouter.js

var express = require('express');
var router = express.Router();
var studentController = require('../controllers/studentController');
var authenticationMiddleWare = require('../middlewares/checkAuthenticated');

// Routes that deal with marks
router.get('/:studentId/marks/:occurrenceId',authenticationMiddleWare.isAuthenticated,studentController.getMarks);
router.put('/marks/:markId',authenticationMiddleWare.isAuthenticated,studentController.updateRemarks);

我编写了一个中间件来检查用户是否已通过身份验证,如果通过身份验证,则会调用路由处理程序,否则会发送未经授权的错误消息

0 个答案:

没有答案