При неудачной авторизации мне нужно вернуть статус HTTP 401. Я использую Spring Security и следующую авторизацию установки:
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatcher(ADMIN_MATCHERS)
.authorizeRequests()
.antMatchers(ADMIN_MATCHERS)
.access("hasRole('ADMIN')")
.anyRequest().authenticated()
.and()
.formLogin()
.usernameParameter(USERNAME)
.passwordParameter(PASSWORD)
.loginPage(ADMIN_LOGIN)
.permitAll()
.loginProcessingUrl("/admin/login/auth")
.failureHandler(customAuthFailureHandler)
.successHandler(successHandler())
.and()
.logout()
.logoutUrl("/admin/logout")
.logoutSuccessUrl(ADMIN_LOGIN)
.and()
.exceptionHandling()
.accessDeniedPage(ADMIN_LOGIN)
.and()
.csrf().disable()
.httpBasic();
Я использую failureHandler()
, чтобы справиться с этим.
Я написал собственный обработчик:
@Component("customAuthFailureHandler")
public class CustomAuthFailureHandler extends SimpleUrlAuthenticationFailureHandler {
private static final String ADMIN_LOGIN = "/admin/login";
private static final Integer STATUS_UNAUTHORIZED = 401;
private static final String RESPONSE_CODE_KEY = "Response-Code";
private static final String RESPONSE_BAD_CREDENTIALS = "bad-credentials";
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
response.setStatus(STATUS_UNAUTHORIZED);
response.addHeader(RESPONSE_CODE_KEY, RESPONSE_BAD_CREDENTIALS);
getRedirectStrategy().sendRedirect(request, response, ADMIN_LOGIN);
}
}
Заголовок возвращает OK, но со статусом 302 вместо 401.