是否存在node.js的现有用户身份验证库?特别是,我正在寻找可以为用户(使用自定义后端auth DB)进行密码身份验证的东西,并将该用户与会话关联。

在我编写一个认证库之前,我想看看人们是否知道现有的库。在谷歌上找不到明显的东西。

-Shreyas


当前回答

如果您正在寻找Connect或Express的身份验证框架,Passport值得一试:https://github.com/jaredhanson/passport

(游戏邦注:我是Passport的开发者)

在研究了connect-auth和everyauth之后,我开发了Passport。虽然它们都是很棒的模块,但并不适合我的需求。我想要更轻便、不显眼的东西。

Passport被分解为单独的模块,因此您可以选择只使用您需要的模块(OAuth,仅在必要时使用)。Passport也不会在应用程序中挂载任何路由,这使您可以灵活地决定何时何地需要身份验证,并且钩子可以控制身份验证成功或失败时发生的情况。

例如,下面是设置基于表单(用户名和密码)的身份验证的两步过程:

passport.use(new LocalStrategy(
  function(username, password, done) {
    // Find the user from your DB (MongoDB, CouchDB, other...)
    User.findOne({ username: username, password: password }, function (err, user) {
      done(err, user);
    });
  }
));

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

通过Facebook、Twitter等进行身份验证还可以使用其他策略。如果需要,可以插入自定义策略。

其他回答

下面是两个流行的用于node js身份验证的Github库:

https://github.com/jaredhanson/passport(易受暗示)

https://nodejsmodules.org/pkg/everyauth

slim-auth

轻量级、零配置的用户认证模块。它不需要单独的数据库。

https://www.npmjs.com/package/slimauth

很简单:

app.get('/private-page', (req, res) => {

    if (req.user.isAuthorized) {
        // user is logged in! send the requested page
        // you can access req.user.email
    }
    else {
        // user not logged in. redirect to login page
    }
})

关于手摇方法,要注意一点:

我很失望地看到,本文中建议的一些代码示例并不能防止会话固定或定时攻击等基本身份验证漏洞。

与这里的一些建议相反,身份验证并不简单,处理解决方案也不总是简单的。我推荐passsportjs和bcrypt。

但是,如果你决定着手解决问题,可以看看express js提供的例子,以获得灵感。

祝你好运。

如果你想要第三方/社交网络登录集成,也要看看每个auth。

几年过去了,我想介绍我的Express身份验证解决方案。它叫做Lockit。你可以在GitHub上找到这个项目,也可以在我的博客上找到一个简短的介绍。

那么与现有的解决方案有什么不同呢?

easy to use: set up your DB, npm install, require('lockit'), lockit(app), done routes already built-in (/signup, /login, /forgot-password, etc.) views already built-in (based on Bootstrap but you can easily use your own views) it supports JSON communication for your AngularJS / Ember.js single page apps it does NOT support OAuth and OpenID. Only username and password. it works with several databases (CouchDB, MongoDB, SQL) out of the box it has tests (I couldn't find any tests for Drywall) it is actively maintained (compared to everyauth) email verification and forgot password process (send email with token, not supported by Passport) modularity: use only what you need flexibility: customize all the things

看一下这些例子。