Describe the bug Requests that have the header "X-Requested-With: XMLHttpRequest" (correctly) return HTTP 401.

However, requests that have the Accept header set to any value other than those listed at https://github.com/spring-projects/spring-security/blob/5.4.5/config/src/main/java/org/springframework/security/config/annotation/web/configurers/AbstractAuthenticationFilterConfigurer.java#L256 should also result in an HTTP 401. Currently, however, they are responded to with a 302 redirect to the login page.

See also https://github.com/spring-projects/spring-security/issues/6812

To Reproduce Here's a test that can be added to OAuth2LoginConfigurerTests demonstrating the problem:

    @Test
    public void oauth2LoginWithOneClientConfiguredAndRequestAcceptJSONNotAuthenticatedThenDoesNotRedirectForAuthorization()
            throws Exception {
        loadConfig(OAuth2LoginConfig.class);
        String requestUri = "/";
        this.request = new MockHttpServletRequest("GET", requestUri);
        this.request.setServletPath(requestUri);
        this.request.addHeader("Accept", MediaType.APPLICATION_JSON);
        this.springSecurityFilterChain.doFilter(this.request, this.response, this.filterChain);
        assertThat(this.response.getStatus()).isEqualTo(401);
        assertThat(this.response.getRedirectedUrl()).doesNotMatch("http://localhost/oauth2/authorization/google");
    }

Expected behavior Requests with the Accept header set to application/json (for example) should receive an HTTP 401 response.

Sample I've provided a unit test so hopefully that's acceptable in place of a full sample project.

Comment From: jgrandja

@candrews See comment

Comment From: jgrandja

@candrews Closing as per comment.

Comment From: jgrandja

@candrews See this test and associated config for configuring oauth2Login() with a custom AuthenticationEntryPoint for handling XHR requests.