Spring Security – need 403 error, not redirect

For java configuration you need to do

http.exceptionHandling().authenticationEntryPoint(alwaysSendUnauthorized401AuthenticationEntryPoint);

Where alwaysSendUnauthorized401AuthenticationEntryPoint is innstance of class

public class AlwaysSendUnauthorized401AuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public final void commence(HttpServletRequest request, HttpServletResponse response,
                               AuthenticationException authException) throws IOException {
        LOGGER.debug("Pre-authenticated entry point called. Rejecting access");
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
    }
}

This disables default behavior of Spring (redirecting unauthenticated requests to login form).

Side note:
for such case HTTP code SC_UNAUTHORIZED(401) is better choice than SC_FORBIDDEN(403).

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)