为restify.js实现基于令牌的身份validation的最佳方式是什么?

我正在尝试使用restify.js构build一个RESTful API,但我不想将API暴露给所有人。 我将使用基于令牌的身份validation。 我脑海中的过程就是这样,我不确定这是否合理。

  1. 用户发送用户名/密码到一个API来获取令牌。

  2. 这个令牌应该包含在每个其他API调用的请求中。

如果这是合理的,是否有任何node.js库我可以使用?

另外,我如何保护令牌? 如果有人用令牌拦截了一个http请求,那么这个人将得到api URL和令牌。 然后他可以根据需要发送请求。 有没有办法避免这种情况?

非常感谢!

基本访问validation

Restify与一个authorizationParser插件捆绑在一起。 authorizationParserparsing出Authorization 。 当插件正在使用时,它将使req.usernamereq.authorization属性可用。 后者的格式是:

 { scheme: <Basic|Signature|...>, credentials: <Undecoded value of header>, basic: { username: $user password: $password } } 

您的服务器将需要select性地拦截需要身份validation的请求并validation用户访问凭据。

这是一个示例服务器,将要求所有呼叫的身份validation:

 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); 

最简单的testing方法是使用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带有内置的支持基本authentication的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

如果您更喜欢令牌authentication,那么您可以使用实现客户端凭证authenticationstream程的restify-oauth2软件包,这就是您所要做的。

文档页面逐步介绍了如何设置这种authentication,包括每个端点的angular色,并且在他们的存储库中有一个代码示例 。

概要

无论您select哪种身份validation方法,都需要您使用HTTPS。 不同的是,如果用户名/密码被盗用,用户将需要更改他们的凭据。 如果令牌受到威胁,则用户需要请求新的令牌。 后者可以以编程方式完成,而前者通常依赖于硬编码值。

边注。 在生产环境中,如果通过不安全的渠道(如HTTPS泄露)至less一次传输证书,则证书必须被视为“受到威胁”,例如Heartbleed等SSL漏洞。