我目前正在使用 NodeJS 和 restify 开发 RESTful Web 服务.
我已使用 node-mysql 为数据库启动并运行所有内容,但我还想实现 HTTP 基本身份验证。
我只用 Apache 和一个 .htaccess
文件做了一次。
但是这里的网络服务器带有 restify,我这样启动它:
var server = restify.createServer({
name: 'my webservice'
});
restify 文档 (http://mcavage.me/node-restify/#Bundled-Plugins) 中列出了一个身份验证解析器插件,但我不知道如何使用它。
req.username
值始终设置为匿名,即使我使用 http://user:pass@url...
。
如果我可以将它与 .htpasswd
文件一起使用来存储/访问用户并通过。
有谁知道如何用 restify 或其他模块实现这个?
最佳答案
最后我找到了一种不需要任何额外模块的方法。
首先我发送正确的标题:
var auth = req.headers['authorization'];
res.statusCode = 401;
res.setHeader('WWW-Authenticate', 'Basic realm="Secure Area"');
res.end('need creds');
然后我检查用户并通过,如果没问题则发送正确的状态码
res.statusCode = 200; // OK
如果密码不正确:
res.statusCode = 401; // Force them to retry authentication
res.setHeader('WWW-Authenticate', 'Basic realm="Secure Area"');
res.end('<html><body>You shall not pass</body></html>');
这很好用。我只是在阅读 .htpasswd 和加密密码时遇到了一些麻烦。 有谁知道如何根据 .htpasswd 文件检查普通密码?
关于javascript - 使用 Node.js 和 restify 进行基本身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22992094/