【问题标题】:Passport local strategy not authenticate护照本地策略未通过身份验证
【发布时间】:2018-03-27 01:46:40
【问题描述】:

当我尝试登录并收到SUCCESS 消息时,我的回调成功调用。但我仍然重定向到登录页面。

passport.use(new LocalStrategy(
function(username, password, done) {

        console.log(username + "----" + password)

        if(username == "test" && password == "test"){
            console.log("SUCCESS")
            done(null, { name: username})
        }
        else{
            done(null, false)
        }
}))

我的路线是按下一个顺序定义的

 .. some othe initialization, cookieparser, bodyparser, session ...
 app.use(passport.initialize())
 app.use(passport.session())

 app.use('/login', login);


 app.post('/login',passport.authenticate('local', { failureRedirect: '/login' }),
    function(req, res) {
       res.redirect('/plans');
    });

app.all('*',function (req, res, next) {

   console.log(req.isAuthenticated())
   if (req.isAuthenticated()) {
       return next()
   }
   res.redirect('/login')
})

app.use('/', index);
app.use('/users', users);
app.use('/plans', plans);

这里有什么错误吗?谢谢。

【问题讨论】:

    标签: node.js passport.js passport-local


    【解决方案1】:

    可能的原因如下:

    在我的节点应用程序中,我有以下中间件:

    app.use(session({
        secret: process.env.SESSION_SECRET,
        saveUninitialized: true,
        resave: true,
        cookie: {  httpOnly: true,  secure: true  }
    }));
    

    以下行总是返回 false:

    req.isAuthenticated()
    

    当我将安全的值从 true 更改为 false 时。问题消失了。

    【讨论】:

      【解决方案2】:

      这可能有点摸不着头脑,但您是否需要在 failureRedirect 之上再进行 successRedirect?我认为您的身份验证正确,但是该路线不知道成功后该做什么,因此它只是默认为任何可用的途径。正如我所说,这是一个猜测,但似乎是合理的。

      告诉我。

      只是展示护照文件中的一个例子:

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

      来源:http://passportjs.org/docs

      另外,如果你想进行身份验证,然后让它通过你传入的实际路由函数,那么我认为你想一起删除重定向。

      app.post('/login',
      passport.authenticate('local'),
      function(req, res) {
         // If this function gets called, authentication was successful.
         // `req.user` contains the authenticated user.
      res.redirect('/users/' + req.user.username);
      });
      

      也来自文档。

      最好, 亚军5

      【讨论】:

      • 我已经在上面尝试过,但这没有帮助。我仍然没有通过身份验证,即使在尝试登录后我尝试访问任何资源
      • 你是如何验证用户请求的?您使用的是令牌系统还是会话系统?我认为您实际上是通过获取成功控制台登录身份验证策略来成功显示身份验证的。问题是为什么在随后的请求中没有得到尊重。我假设没有为发出的请求传递适当的身份验证信息。
      猜你喜欢
      • 2015-09-10
      • 2018-12-13
      • 2016-03-11
      • 2018-06-08
      • 2022-07-19
      • 2017-03-21
      • 2017-05-25
      • 2016-02-28
      • 2020-10-21
      相关资源
      最近更新 更多