Here’s my simple requirements:
- /admin/** path require ROLE_ADMIN
- /login/**, /css/**, /js/**, **/favicon.ico can be accessed anonymously
- any other path required ROLE_USER
- login form
Here’s how to implement it on your Spring Boot project:
- Add the spring boot security starter dependency:
org.springframework.boot spring-boot-starter-security - Add a SecurityConfig class extending WebSecurityConfigurerAdapter and implement the path, user and roles requirements above
(SecurityProperties.ACCESS_OVERRIDE_ORDER) public class SecurityConfig extends WebSecurityConfigurerAdapter { protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/admin/**").hasRole("ADMIN") .antMatchers("/css/**", "/js/**", "/img/**", "**/favicon.ico").anonymous() .anyRequest().hasRole("USER") .and() .formLogin() .permitAll() ; } public void configure(AuthenticationManagerBuilder auth) throws Exception { auth .inMemoryAuthentication() .withUser("admin").password("admin321").roles("USER", "ADMIN").and() .withUser("jim").password("jim321").roles("USER"); } }
This setup only works assuming you have on your main configuration class. By default Spring Security will provide a login form at /login but you can implement your own. I’ve also setup two users to test it