javascript - Req.isAuthenticated 变为 false

标签 javascript node.js express passport.js

当我登录时,我已通过身份验证,但当我切换到另一个页面时,req.isAuthenticated 返回 false,并且我位于登录面板上。第二件事是,当我登录时,我不断收到错误“发送后无法设置 header ”。这是我的代码:

const isLoggedIn = (req, res, next) => {
  if (req.isAuthenticated()) {
    return res.end();
  } else {
    return res.redirect("/login");
  }
}
module.exports = (app, passport) => {
  app.post("/login", (req, res, next) => {
    passport.authenticate("local-login", 
    (err, user, info) => {
        if(!user) {
          res.render("index", { message: "Wrong password or login!" })
        } else {
          req.login(user, (error) => {
            if (error) return next(error);
            console.log("AUTH: ", req.isAuthenticated()) <--- RETURNS TRUE
            return res.render("map", { name: user.name });
          });
        }
      })(req, res, next);
  });
  app.get("/", (req, res) => {
    return res.render("index"); // load the index file
  })
  app.get("/login", (req, res) => {
    return res.render("index"); // load the index file
  })
  app.get("/map", isLoggedIn, (req, res) => {
    return res.render("map");
  });
  app.get("/vehicles", isLoggedIn,  (req, res) => {
    return 
  });
  app.get("/settings", isLoggedIn, (req, res) => {
    res.render("settings");
  });
  app.get("/logout", (req, res) => {
    req.logout();
    res.redirect("/");
  });
};

最佳答案

登录页面当然会给您 req.isAuthenticated true 因为您刚刚通过 passport 中间件进行了身份验证。

Passport 将返回 req.isAuthenticated true 直到您未注销,并且当您点击 /logout 时,它​​将设置 req.isAuthenticated false > 路线

因此,维护用户的状态,您必须使用 session 来存储用户的状态 应用程序。

找到以下链接:https://www.npmjs.com/package/express-session

您收到“发送后无法设置 header ”。因为你返回响应两次。第一个是在 req.isAuthenticated() 变为 true 之后,第二个就像您再次渲染一个 map 页面。

所以你应该使用next()而不是return res.end()

const isLoggedIn = (req, res, next) => {
  if (req.isAuthenticated()) {
    req.session.isAuthenticated = true;
    res.locals.isAuthenticated = true;
    res.locals.user =req.user; 
    next(); //If you are authenticated, run the next
  } else {
    return res.redirect("/login");
  }
}

关于javascript - Req.isAuthenticated 变为 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46844915/

相关文章:

javascript - ExtJS 4 存储中少数实例中的唯一记录

node.js - Node JS - 无法终止使用子进程 Exec 执行的进程

node.js - 使用通过 heroku foreman 从 .env 文件加载的 RSA 私钥签署 JWT 时出错

javascript - 在 Node/Express 中将 CSV 转换为 XML 的优雅方式

node.js - 测试在 Node 中使用 mocha/supertest 重定向的请求

javascript - angularjs正常导航而不是$location.path

javascript - 使用 jquery 单击多个 div 时添加和删除类

javascript - 在Javascript中计算二次曲线上任意点的切线斜率

javascript - 将对象序列化为 XML 会破坏结构定义

node.js - Node js错误 "process with a non-zero exit code"