I am trying to practice spring security and this is my spring security configuration
@Configuration
@EnableWebSecurity
public class ProjectConfig extends WebSecurityConfigurerAdapter {
@Autowired
AuthenticationProvider authenticationProvider;
@Autowired
AuthenticationManagerBuilder builder;
@Bean
public AuthenticationManager global() throws Exception {
builder
.inMemoryAuthentication()
.passwordEncoder(NoOpPasswordEncoder.getInstance())
.withUser("admin")
.password("123")
.authorities(() -> "ADMIN");
return builder.build();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.antMatcher("/hello")
.authorizeRequests()
.anyRequest()
.authenticated();
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authenticationProvider);
auth.parentAuthenticationManager(global());
}
}
and this is my custom authentication provider:
@Component
public class CustomProvider implements AuthenticationProvider {
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
return BadCredentialsException("error");
}
@Override
public boolean supports(Class<?> authentication) {
return true;
}
}
I read about how we can create a parent for authentication manager and tried to test it. every time I make a request using Postman I get 403 error. what is wrong with my configuration? Postman
CodePudding user response:
First Spring uses ProviderManager
class as the implementation of AuthenticationManager
interface and if you see the implementation of the authenticate
method you figure out that it only uses parent authentication manager if the child result is null
not exception
in your case.
if (result == null && this.parent != null) {
// Allow the parent to try.
try {
parentResult = this.parent.authenticate(authentication);
result = parentResult;
}
// other stuff
}
so change the following code in CustomProvider
to returns null
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
return AuthenticationException("error");
}
also from the image I noticed you are using http basic authentication but you didn't enable it in your configuration.
http
.antMatcher("/hello")
.authorizeRequests()
.anyRequest()
.authenticated()
.and()
.httpBasic();