I have created self signed certificate using openssl and put generated certificate in the folder and gave the path in the code as well as in the mosquitto.conf file.

I have created a index.js file as follow:

const mqtt = require('mqtt')
const fs = require('fs')
const path = require('path')
const KEY = fs.readFileSync(path.join(\__dirname, 'certs', 'server.key'))
const CERT = fs.readFileSync(path.join(\__dirname, 'certs','server.crt'))
const TRUSTED_CA_LIST = fs.readFileSync(path.join(\__dirname, 'certs','ca.crt'))
const PASSWORD = fs.readFileSync(path.join(\__dirname, 'password', 'passwd_mqtt'))
const USERNAME = 'user1'

const PORT = 8883
const HOST = 'localhost'
const clientId = `mqtt_${Math.random().toString(16).slice(3)}`
const connectUrl = `mqtts://${HOST}:${PORT}`

const options = {
clientId,
clean: true,
port: PORT,
host: HOST,
key: KEY,
cert: CERT,
password: PASSWORD,
username: USERNAME,
rejectUnauthorized: false,
// The CA list will be used to determine if server is authorized
ca: TRUSTED_CA_LIST,
protocol: 'mqtts',
protocolId: 'MQTT',
protocolVersion: 5,
connectTimeout:1000,
debug:true
}

const client = mqtt.connect(connectUrl,options)

client.on('connect', function () {
console.log('Connected')
})

client.on('error', function (error) {
console.log(error)
})
client.subscribe('messages')

client.publish('messages', 'Current time is: ' + new Date())
client.on('message', function (topic, message) {
console.log(message)
})

my mosquitto.conf file is as follow:

listener 8883
allow_anonymous false
require_certificate true
use_identity_as_username true
protocol mqtt
persistence true
allow_zero_length_clientid true
log_type all
connection_messages true
max_connections -1
password_file /Users/mithila/mqtt_node_tls/password/passwd_mqtt
cafile /Users/mithila/mqtt_node_tls/certs/ca.crt
keyfile /Users/mithila/mqtt_node_tls/certs/server.key
certfile /Users/mithila/mqtt_node_tls/certs/server.crt
tls_version tlsv1.2

after running index.js file I am getting following error:

Error: Connection refused: Bad User Name or Password
code: 134

and i am getting error on local mosquito terminal as:

1648034540: Sending CONNACK to mqtt_e32d3293f5b1 (0, 134)
1648034540: Client mqtt_e32d3293f5b1 disconnected, not authorised.

I have created password file using command:

password_file /etc/mosquitto/passwd_mqtt

I have tried all possible solutions given in the various blog like creating user certificate and password file

0

There are 0 answers