javaspringservletsjava-melody

How to add security for Java Melody Monitor URL in spring application


We are using Java Melody in spring application. I would like to add security to access /monitoring url only by admin user. I have to check some property value and permissions based on that one should get access.

What are the different approaches available to achieve this? Can we do it in spring security?

Please let me know if I need to provide any additional information here.


Solution

  • You can use javamelody parameters authorized-users for http basic auth or allowed-addr-pattern for access based on ip address. See https://github.com/javamelody/javamelody/wiki/UserGuide#16-security

    For example in application.yml, if you use Spring-boot:

    javamelody:
      init-parameters:
        authorized-users: admin:password
    

    Or you can use Spring security with .antMatchers("/monitoring").hasRole("ADMIN").

    For example in Spring-boot 2, using spring-boot-starter-security dependency, basic auth and in memory user's storage:

    import org.springframework.context.annotation.Bean;
    import org.springframework.security.config.annotation.web.builders.HttpSecurity;
    import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
    import org.springframework.security.core.userdetails.User;
    import org.springframework.security.core.userdetails.UserDetails;
    import org.springframework.security.core.userdetails.UserDetailsService;
    import org.springframework.security.provisioning.InMemoryUserDetailsManager;
    
    @Configuration
    @EnableWebSecurity
    public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.httpBasic().and().authorizeRequests().antMatchers("/monitoring").hasRole("ADMIN")
                    .anyRequest().permitAll();
        }
    
        @Bean
        @Override
        public UserDetailsService userDetailsService() {
            UserDetails user = User.withDefaultPasswordEncoder().username("user").password("password")
                    .roles("USER").build();
            UserDetails admin = User.withDefaultPasswordEncoder().username("admin").password("password")
                    .roles("ADMIN").build();
    
            return new InMemoryUserDetailsManager(user, admin);
        }
    }
    

    If you use Spring security without Spring boot, be sure to put the Spring Security filter before the javamelody Monitoring filter in your web.xml file.