【问题标题】:Passport req.user not persisting across requests -Passport req.user 不会在请求中持续存在 -
【发布时间】:2019-06-25 05:16:01
【问题描述】:

使用 passport.js 本地策略我正在尝试使用 req.user 获取当前用户 ID,以便我可以使用用户 ID 将食谱存储在数据库中。问题似乎与我在应用程序的配置文件中的 passport.js 文件的反序列​​化部分有关。每当我出于某种原因点击 /api/saveRecipe 路由时,它就会被反序列化,然后 req 用户不再可用。

注意:我在我的后端服务器上使用前端的 react 进行身份验证。

下面是我的 server.js 文件

问题:调用 passport.authenticate('local') 后 req.user 可用,但一旦命中 api/saveRecipe 路由,req.user 不再可用。

在 S.O. 上研究了这个主题之后。似乎它通常与服务器文件设置中的顺序有关,但我已经查看并查看过,我相信我的设置是正确的......

const express = require("express");
const bodyParser = require("body-parser");
const session = require("express-session");
const routes = require("./routes");

// Requiring passport as we've configured it
let passport = require("./config/passport");

const sequelize = require("sequelize");

// const routes = require("./routes");
const app = express();
var db = require("./models");
const PORT = process.env.PORT || 3001;

// Define middleware here
app.use(express.urlencoded({ extended: true }));
app.use(express.json());

// passport stuff
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.static("public"));

// We need to use sessions to keep track of our user's login status
// app.use(cookieParser('cookit'));
app.use(
  session({ 
    secret: "cookit", 
    name: "cookit_Cookie"
   })
);
app.use(passport.initialize());
app.use(passport.session());

// Serve up static assets (usually on heroku)
if (process.env.NODE_ENV === "production") {
  app.use(express.static("client/public"));
}

// the view files are JavaScript files, hence the extension
app.set('view engine', 'js');

// the directory containing the view files
app.set('pages', './');

// Add routes, both API and view
app.use(routes);

// Syncing our database and logging a message to the user upon success
db.connection.sync().then(function() {
  console.log("\nDB connected\n")
  // Start the API server
  app.listen(PORT, function() {
    console.log(`????  ==> API Server now listening on PORT ${PORT}!`);
  });
});
module.exports = app;

我的 passport.js 代码

//we import passport packages required for authentication
var passport = require("passport");
var LocalStrategy = require("passport-local").Strategy;
//
//We will need the models folder to check passport against
var db = require("../models");

// Telling passport we want to use a Local Strategy. In other words, we want login with a username/email and password
passport.use(
  new LocalStrategy(
    // Our user will sign in using an email, rather than a "username"
    {
      usernameField: "email",
      passwordField: "password",
      passReqToCallback: true
    },
    function(req, username, password, done) {
      // console.log(`loggin in with email: ${username} \n and password: ${password}`)
      // When a user tries to sign in this code runs
      db.User.findOne({
        where: {
          email: username
        }
      }).then(function(dbUser) {
        // console.log(dbUser)
        // If there's no user with the given email
        if (!dbUser) {
          return done(null, false, {
            message: "Incorrect email."
          });
        }
        // If there is a user with the given email, but the password the user gives us is incorrect
        else if (!dbUser.validPassword(password)) {
          return done(null, false, {
            message: "Incorrect password."
          });
        }
        // If none of the above, return the user
        return done(null, dbUser);
      });
    }
  )
);

// serialize determines what to store in the session data so we are storing email, ID and firstName
passport.serializeUser(function(user, done) {
  console.log(`\n\n        serializing ${user.id}\n`)
  done(null, user.id);
});

passport.deserializeUser(function(id, done) {
  console.log(`\n\n        DEserializing ${id}\n`)
  db.User.findOne({where: {id:id}}, function(err, user) {
    done(err, user);
  });
});
// Exporting our configured passport
module.exports = passport;

const router = require("express").Router();
const controller = require("../../controllers/controller.js");
const passport = require("../../config/passport");

router.post(
  "/login",
  passport.authenticate("local", { failureRedirect: "/login" }),
  function(req, res) {
    console.log(`req body -${req.body}`);
    res.json({
      message: "user authenticated",
    });
  }
);


router.post("/saveRecipe", (req, res) => {
  console.log(req.user)
  if (req.isAuthenticated()) {
    controller.saveRecipe;
  } else {
    res.json({ message: "user not signed in" });
  }
});

module.exports = router;

【问题讨论】:

    标签: node.js express passport.js


    【解决方案1】:

    问题出在您的 router.post('login') 中。试着把它改成这样:

      app.post('/login', passport.authenticate('local-login', {
        successRedirect: '/profile',
        failureRedirect: '/login/failed'})
      )
    

    这将在您的下一个请求中正确设置 req.user!

    【讨论】:

      猜你喜欢
      • 2018-02-08
      • 2017-10-01
      • 2013-09-19
      • 1970-01-01
      • 2016-04-12
      • 2011-10-29
      • 1970-01-01
      • 2019-07-03
      • 1970-01-01
      相关资源
      最近更新 更多