WebSecurityConfig:.anyRequest()。authenticated()更改ResponseEntityExceptionHandler的行为

发布时间:2020-07-07 16:27

在WebSecurityConfigurerAdapter类中,我有一种方法可以配置Spring应用程序的HttpSecurity。我还有一个ResponseEntityExceptionHandler类,可以处理所有错误,并返回一个不错的JSON响应,如下所示:

@ControllerAdvice
public class CustomGlobalExceptionHandler extends ResponseEntityExceptionHandler {

    @Autowired
    private Logger logger;

    @ExceptionHandler(ImpossibleRequestException.class)
    public void handleImpossibleRequestExceptions(HttpServletRequest httpServletRequest, Authentication authentication,
                                                  ImpossibleRequestException e, HttpServletResponse response) throws IOException {
        logger.logException(e, authentication, httpServletRequest);
        response.sendError(HttpStatus.BAD_REQUEST.value());
    }
}

但是,问题是如果我像这样配置HttpSecurity。

@Override
protected void configure(HttpSecurity http) throws Exception {

    // Disable CSRF (cross site request forgery)
    http.csrf().disable();

    // No session will be created or used by spring security
    http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

    // Entry points
    http.authorizeRequests()//
            .anyRequest().authenticated();
}

在这种情况下,我的ResponseEntityExceptionHandler的行为已更改。首先,尽管程序跳入了处理ImpossibleRequestException的方法,但它不再发送回json响应,而是仅返回空响应。其次,它返回到引发ImpossibleRequestException的方法。例如:

@GetMapping(value = "/test")
public String test(){
    // Before configuring .anyRequest().authenticated(), program used to stop here
    throw new ImpossibleRequestException("test");
    //Now program stops here.
    return "failed to throw exception";
}

我想将HttpSecurity配置为要求所有请求都经过身份验证,但仍允许由ResponseEntityExceptionHandler类处理异常。我该怎么做?

回答1