I have made a custom exception which should give the message to client when raised. However, that does not seem to be working whenever error code is 401 i.e. UNAUTHORIZED. I tried changing the status code to something else, and message showed up.
Note - I have already set the flag server.error.include-message=always in application.properties
BadCredentialsException.java
@ResponseStatus(value = HttpStatus.UNAUTHORIZED)
public class BadCredentialsException extends RuntimeException{
// Runtime exception just needs this, I guess :/
private static final long serialVersionUID = 1;
public BadCredentialsException(String message){
super(message);
}
}
Here's how I have tried raising the exception.
public ResponseEntity<Boolean> loginUser(String username, String password){
// validating username
User user = myUserRepository.findByUsername(username).
orElseThrow(() -> new ResourceNotFoundException("No username: " + username + " found. Please enter a correct username!"));
// validating password
if(!new BCryptPasswordEncoder().matches(password, user.getPassword())){
throw new BadCredentialsException("Incorrect Password. Please enter correct password to login!");
}
return ResponseEntity.ok(true);
}
Note - message is correctly being displayed in the terminal though. Just not showing up on the client.
UPDATE 1 - I have made this particular endpoint to be accessible by everyone, using permitAll(). In postman, when I select select "no auth" and call this endpoint with expected exception, exception does not give the message unless, I give correct basic auth credentials (any role). I have absolutely no clue why this is happening.
UPDATE 2 - Adding SecurityConfiguration code.
SecurityConfiguration.java
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().
authorizeRequests().
antMatchers(HttpMethod.POST, "/api/v2/user/login/**").permitAll().
antMatchers(HttpMethod.POST, "/api/v2/user/", "/api/v2/user", "/api/v2/user/change-role/**").hasAuthority("ROOT").
antMatchers(HttpMethod.GET, "/api/v2/user/", "/api/v2/user").hasAuthority("ROOT").
antMatchers(HttpMethod.POST, "/api/v1/customers/", "/api/v1/customers").hasAnyAuthority("ADMIN", "ROOT").
antMatchers(HttpMethod.GET, "/api/v1/customers/", "/api/v1/customers").hasAnyAuthority("EMPLOYEE", "ADMIN", "ROOT").
anyRequest().
authenticated().
and().
httpBasic();
}