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

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

-Shreyas


当前回答

我基本上也在找同样的东西。具体来说,我想要的是:

使用express.js,它包装了Connect的中间件功能 “基于表单的”身份验证 对哪些路由进行验证的粒度控制 用户/密码的数据库后端 使用会话

我最终所做的是创建自己的中间件函数check_auth,我将其作为参数传递给我想要验证的每个路由。Check_auth仅检查会话,如果用户没有登录,则重定向到登录页面,如下所示:

function check_auth(req, res, next) {

  //  if the user isn't logged in, redirect them to a login page
  if(!req.session.login) {
    res.redirect("/login");
    return; // the buck stops here... we do not call next(), because
            // we don't want to proceed; instead we want to show a login page
  }

  //  the user is logged in, so call next()
  next();
}

然后,对于每个路由,我确保该函数作为中间件传递。例如:

app.get('/tasks', check_auth, function(req, res) {
    // snip
});

最后,我们需要实际处理登录过程。这很简单:

app.get('/login', function(req, res) {
  res.render("login", {layout:false});
});

app.post('/login', function(req, res) {

  // here, I'm using mongoose.js to search for the user in mongodb
  var user_query = UserModel.findOne({email:req.body.email}, function(err, user){
    if(err) {
      res.render("login", {layout:false, locals:{ error:err } });
      return;
    }

    if(!user || user.password != req.body.password) {
      res.render("login",
        {layout:false,
          locals:{ error:"Invalid login!", email:req.body.email }
        }
      );
    } else {
      // successful login; store the session info
      req.session.login = req.body.email;
      res.redirect("/");
    }
  });
});

无论如何,这种方法主要被设计为灵活和简单。我相信有很多方法可以改善它。如果你有任何建议,我非常希望得到你的反馈。

编辑:这是一个简化的例子。在生产系统中,您绝对不希望以纯文本的形式存储和比较密码。正如一位评论者指出的那样,有一些库可以帮助管理密码安全。

其他回答

有一个项目叫Drywall,实现了一个用户登录系统与护照,也有一个用户管理管理面板。如果你正在寻找一个功能齐全的用户认证和管理系统,类似于Django提供的Node.js,这就是它。我发现,对于构建一个需要用户身份验证和管理系统的节点应用程序来说,这是一个非常好的起点。有关护照如何工作的信息,请参阅Jared Hanson的回答。

对身份验证的另一种理解是passdless,这是express的一个基于令牌的身份验证模块,它绕过了密码[1]的固有问题。它实现起来很快,不需要太多表单,并且为普通用户提供了更好的安全性(完全披露:我是作者)。

[1]:密码过时

下面是我的一个项目中的一些基本身份验证代码。我使用它来对付CouchDB和额外的认证数据缓存,但我剥离了这些代码。

在请求处理周围包装一个身份验证方法,并为身份验证不成功提供第二个回调。成功回调将获得用户名作为附加参数。不要忘记在失败回调中正确处理错误或缺少凭据的请求:

/**
 * Authenticate a request against this authentication instance.
 * 
 * @param request
 * @param failureCallback
 * @param successCallback
 * @return
 */
Auth.prototype.authenticate = function(request, failureCallback, successCallback)
{
    var requestUsername = "";
    var requestPassword = "";
    if (!request.headers['authorization'])
    {
        failureCallback();
    }
    else
    {
        var auth = this._decodeBase64(request.headers['authorization']);
        if (auth)
        {
            requestUsername = auth.username;
            requestPassword = auth.password;
        }
        else
        {
            failureCallback();
        }
    }


    //TODO: Query your database (don't forget to do so async)


    db.query( function(result)
    {
        if (result.username == requestUsername && result.password == requestPassword)
        {
            successCallback(requestUsername);
        }
        else
        {
            failureCallback();
        }
    });

};


/**
 * Internal method for extracting username and password out of a Basic
 * Authentication header field.
 * 
 * @param headerValue
 * @return
 */
Auth.prototype._decodeBase64 = function(headerValue)
{
    var value;
    if (value = headerValue.match("^Basic\\s([A-Za-z0-9+/=]+)$"))
    {
        var auth = (new Buffer(value[1] || "", "base64")).toString("ascii");
        return {
            username : auth.slice(0, auth.indexOf(':')),
            password : auth.slice(auth.indexOf(':') + 1, auth.length)
        };
    }
    else
    {
        return null;
    }

};

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
    }
})

几年过去了,我想介绍我的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

看一下这些例子。