I have a spring boot application where I want to secure different endpoints with different credentials. I think roles are the best (only?) way to implement this and have written:
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
private static final String ROLE_1 = "role1";
private static final String ROLE_2 = "role2";
@Autowired
private MyBasicAuthenticationEntryPoint authenticationEntryPoint;
@Override
protected void configure(final AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user1").password(passwordEncoder().encode("user1Pass")).roles(ROLE_1)
.and()
.withUser("user2").password("user2Pass").roles(ROLE_2);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeRequests().antMatchers("/endpoint1").hasRole(ROLE_1)
.antMatchers("/endpoint2").hasRole(ROLE_2)
.antMatchers("/").permitAll().and().httpBasic()
.authenticationEntryPoint(authenticationEntryPoint);
http.headers().frameOptions().disable();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
But when I call either endpoint (with the credentials from configure
) I get 401 Unauthorized
. Why are the credentials I specify in configure
not accepted?