Node.js用户名和密码验证 [英] Node.js username and password authentication

查看:166
本文介绍了Node.js用户名和密码验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用 Node.js Express.js 构建一个Web应用.

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

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

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

app.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

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

我希望在不使用任何 ExpressJS 插件的情况下实现 .

I am looking to achieve this without the use of any ExpressJS plugins.

所以我的问题是,如何在ExpressJS和NodeJS中实现简单的用户名和密码认证?

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

推荐答案

我找到了答案我一直在寻找使用 ExpressJS 附带的 Connect 中间件,无需使用cookie或添加其他Node模块的需求:

I found the answer I was looking for using the Connect middleware included with ExpressJS, without the need to use cookies or add in another Node module:

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

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

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

这篇关于Node.js用户名和密码验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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