nodejs mqtt, mosca用户身份验证
kevin.Zhu 发布于:2018-3-22 13:04 分类:文摘 有 20 人浏览,获得评论 0 条
https://github.com/mcollina/mosca/wiki/Authentication-&-Authorization
https://github.com/mcollina/mosca/wiki/Mosca-as-a-standalone-service.#authorization
Using Mosca's standalone authorizer with an embedded Mosca
在mosca的嵌入式应用中使用mosca独立服务的认证方式
If you are using Mosca as embedded broker into your own application, but would still like to make use of its authorization feature with CLI as defined in the Mosca as a standalone wiki page, you may proceed as described below.
First, you should copy the loadAuthorizer()
method out from lib/cli.js
since it is defined as private. Or simply refer to it from below:
var fs = require("fs"); var Authorizer = require("mosca/lib/authorizer"); function loadAuthorizer(program, cb) { if (program.credentials) { fs.readFile(program.credentials, function(err, data) { if (err) { cb(err); return;
} var authorizer = new Authorizer(); try { authorizer.users = JSON.parse(data); cb(null, authorizer);
} catch(err) { cb(err);
}
});
} else { cb(null, null);
}
}
Then add the credentials
setting into your moscaSettings
with the path to your credentials file.
credentials: "config/mqtt_credentials.json"
Finally, setup your authorizer in the setup()
method like below:
function setup() { // setup authorizer loadAuthorizer(moscaSettings, function(err, authorizer) { if (err) { // handle error here } if (authorizer) { server.authenticate = authorizer.authenticate; server.authorizeSubscribe = authorizer.authorizeSubscribe; server.authorizePublish = authorizer.authorizePublish;
}
}); // you are good to go! }