可以在我的网站上使用的node.js中如何进行身份验证? [英] How to do authentication in node.js that I can use from my website?

查看:86
本文介绍了可以在我的网站上使用的node.js中如何进行身份验证?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个Node.js服务来验证我网站的用户.我该怎么办?

I want a Node.js service to authenticate the user of my website. How can I do this?

我想使用简单的密码方法而非OpenID来实现Everyauth身份验证.

I want to implement Everyauth authentication using the simple password method, not OpenID.

我尝试了 https://github.com/jimpick/everyauth-example-password并且有效.

我想使用数据库进行存储.该脚本不使用数据库.我过去使用过MySQL,所以我更喜欢这样做,但是我对其他任何东西(例如MongoDB)都没问题.

I want to use the database to store. This script does not use a database. I have used MySQL in past so I prefer that but I am ok with anything else as well such as MongoDB.

我只想将数据库添加到我的脚本中.请帮忙.

I just want to add database to my script. Please help.

推荐答案

您只需要修改.authenticate方法.由于连接到数据库是(或应该是)异步操作,因此您需要添加promise对象(请参见 everyauth文档).

You only need to modify .authenticate method. Since connecting to database is (or should be) an asynchronous operation, then you need to add promise object (see everyauth documentation).

假设您有一些ORM,其中的用户数据与具有usernamepassword属性的user对象相对应(在我的示例中,我将使用猫鼬引擎),这就是它的外观:

Assuming you have some ORM with user data corresponding to user object with username and password attributes (in my example I'll use mongoose engine), this is how it may look:

.authenticate( function (login, password) {
    var promise = this.Promise(); /* setup promise object */

    /* asynchrnously connect to DB and retrieve the data for authentication */
    db.find({ username:login }, function(err, user) {
        if (err)
            return promise.fulfill([err]);
        if ((!user) || (user.password != password))
            return promise.fulfill(['Incorrect username or password!']);
        promise.fulfill(user);
    });

    return promise; /* return promise object */
})

我没有对其进行测试,但是根据文档,它应该可以工作.请记住,错误应该保存在数组中.

I didn't test it, but according to the documentation it should work. Remember that errors are supposed to be held in array.

顺便说一句:如果您仅使用密码方法,那么就无需使用大炮来对付苍蝇. :)编写自己的身份验证机制(不一定完美,但可以正常工作)非常简单,如果您不知道如何进行身份验证,则应该学习它.将来它将受益,因为一般而言,身份验证和安全性在每个Web应用程序中都非常重要.

By the way: if you are using only the password method, then there is no need to, you know, use a cannon against a fly. :) Writing your own (not necessarly perfect, but working) authentication mechanism is really simple and if you don't know how to do this you should learn it. It will benefit in the future, because authentication and security in general are very important in every web app.

这篇关于可以在我的网站上使用的node.js中如何进行身份验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆