2017-05-28 76 views
0

設置用戶身份驗證可以通過設置.htaccess和.htpasswd輕鬆實現。但是,我正在開發一個新的Web應用程序,我使用express.js或react.js創建一個Web服務器。我在網上搜索了用戶認證,但他們是電子郵件樣式登錄的長期項目,如here。我只需要一個通用的用戶名和密碼。當用戶瀏覽我的網站時,彈出窗口顯示用戶名和密碼。 (與.htaccess樣式相同)express.js或react.js中的通用用戶名/密碼身份驗證

回答

1

根據我的理解,您需要在nodejs中使用http服務器身份驗證。

我知道一個npm模塊。 link

而且它也很容易設置。 基本例如

// 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); 
+0

我會在星期二實施它,但這似乎是正確的答案,並感謝您的鏈接。 .htpasswd格式將是相同的?就像它將有一行用戶名:在這種情況下密碼西蒙:密碼 –

0

如果有人有興趣ES2016做然後按照下面的代碼。設置babel等,使其工作。

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); 
相關問題