Вы можете создать собственную реализацию этого интерфейса для изменения ответа - AuthenticationFailureHandler
@Component
public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler
{
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
AuthenticationException ex) throws IOException, ServletException
{
response.setStatus(HttpStatus.UNAUTHORIZED.value());
Map<String, Object> data = new HashMap<>();
data.put("timestamp", Calendar.getInstance().getTimeInMillis()); // you can format your date here
data.put("status",HttpStatus.UNAUTHORIZED.value());
data.put("message", "You are not authorized.");
data.put("path", request.getRequestURL().toString());
OutputStream out = response.getOutputStream();
com.fasterxml.jackson.databind.ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(out, data);
out.flush();
}
}
Вам необходимо настроить этот класс CustomAuthenticationFailureHandler.java
.
@Configuration
@EnableWebSecurity
@ComponentScan("your.base.package")
public class WebSecurityConfig extends WebSecurityConfigurerAdapter
{
@Override
protected void configure(final HttpSecurity http) throws Exception {
http.exceptionHandling().accessDeniedHandler(accessDeniedHandler())
;
}
@Bean
public AccessDeniedHandler accessDeniedHandler() {
return new CustomAuthenticationFailureHandler();
}
}