The problem is as follows. I implemented the login through Keycloak Bearer Spring security like this
public class KeycloakSecurityConfiguration extends KeycloakWebSecurityConfigurerAdapter {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
KeycloakAuthenticationProvider keycloakAuthenticationProvider = keycloakAuthenticationProvider();
keycloakAuthenticationProvider.setGrantedAuthoritiesMapper(new SimpleAuthorityMapper());
auth.authenticationProvider(keycloakAuthenticationProvider);
}
@Override
public void configure(HttpSecurity http) throws Exception {
super.configure(http);
http.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.sessionAuthenticationStrategy(sessionAuthenticationStrategy())
.and()
.csrf().disable()
.addFilterBefore(keycloakPreAuthActionsFilter(), LogoutFilter.class)
.addFilterBefore(keycloakAuthenticationProcessingFilter(), X509AuthenticationFilter.class)
.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint())
.and()
.authorizeRequests().antMatchers(Constants.API_BASE_PATH + "/**").authenticated();
}
}
, when I send the Authorization request header empty, keycloak throws error 401. Which I cannot catch through @ExceptionHandler like this :
@ExceptionHandler(RuntimeException.class) protected ResponseEntity keycloakAuthenticationExceptionn(RuntimeException ex) { return buildResponseEntity(new ErrorResponseWrapper(BAD_REQUEST,new MessageResponse(ex.getLocalizedMessage()),ex,ErrorCode.NOT_AUTHORIZED)); } .