基本アクセス認証
Restify にはauthorizationParser
プラグインがバンドルされています。authorizationParser
をパーサーで出力しAuthorization
ます。プラグインが使用されている場合、プロパティがreq.username
利用req.authorization
可能になります。後者の形式は次のとおりです。
{
scheme: <Basic|Signature|...>,
credentials: <Undecoded value of header>,
basic: {
username: $user
password: $password
}
}
サーバーは、認証が必要なリクエストを選択的にインターセプトし、ユーザー アクセス資格情報を検証する必要があります。
すべての呼び出しに対して認証を必要とするサーバーの例を次に示します。
var restify = require('restify'),
server;
server = restify.createServer();
server.use(restify.authorizationParser());
server.use(function (req, res, next) {
var users;
// if (/* some condition determining whether the resource requires authentication */) {
// return next();
// }
users = {
foo: {
id: 1,
password: 'bar'
}
};
// Ensure that user is not anonymous; and
// That user exists; and
// That user password matches the record in the database.
if (req.username == 'anonymous' || !users[req.username] || req.authorization.basic.password !== users[req.username].password) {
// Respond with { code: 'NotAuthorized', message: '' }
next(new restify.NotAuthorizedError());
} else {
next();
}
next();
});
server.get('/ping', function (req, res, next) {
res.send('pong');
next();
});
server.listen(8080);
テストする最も簡単な方法は、curl を使用することです。
$ curl -isu foo:bar http://127.0.0.1:8080/ping
HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 6
Date: Fri, 12 Dec 2014 10:52:17 GMT
Connection: keep-alive
"pong"
$ curl -isu foo:baz http://127.0.0.1:8080/ping
HTTP/1.1 403 Forbidden
Content-Type: application/json
Content-Length: 37
Date: Fri, 12 Dec 2014 10:52:31 GMT
Connection: keep-alive
{"code":"NotAuthorized","message":""}
Restify には、基本認証をサポートする組み込みの JsonClientが付属しています。
var restify = require('restify'),
client;
client = restify.createJsonClient({
url: 'http://127.0.0.1:8080'
});
client.basicAuth('foo', 'bar');
client.get('/ping', function(err, req, res, obj) {
console.log(obj);
});
OAuth 2.0
トークン認証を希望する場合は、クライアント資格情報認証フローを実装するrestify-oauth2パッケージを使用できます。これが目的です。
ドキュメントページでは、各エンドポイントの役割を含め、そのような認証を設定する方法を段階的に説明しており、リポジトリにはコード例があります.
概要
どの認証方法を選択しても、すべて HTTPS を使用する必要があります。違いは、ユーザー名/パスワードが侵害された場合、ユーザーは資格情報を変更する必要があることです。トークンが侵害された場合、ユーザーは新しいトークンを要求する必要があります。後者はプログラムで実行できますが、前者は通常、ハードコードされた値に依存します。
サイドノート。運用環境では、 Heartbleedなどの SSL バグの場合のように、侵害された HTTPS などの安全でないチャネルを介して少なくとも 1 回転送された場合、資格情報は「侵害された」と見なす必要があります。