Team XSockets.NET

MQTT Samples - Authentication

You can do authentication in 2 ways. You can use the VerifyConnection method on the MqttBridge and check the Username and Password from the Mqtt client. However, you can also use the XSockets AuthenticationPipeline module to create a IPrincipal for the connection. Once you have the principal you can use that in all the methods in the MqttBridge to (for example) get role based authentication.

Both ways are described below.

MqttMsgConnect

This method use only the MqttMsgConnect to validate the user.

/// <summary>
/// Verify by using the MqttMsgConnect
/// </summary>
public class MyMqttBride : MqttBridge
{
    public override bool VerifyConnection(MqttMsgConnect message, MqttClient client)
    {
        if (message.Password == "secret4you" && message.Username == "ron-burgundy")
        {
            return true;
        }
        return false;
    }
}

You can set the credentials in the MQTT.fx client under setting/user credentials

Authentication Pipeline

Now we take a look at how to create a IPrincipal to be used in the MqttBridge.

[Export(typeof(IXSocketAuthenticationPipeline))]
public class MyAuthPipeline : IXSocketAuthenticationPipeline
{
    public IPrincipal GetPrincipal(IXSocketProtocol protocol)
    {

        if (protocol.ConnectionContext.User == null)
        {
            //You can access to MQTT connection info like this
            var mqttinfo = (MqttMsgConnect)protocol.ConnectionContext.Environment["mqttclient"];
            if (mqttinfo != null)
                if (mqttinfo.Password == "secret4you" && mqttinfo.Username == "ron-burgundy")
                {
                    //You will find user info on the ConnectionContext
                    //fake, implement your own logic to set the User 
                    var roles = new string[] { "superman", "hulk" };
                    var userIdentity = new GenericIdentity("Run Burgundy");
                    return new GenericPrincipal(userIdentity, roles);
                }
        }

        return protocol.ConnectionContext.User;
    }
}

/// <summary>
/// Verify by using the XSockets AuthPipeline
/// </summary>
public class MyMqttBride : MqttBridge
{
    public override bool VerifyConnection(MqttMsgConnect message, MqttClient client)
    {
        if (client.ConnectionContext.User != null && client.ConnectionContext.User.IsInRole("superman"))
        {
            return true;
        }
        return false;
    }
}

results matching ""

    No results matching ""