title: Spring Security: how to change HTTP Status for response?
body: <p>On unsuccessful authorization I need to return HTTP 401 status. I use Spring Security and the following setup authorization:</p>
  
  <pre><code>        @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();
  </code></pre>
  
  <p>I use <code>failureHandler()</code> to handle it.</p>
  
  <p>I wrote a custom handler:</p>
  
  <pre><code>@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);
      }
  }
  </code></pre>
  
  <p>Header returns OK, but with status 302 instead of 401.</p>