Spring Security 重定向到登录表单而不是返回状态 401

sta*_*mis 5 spring-security spring-boot

我需要 Spring 返回未经授权的(状态 401)而不是将用户重定向到登录页面。原因是我正在做一个 SPA 应用程序后端,它已经内置了用于在收到 http 状态代码 401 时进行重定向的机制。我正在使用的 Spring Boot 版本是 1.3.0,但我也用 1.4.1 尝试过,但仍然遇到同样的问题。

我的安全配置是:

@Configuration
@EnableWebSecurity
@EnableRedisHttpSession
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    AuthenticationProvider authenticationProvider;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
             .antMatchers("/loginPath").permitAll()
                .anyRequest().authenticated()
                .and()
                .exceptionHandling().authenticationEntryPoint(
                (request, response, authException) -> response.sendError(HttpServletResponse.SC_UNAUTHORIZED))
                .and()
                .formLogin().loginPage("/loginPath")
                .successHandler(loginSuccessHandler()).permitAll()
                .and()
                .logout().deleteCookies("SESSION").permitAll()
                .and()
                .authenticationProvider(authenticationProvider)
                .csrf().disable()
                .httpBasic().disable();
    }
...
}
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助。

编辑

“/error”有一个视图控制器映射,可以将用户重定向到分配了最高优先级的登录页面。当它被删除时,一切都按预期工作。 似乎 Spring Security 会返回 401 和 /error 作为视图,但由于重定向配置和更高的优先级,它会被覆盖。