0

I am using mqtt paho javascript client library to connect to an mqtt server,i am able to connect to server with username and password, now the issue is ...how can i warn user if he gives wrong username or password.i followed this link is there any onFailure function to report an error if user credentials are wrong??

client.connect({onSuccess:this.onConnect.bind(this),userName:Name,password:Password},{onFailure:console.log("failed")});



  onConnect() {
  // Once a connection has been made, make a subscription and send a message.
  console.log("onConnect");
  
  }

even though I am able to connect , I can see but "onConnect" and "failed" messages in my console

Lisa
  • 655
  • 3
  • 10
  • 34

3 Answers3

0

You need to read the Connect Return code field that the Broker will bring you

there is a list of constants defined in the protocol:

the one you are looking for is:

0x04 Connection Refused, bad user name or password

other values specified are:

0x00: Connection Accepted

0x01: Connection Refused

0x02: Connection Refused

0x03: Connection Refused

0x04: Connection Refused

0x05: Connection Refused, not authorized

from 6-255: Reserved for future use

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
  • could you please provide a sample how to read the Connect Return code field that the Broker is bringing . – Lisa Mar 24 '17 at 06:20
0

Taken from the docs here

The Paho connect method takes an options parameter which includes a onFailure callback function which will include an error code for a authentication failure:

client.connect({
  onFailure: function(err) {
    if (err.errorCode == 0x4) {
      //bad user/password
    }
  }
});
hardillb
  • 54,545
  • 11
  • 67
  • 105
  • client.connect({ onFailure: function(err) { if (err.errorCode == 0x4) { //bad user/password } }, {onSuccess:this.onConnect.bind(this),userName:"user",password:"123"}}); – Lisa Mar 23 '17 at 12:22
  • I used the above code but i didn't get any error msg – Lisa Mar 23 '17 at 13:00
  • That code won't show you an error, it just shows you where to handle the error, you have to add that bit yourself – hardillb Mar 23 '17 at 13:09
  • i wrote " console.log(err); " in onFailure function ,but couln't see anything in console – Lisa Mar 23 '17 at 13:23
0

connect method takes connectionOptions as parameters so ,you can give options like onSuccess,onFailure,userName,password. A single response object parameter is passed to the onFailure callback that has fields like errorCode ,errorMessage.

client.connect({onSuccess:this.onConnect.bind(this),
userName:uName,
password:uPassword,
onFailure:this.onFailure.bind(this)
});
onConnect() {
  // Once a connection has been made, make a subscription and send a message.
  console.log("onConnect");
     }
onFailure(responseObject){
  console.log("you have no access to the connnection!!!");
  console.log(responseObject);
 }
hardillb
  • 54,545
  • 11
  • 67
  • 105
Lisa
  • 655
  • 3
  • 10
  • 34