Express:一个路由的基本authentication

我正在尝试制作一组​​工具来访问我的数据库。 大多数是通过我的web应用程序访问数据,但我也需要一个页面,我的快速动力站点的密码为网站所有者提供一个在线工具来编辑数据库; 所有其他路由将不需要身份validation。

使用express 3, basic-auth很容易添加这样一个密码,但是它的function已经被Express 4中的中间件和大多数在线教程所淘汰。 basic-auth的新版本将处理authentication标题信息,但是如何在浏览器中触发loginpopup窗口呢?

下面的代码只不过是样板,所以对于世界上最简单的login提示一些提示是值得欢迎的。

 express = require('express') app = express() auth = require 'basic-auth' port = Number(process.env.PORT || 9778); app.listen port, () -> console.log "Listening on port: " + port app.use '/editor', (req, res) -> user = auth req if (user == "....") ... console.log user app.get '/editor', (req, res) -> # if authenticated send 'editor.html' else.... res.send 401, "Need password" 

目前我添加身份validation访问页面,然后允许该页面发布到CRUD节点。 我想我应该真的转向一个适当的REST API并要求在CUD上进行身份validation?

根据基本authentication规范,服务器可以通过发送带有401状态代码的WWW-Authenticate头来请求authentication。 以下为我工作:

 res.set({ 'WWW-Authenticate': 'Basic realm="simple-admin"' }).send(401); 

我把自己的中间件看起来像这样:

 var auth = require('basic-auth'); module.exports = function(req, res, next){ var user = auth(req); if(validAuth){ // Here you need some logic to validate authentication next(); } else { res.set({ 'WWW-Authenticate': 'Basic realm="simple-admin"' }).send(401); } }; 

基于@JustinY这是最终的结果

 app.use '/editor', (req, res, next) -> user = auth req if (user.pass == '******') console.log user next() else res.set 'WWW-Authenticate': 'Basic realm="simple-admin"' res.send 401, "Need password" app.get '/editor', (req, res) -> res.sendfile 'editor/index.html'