0

目前我一直在使用一个名为 Postman 的 chrome 应用程序从 nodejs/express/passportjs 测试我的服务。

目前,我在思考如何获取用户信息并使用主干对其进行身份验证时遇到了麻烦。

我会尝试像这样对用户进行身份验证:

$.post("http://localhost:3000/login", { username: "joe", password: "pass" })
.done(function(data) {
  console.log(data)
  //try to pull a service that's protected by passport
})
.fail(function(data) {
  console.log(data)
})

当它成功时,它根本不起作用。它给出了我为某人未登录时设置的 500 错误。

我应该采取任何特定的方向来管理主干中的passportjs身份验证?

4

1 回答 1

0

500 错误意味着服务器中的某些部分代码无法正常工作。您可以使用护照从快递发送登录用户。您可以按照以下示例进行操作。

var app = express();
var login = require('./routes/login');
app.post('/login', 
    passport.authenticate('local', { successRedirect: '/',  
                                   failureRedirect: '/login',
                                   failureFlash: true }), 
    login.login);

您的 login.js 文件可能如下所示

exports.login = function (req, res) {
    res.json(req.user);
}

护照的身份验证过程使用登录用户填充请求(req)中的用户变量。

请注意,您必须使用 cookie 解析器和 express 会话才能使护照会话正常工作。例如,

app.use(express.cookieParser());
app.use(express.session({ secret: 'keyboard cat' }));

您的本地身份验证可能如下所示(假设您有一个通过用户名 (findByUsername) 查找用户的函数)。

passport.use(new LocalStrategy({
    usernameField: 'username',
    passwordField: 'password'
  },
  function(username, password, done) {
    // asynchronous verification, for effect...
    process.nextTick(function () {

      // Find the user by username.  If there is no user with the given
      // username, or the password is not correct, set the user to `false` to
      // indicate failure and set a flash message.  Otherwise, return the
      // authenticated `user`.
      findByUsername(username, function(err, user) {
        if (err) { return done(err); }
        if (!user) { return done(null, false, { message: 'Unknown user ' + username }); }
        if (user.password != password) { return done(null, false, { message: 'Invalid password' }); }
        return done(null, user);
      })
    });
  }
));
于 2013-08-15T02:15:43.177 回答