简体   繁体   English

express.js或react.js中的通用用户名/密码身份验证

[英]Universal username/password authentication in express.js or react.js

Setting up user authentication can be easily achieved in apache by setting up .htaccess and .htpasswd However I am developing an new web application and I am using express.js or react.js to create a web server. 可以通过设置.htaccess和.htpasswd在apache中轻松实现设置用户身份验证。但是,我正在开发一个新的Web应用程序,并且正在使用express.js或react.js创建一个Web服务器。 I searched user authentication online but they are long projects for email style logins like here . 我搜索用户认证在线,但他们对于电子邮件的风格类似的登录项目,长在这里 All I need is a single universal username and password. 我只需要一个通用的用户名和密码。 When a user browse to my website a pop appear for the username and password. 当用户浏览到我的网站时,会弹出一个用户名和密码的弹出窗口。 (Same like .htaccess style) (与.htaccess样式相同)

As per my understandings you need http server authentication in nodejs. 根据我的理解,您需要在nodejs中进行HTTP服务器身份验证。

I know one npm module. 我知道一个npm模块。 link 链接

And it's pretty easy to setup also. 而且设置起来也很容易。 Basic example 基本例子

// Authentication module. 
var auth = require('http-auth');
var basic = auth.basic({
    realm: "Simon Area.",
    file: __dirname + "/../data/users.htpasswd"
});

// Creating new HTTP server. 
http.createServer(basic, (req, res) => {
    res.end(`Welcome to private area - ${req.user}!`);
}).listen(1337);

If anyone is interested to do in ES2016 then follow the following code. 如果有人有兴趣在ES2016中进行操作,请遵循以下代码。 Set the babel etc to make it work. 设置巴别塔等使其工作。

import express from 'express';
import auth from 'http-auth';
// Configure basic auth
const basic = auth.basic({ 
realm: 'SUPER SECRET STUFF'
}, (username, password, callback) => { 
callback(username == 'admin' && password == 'password'); 
});
// Set up express app
const app = express();
// Create middleware that can be used to protect routes with basic auth
const authMiddleware = auth.connect(basic);
// Protected route
app.get('/', authMiddleware, (request, response) => { 
response.send('you made it!'); 
});
app.listen(3000);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM