如何在 HiveMQ 的 PublishInboundInterceptor 中获取客户端用户名

How to get client username in PublishInboundInterceptor in HiveMQ

在 PublishInboundInterceptor 中,我可以获取客户端 ID,然后我想我可以使用 ClientService 获取用户名,但我失败了。

有没有办法获取客户端用户名和密码?

PublishInboundInterceptor 中没有现成的方法来获取 username/password。您必须通过 SimpleAuthenticator、EnhancedAuthenticator 或 ClientLifecycleEventListener#onMqttConnectionStart 获取凭据,然后将它们存储在 ConnectionAttributeStore 中(这是每个客户端自己拥有的存储,并存储在客户端断开连接时删除的属性)。

我举了一个例子来展示这一点:

// use a SimpleAuthenticator to store username/password (if they are set by the client) in the connection attribute store of the client
// other options to fetch username/password: ClientLifecycleEventListener#onMqttConnectionStart or EnhancedAuthenticator
Services.securityRegistry().setAuthenticatorProvider(providerInput ->
        (SimpleAuthenticator) (simpleAuthInput, simpleAuthOutput) -> {
            final ConnectionAttributeStore connectionAttributeStore = simpleAuthInput.getConnectionInformation().getConnectionAttributeStore();
            final ConnectPacket connectPacket = simpleAuthInput.getConnectPacket();

            connectPacket.getUserName().ifPresent(username -> connectionAttributeStore.put("username", ByteBuffer.wrap(username.getBytes(StandardCharsets.UTF_8))));
            connectPacket.getPassword().ifPresent(password -> connectionAttributeStore.put("password", password));
        });

// in the publish inbound interceptor fetch username/password from the connection attribute store (check optional if they are set)
Services.initializerRegistry().setClientInitializer((initializerInput, clientContext) ->
        clientContext.addPublishInboundInterceptor(
                (publishInboundInput, publishInboundOutput) -> {
                    final Optional<String> usernameOptional = publishInboundInput.getConnectionInformation().getConnectionAttributeStore().getAsString("username");
                    final Optional<@Immutable ByteBuffer> passwordOptional = publishInboundInput.getConnectionInformation().getConnectionAttributeStore().get("password");

                    //happy coding
                }
        )
);

希望对您有所帮助!