Question:
If authorization is unsuccessful, I need to return the 401 status. Since our project uses Spring Security
, the authorization setting is configured through it:
@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();
As we can see, I used failureHandler()
to handle the authorization error.
And I wrote a custom handler:
@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);
}
}
Header is sent without problems, but instead of the 401 status, the response is 302. That is, the status I defined is overwritten somewhere. Maybe not need to use sendRedirect
?
Please tell me a working solution within the existing code.
Answer:
In general, it turned out that you can do either redirection with, say, headers, but without HttpStatus
, or add HttpStatus
, but without redirects. So that there is both status and redirection, you cannot do it with Spring Security.
I solved the problem as follows: I created another jsp and changed the line in the settings
.failureHandler(customAuthFailureHandler)
on
.failureUrl(ADMIN_LOGIN_FAILED)
The same can be done with the help of the handler.