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).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…