Spring Security-多个WebSecurityConfigurerAdapter httpServletResponse.sendError不起作用

时间:2019-08-04 11:40:54

标签: spring spring-boot spring-mvc spring-security

我在我的spring boot项目中设置了多个WebSecurityConfigurerAdapter,并且运行正常。我有一个针对Web请求的安全配置,另一个针对其余请求的安全配置。

我有其他休息要求

http.csrf().disable()
    .antMatcher("/rest/**").authorizeRequests()
    .anyRequest().authenticated()
    .and()
    .addFilterBefore(new CustomFilter(userAuthService), UsernamePasswordAuthenticationFilter.class);

对于我的网络请求,

 http
    .authorizeRequests()
    .antMatchers("/web/**", "/resources/**").permitAll()
    .antMatchers("/", "/login", "/register").permitAll()
    .anyRequest().authenticated()
    .and().formLogin().loginPage("/login").permitAll()
    .and().logout().permitAll();

我的设置正常运行。除了当我使用httpServletResponse.sendError()发送错误时,我被重定向到登录页面,而不是看到错误响应。我的CustomFilter逻辑是

HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
if (myAuthProcess()) {
   setAuthStatus();
   chain.doFilter(request, response);
}
else {
    //httpServletResponse.setStatus(HttpStatus.UNAUTHORIZED.value()); //-- this works. I see an error 401 on the request, but I cannot sent description or error info here
     httpServletResponse.sendError(HttpStatus.UNAUTHORIZED.value(), "token missing"); //--this does not work. It takes me to the login page with status 200 instead of throwing a 401.
}

是的,两个anyRequest().authenticated()中确实都有@Configuration,因为我希望所有URL都得到保护。如何让Spring使用httpServletResponse.sendError引发错误,而不是让我回到登录页面?

0 个答案:

没有答案