I have the below configuration where i need to configure HTTPBasic
authentication for /api/v1/**
endpoints and i want to configure form
authentication for /users/
url pattern. When i run with the below configuration, the configuration for web requests is working correctly but the configuration for API is not working. No security is being applied. Where am I going wrong?
@Configuration
@EnableWebSecurity
public class WebSecurityConfig {
@Order(1)
@Configuration
public static class MVCSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Bean
public BCryptPasswordEncoder getBCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.
antMatcher("/users/**")
.csrf()
.and()
.authorizeRequests()
.antMatchers(
"/resources/**", "/users/register", "/users/signup", "/users/confirm", "/users/user-action", "/users/reset-password", "/confirm", "/webjars/**")
.permitAll()
.antMatchers("/users/**")
.hasRole("USER")
.anyRequest()
.authenticated()
.and()
.formLogin().loginPage("/login").usernameParameter("username").passwordParameter("password");
http
.authorizeRequests()
.antMatchers("/api/v1/users/**")
.hasRole("USER")
.anyRequest()
.authenticated()
.and()
.httpBasic();
}
}
I have put your code to work with this configuration bellow:
@EnableWebSecurity
public class SecurityConfiguration {
public class ApiSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.antMatcher("/api/v1/users/**")
.authorizeRequests().anyRequest()
.hasRole("USER").and().httpBasic();
}
}
@Configuration
@Order(2)
public class MVCSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().and().authorizeRequests()
.antMatchers("/resources/**", "/users/register", "/users/signup", "/users/confirm",
"/users/user-action", "/users/reset-password", "/confirm", "/webjars/**").permitAll()
.antMatchers("/users/**").hasRole("USER")
.and()
.formLogin().usernameParameter("username").passwordParameter("password");
}
}
}
View docs for Spring Security and sample code here.