You can achieve it by using Spring Security.
Spring Security
A highly customizable framework, Spring Security is widely used to handle the authentication and access control (authorization) issues arising in any Enterprise based application developed in Java.
Ex :
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeRequests().antMatchers("/user/login").permitAll().antMatchers(HttpMethod.OPTIONS)
.permitAll()
.antMatchers(HttpMethod.GET, "/user").hasRole("ADMIN")
.antMatchers(HttpMethod.GET, "/user/list").hasAnyRole("MANAGER", "ADMIN")
.authenticated();
}
}