mqtt雙向ssl認證

const mosca = require('mosca');
const tls = require('tls');
var mqttconfig=require('../config/mqtt_config/mqtt_config').config;
//var dataParse = require('./dataParse');


var CAFILE = '../ssl-file/cert_mesh_mqtts_100y_sha256/ca.crt';  		
var SECURE_KEY = '../ssl-file/cert_mesh_mqtts_100y_sha256/server.key.insecure';
var SECURE_CERT = '../ssl-file/cert_mesh_mqtts_100y_sha256/server.crt';


var sslsetting = {
	port: 1883,
	logger:{
		name:"secureExample",
		level:40,
	},
	secure :{
		port: 9883,
		keyPath: SECURE_KEY,
		certPath: SECURE_CERT,
		caPaths: [CAFILE],  //ca could have lots,so this place should use array.
		requestCert: true,
	}
};


var server = new mosca.Server(sslsetting);    //connect client 
var clientId;
//var packetMessage;

server.on('clientConnected', function(client) {
    console.log('client connected ! cilent id :', client.id);
	clientIdclientId=client.id;
});


server.on('published', function(packet,client) 
{
});

server.on('message', function (topic, message) {
});

// Accepts the connection according to some conditions
var authenticate = function(client, username, password, callback) {
    //console.log('client:',client.id);
    //console.log('username:',username);
    //console.log('password:',password);
    callback(null, true);
}

// Accepts the Publish according to some conditions
var authorizePublish = function(client, topic, payload, callback) {
    //console.log('pub:',client.id.indexOf("/server/xiaofu968343"), (client.id.indexOf("/server/xiaofu968343") == 0), (topic.indexOf("/server/") == 0));
    callback(null, ((client.id.indexOf(mqttconfig.server_id) == 0) || (topic.indexOf("/server/") == 0)));
}

// Accepts the Subscribe according to some conditions
var authorizeSubscribe = function(client, topic, callback) {
    //console.log('client:',client.id);
    //console.log('client:',client.user);
    //console.log('topic:',topic);
    //callback(null, client.user == topic.split('/')[1]);
    callback(null, true);
}

server.on('ready', setup);
// fired when the mqtt server is ready
function setup() {
    console.log('Welcome to MESH server using MQTT!');
    console.log('2018.5.19  14.50                                                              ');
    //server.authenticate = authenticate;
    server.authorizePublish = authorizePublish;
    //server.authorizeSubscribe = authorizeSubscribe;
}


展开阅读全文

没有更多推荐了,返回首页