Search code examples
springspring-bootspring-jmx

how to set authentication credentials for JMX in spring boot?


I have enabled JMX in my spring boot application. I am able to set/get properties on using Jconsole. I want to add authentication (username/password) for connecting to the MBeanServer. I prefer annotation based if possible.

Here is my JMXBean.

@ManagedResource(objectName = "Examples:type=JMX,name=Resource")
public class Resource {
    List<String> items = new ArrayList<>();

    @ManagedAttribute
    public String getLastItem() {
        return items.get(getSize()-1);
    }

    @ManagedAttribute
    public int getSize() {
        return items.size();
    }

    @ManagedOperation
    public void addItem(String item) {
        items.add(item);
    }

    @ManagedOperation
    public String getItem(int pos) {
        return items.get(pos);
    }

    @ManagedOperation
    public List<String> getItems() {
        return items;
    }


}

Currently I do not have any XML configuration.

I have the bean initialized in my configuration

@Configuration
@EnableAutoConfiguration
@ComponentScan
public class Application extends SpringBootServletInitializer {

    public static void main(final String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Override
    protected final SpringApplicationBuilder configure(final SpringApplicationBuilder application) {
        return application.sources(Application.class);
    }

    @Bean
    public Resource jmxResource() {
        return new Resource();
    }
}

Solution

  • To enable remote JMX access, you need to start your Spring Boot application with the following JVM parameter:

    -Dcom.sun.management.jmxremote.port=<port>
    

    To configure file-based password authentication, add the following parameter:

    -Dcom.sun.management.jmxremote.password.file=<file>
    

    There are two predefined users: monitorRole and controlRole. By default, the former has only read access, the latter may also write (see $JRE_HOME/lib/management/jmxremote.access). Use jmxremote.password.template in $JRE_HOME/lib/management as a template for the password file and stick to those usernames. For example:

    monitorRole <password>
    controlRole <password>
    

    Log in using either of those usernames and the password you specified.

    Be advised that when using this method, passwords are stored in plain text and it is not recommended for production use. See the documentation on how to set up authentication using SSL client certificates or LDAP.