简体   繁体   中英

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

As per my understandings you need http server authentication in nodejs.

I know one npm module. 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. 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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