Node.js 用户名密码认证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14035264/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 16:49:54  来源:igfitidea点击:

Node.js username and password authentication

node.jsexpress

提问by Jasdeep Khalsa

I'm currently building a web app using Node.jsand Express.js.

我目前正在使用Node.js和构建一个网络应用程序Express.js

I'm looking for a way to have a simple server-side authentication with a username and password in my main app.jsfile which is listening for a postrequest at http://www.domain.com/login:

我正在寻找一种方法,在我的主app.js文件中使用用户名和密码进行简单的服务器端身份验证,该文件正在侦听以下位置的post请求http://www.domain.com/login

app.js

应用程序.js

app.post('/login', function(req, res) {
  // some server-side code for a username and password
}

On the client-side I have a simple login form with a username and password. This form is going to posted to the server:

在客户端,我有一个带有用户名和密码的简单登录表单。此表单将发布到服务器:

index.html

索引.html

<form method="post" action="/login">
<input type="text" id="user" name="user" />
<input type="password" id="pass" name="pass" />
<button type="submit">Login</button>
</form>

I am looking to achieve this withoutthe use of any ExpressJSplugins.

我希望在使用任何ExpressJS插件的情况下实现这一目标。

Edit:So my question is, how do I achieve a simple username and password authentication in ExpressJS and NodeJS?

编辑:所以我的问题是,如何在 ExpressJS 和 NodeJS 中实现简单的用户名和密码身份验证?

采纳答案by Jasdeep Khalsa

I found the answerI was looking for using the Connectmiddleware included with ExpressJS, withoutthe need to use cookies or add in another Node module:

我找到了我正在寻找的答案,使用Connect随附的中间件ExpressJS无需使用 cookie 或添加另一个 Node 模块:

var express = require('express');

function authorize(username, password) {
    return 'someone' === username & 'password' === password;
}

var app = express.createServer(
    express.basicAuth(authorize)
);

app.get('/', function(request, response) {
    response.send('Authorized!');
});

console.log('Starting server...')
app.listen(8080);

After running the application and navigating to http://localhost:8080, it prompts for a username and password. Simples.

运行应用程序并导航到 后http://localhost:8080,它会提示输入用户名和密码。简单。

回答by randunel

With the use of ExpressJS sessions, you may hold session cookies. You need cookieParser and a session store. But if you don't want to extend this ExpressJS functionality (this is what i understand from your message), you should manage your own sessions with a token or a secret temporary string.

通过使用 ExpressJS 会话,您可以持有会话 cookie。您需要 cookieParser 和会话存储。但是如果你不想扩展这个 ExpressJS 功能(这是我从你的消息中理解的),你应该使用令牌或秘密临时字符串管理你自己的会话。

Although I strongly advise you to use ExpressJS sessions, this is how you should do it without ExpressJS cookies.

尽管我强烈建议您使用 ExpressJS 会话,但如果没有 ExpressJS cookie,您应该这样做。

  • On each login, create a unique token and store it for future lookup.
  • On each request, send that token from the client and check it on the server. Redirect to the login if the token is invalid
  • 在每次登录时,创建一个唯一的令牌并将其存储以备将来查找。
  • 对于每个请求,从客户端发送该令牌并在服务器上检查它。如果令牌无效,则重定向到登录

Here is the login code example:

这是登录代码示例:

app.post("/login", function(req, res) {
    if(req.body.username && req.body.password) {
        // check username and password
        if(authenticated) {
            // create a token and store it with the current date (if you want it to expire)
            var token = generateAndStoreRandomString(req.body.username);
            res.redirect("http://your.domain/path?token=" + token);
            return;
        }
        // Do something if username or password wrong
    }
    // Do something if no username or password
});

Now, on every request:

现在,对于每个请求:

app.get("somePath", function(req, res) {
    if(!req.query.token) {
        res.redirect("http://your.domain/login");
        return;
    }
    // Check token in database, if it exists and it hasn't expired
    if(!authenticated) {
        res.redirect("http://your.domain/login");
        return;
    }
    // The user is authenticated. Do the actions required by "somePath"
});

Try to have a process clean up the expired tokens every once in a while, since they will add up eventually. If you want to use ExpressJS cookieParser and session store, there are a lot of articles and examples. Post another question if you are having troubles with those.

尝试让一个进程每隔一段时间清理一次过期的令牌,因为它们最终会加起来。如果要使用 ExpressJS cookieParser 和 session store,这里有很多文章和示例。如果您遇到这些问题,请发布另一个问题。

I shall repeat myself, try using ExpressJS sessions. This method can be easily hiHymaned if you use http instead of https.

我将重复自己,尝试使用 ExpressJS 会话。如果您使用 http 而不是 https,则此方法很容易被劫持。

回答by Daniel

It's pretty simple. ExpressJS is a super tiny framework that's build ontop of the basic http server within Node.js and connect, a node module.

这很简单。ExpressJS 是一个超小型框架,它构建在 Node.js 和 connect(一个节点模块)中的基本 http 服务器之上。

To make an authentication system you would use sessions. First you need to call this line:

要制作身份验证系统,您将使用会话。首先,您需要调用此行:

app.use(express.cookieSession());

Then you'll be able to use the req.sessionto store and load sessions.

然后您将能够使用req.session来存储和加载会话。

app.post('/login', function(req, res) {
    if (req.session.username & req.session.password != null) {
       // Already logged in.
    } else {
       var q = db.query("SELECT * FROM `users` WHERE `username`='" + req.params.username + "' AND `password`='" + req.params.password + "'");

       if (q) {
          // Set the sessions.
          req.session.username = req.params.username;
          req.session.password = req.params.password;
       }
    }
});

A basic example. You would definitely have to sanitize the input and secure it, but it should get you started.

一个基本的例子。您肯定必须对输入进行消毒并保护它,但这应该可以帮助您入门。