varoptions=newConnectionOptionsBuilder().WithTCP("test.mosquitto.org",1884).Build();client=newMQTTClient(options);client.BeginConnect(ConnectPacketBuilderCallback);privateConnectPacketBuilderConnectPacketBuilderCallback(MQTTClientclient,ConnectPacketBuilderbuilder){// Add username and password to the connect packetreturnbuilder.WithUserNameAndPassword("rw","readwrite");}
For those cases where only the username or password needed, the .WithUserName and .WithPassword functions can be used.
With MQTT v5 there are two new functions available to do authentication in the ConnectPacketBuilder, WithExtendedAuthenticationMethod and WithExtendedAuthenticationData:
client=newMQTTClientBuilder().WithOptions(options).WithEventHandler(OnAuthenticationCallback).CreateClient();privatevoidOnAuthenticationCallback(MQTTClientclient,AuthenticationMessagemessage){switch(message.ReasonCode){// Successfully authenticatedcaseAuthReasonCodes.Success:break;// Server requires re-authentication of the client.caseAuthReasonCodes.ReAuthenticate:stringtoken="<new token>";client.CreateAuthenticationPacketBuilder().WithReasonCode(AuthReasonCodes.ContinueAuthentication).WithAuthenticationMethod("Bearer").WithAuthenticationData(System.Text.Encoding.UTF8.GetBytes(token)).BeginAuthenticate();break;// Server needs more datacaseAuthReasonCodes.ContinueAuthentication:break;}}