节点护照本地策略总是失败

时间:2015-06-02 18:53:59

标签: javascript node.js authentication

我正在使用Node.js Passport模块来构建身份验证过程,而且我无法弄清楚为什么验证总是会失败,即使我每次都从验证回调中返回成功。为了使示例简单,我只使用passport-local策略而没有持久存储:

/**
 * Tricky {@link NavigationView} doesn't allow create dynamic
 * menu, be clearly adding menu items on the fly doesn't updates
 * Menu Adapter in {@link NavigationView} so, to we should update
 * it manually view {@link NavigationMenuPresenter#updateMenuView(boolean)}
 *
 * Returns {@link NavigationMenuPresenter} instance from {@link NavigationView}
 */
static NavigationMenuPresenter getNavigationMenuPresenter(NavigationView view){
    try {
        Field presenterField = NavigationView.class.getDeclaredField("mPresenter");
        presenterField.setAccessible(true);
        return (NavigationMenuPresenter) presenterField.get(view);
    } catch (NoSuchFieldException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
    return null;
}

通过添加占位符用户序列化/反序列化方法已经解决了类似的问题,但我已经有了这些方法。

这是一个CURL调用,使用用户名和密码点击上面的内容:

var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var express = require('express');
var server = express();

passport.serializeUser(function (user, done) {
  done(null, user);
});

passport.deserializeUser(function (id, done) {
  done(null, id);
});

passport.use(new LocalStrategy(
  function (username, password, done) {
    // Would perform lookup and verification here.
    // Instead return a valid user object every time.
    var user = { username: username };
    return done(null, user);
  }
));

server.post('/login', passport.authenticate('local', { failureRedirect: '/failure' }), function (req, res) {
  res.send('access granted');
});

var port = process.env.PORT || 3000;
server.listen(port,  function() {
  console.log('Listening on port ' + port);
});

当我执行该POST时,每次响应都包含HTTP 302故障重定向到curl -X "POST" "http://127.0.0.1:3000/login" \ --data-urlencode "username=alice" \ --data-urlencode "password=supersecret" ,即使我正在返回/failure(没有错误),并且null中有一个虚拟用户对象{1}}回调。我在俯瞰什么?

1 个答案:

答案 0 :(得分:6)

我忽略了两件事:

  • 没有调用LocalStrategy中间件
  • 我没有解析请求正文,因为Express不包含开箱即用的

现在我顶部的需求块包含两个缺少的项目,并且在发布到passport.initialize()时返回200 OK:

/login