javarabbitmqvirtualhostresttemplate

Cannot add a user to a default virtual host in RabbitMQ


I want to add a user to a default / virtual host in RabbitMQ using REST API.

I am executing a following endpoint:

PUT http://localhost:15672/api/permissions/%2F/user.name and I am getting:

400 Bad Request: "{"error":"bad_request","reason":"vhost_or_user_not_found"}"

%2F is encoded default virtual host name: /.

The virtual host / exists in the RabbitMQ:

enter image description here

It is also interesting, because when I execute the same endpoint but with different virtual host name, it works:

http://localhost:15672/api/permissions/ble/user.name

Do you have any ideas?

Thank you.


Solution

  • The problem is that RestTemplate is encoding your url. This means that the %2F will be further encoded when the request is sent making it unrecognizable to rabbitMQ.

    In order to avoid this you can use the DefaultUriBuilderFactory to force the RestTemplate to not encode the url.

    DefaultUriBuilderFactory uriBuilderFactory = new DefaultUriBuilderFactory();
    uriBuilderFactory.setEncodingMode(DefaultUriBuilderFactory.EncodingMode.NONE);
    restTemplate.setUriTemplateHandler(uriBuilderFactory);
    
    restTemplate.exchange(
      rabbitBaseUrl + "/api/permissions/%2F/" + username,
      HttpMethod.PUT,
      new HttpEntity<>(permissionsObjectNode, headers),
      Void.class
    );