Authorization In HiveMQ Using Extension


In the previous blog, we discussed adding authentication in a HiveMQ extension project. Now to move forward, In this blog, we will learn how to do a custom authorization in HiveMQ using the extension.

First, we need to have a basic project for the HiveMQ extension. If we don’t have one we can create our own basic project as discussed in How to create a custom HiveMQ extension?

To understand why we need authorization in HiveMQ we can take a scenario below:

In our HiveMQ project, the user should publish messages with predefined algorithms. If the messages aren’t encrypted, the broker should discard the packet.

By default, MQTT does not provide any way to authorize data. We can achieve the same by using the custom extension.

The steps to create our own custom extension :

  • First we create a new java class MyPublishAuthorizer and implement PublishAuthorizer
Authorization In HiveMQ Using Extension
  • Add below method, which will call method to decrypt or check that message published by the client is valid or not
public Boolean isValidMsg(String payload) {
		//implement your custom logic or decrypt payload to check message is valid or not?
		
		return false;
	}
  • We have to add the below code inside the authorizePublish method:
try {
final PublishPacket publishPacket = publishAuthorizerInput.getPublishPacket();        
String clientID = publishAuthorizerInput.getClientInformation().getClientId().toString();
        String msg = publishAuthorizerInput.getPublishPacket().getPayload().toString();


        if (isValidMsg(msg)) {
            publishAuthorizerOutput.authorizeSuccessfully();
        } else {
            publishAuthorizerOutput.failAuthorization();
        }
    } catch (Exception ex) {
        System.out.println("Exception");
    }
Authorization In HiveMQ Using Extension
  • Next we have to create a new java class which implements AuthorizerProvider and then add the below code:
return new MyPublishAuthorizer();
Authorization In HiveMQ Using Extension
  • Lastly we have to add the code given below inside the extensionStart method of the main class:
Services.securityRegistry().setAuthorizerProvider(new MyAuthorizerProvider());
Authorization In HiveMQ Using Extension

The broker will check and decrypt each and every message which will reduce the slight performance in real-time based on your processing logic on the message.

In the next blog, we will learn about monitoring HiveMq in Grafana. Stay tuned!

Leave A Comment

Your email address will not be published. Required fields are marked *