先にNode.jsをインストール
Node.jsをインストール - MBP(はてな)
server.js
var http = require("http"); var basic_name = "simple-nodejs_member"; var basic_users = ["QWxhZGRpbjpvcGVuIHNlc2FtZQ=="]; function isUser(_auth) { for (var l=0; l<basic_users.length; l++) { if (basic_users[l] == _auth) { return true; } } return false; } var server = http.createServer(function (req, res) { var auth = req.headers["authorization"]||""; if (!auth.startsWith("Basic ") || !isUser(auth.substring(6))) { res.statusCode = 401; res.setHeader('WWW-Authenticate', 'Basic realm="' + basic_name + '"'); res.end(); } if (!res.finished) { res.writeHead(200, {"Content-Type": "text/plain"}); res.end("hello, Node.js world!"); } }); var port = process.env.PORT || 3000; server.listen(port, function() { console.log("To view your app, open this link in your browser: http://localhost:" + port); });
$ node server.js
safariでhttp://localhost:3000を開くと、ユーザー名とパスワードを入力する画面が表示される。
ユーザ名 "Aladdin"、パスワード "open sesame"
$ curl http://localhost:3000/ \ -H "accept: application/json" \ -H "Authorization:Basic $(echo -n Aladdin:open sesame | openssl base64)"
すると、
hello, Node.js world!%curl: (6) Could not resolve host: が表示される
Docker Basic認証 Webサーバ - MBP(はてな)