我需要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();
}
...
}
感谢您的帮助。
修改
有一个视图控制器映射“/ error”将用户重定向到分配了最高优先级的登录页面。 删除后,一切都按预期工作。 看起来Spring Security会将401和/ error作为视图返回,但由于重定向配置和更高的优先级,它会被覆盖。