在身份验证期间抛出并处理自定义异常 Spring 安全 + WebFlux

Throw and handle custom exception during authentication Spring Security + WebFlux

我试图在身份验证期间在 WebFlux 中抛出自定义异常,并使用 ControllerAdvice (@ExceptionHandler) 处理它。不幸的是,它没有传播,如果我抛出异常,我会得到 HTTP 500,如果我 return 作为 Mono.error()

的异常,我会得到 HTTP 401
@Override //in authentication service
public Mono<UserDetails> findByUsername(String username) {
    //find user by username from database, 
    //if not enabled, throw a custom exception, 
    //if doesn't exist, throw UsernameNotFoundException, 
    //return org.springframework.security.core.userdetails.User otherwise.
}

@ExceptionHandler //in controller advice
public Mono<HttpStatus> handleException(MyCustomExceptionThrownFromFindByUsername ex) {
    //implemented
}

有什么方法可以帮助异常进入 ExceptionHandler 吗?

UserDetailsService(两者都是 reactive and non-reactive) has as a job to retrieve the user based on the username. Nothing more and nothing less. Checking if the user is enabled is delegated to a UserDetailsChecker,它调用 UserDetails 实现上的一些方法,并会做出相应的反应。不要尝试在这里做更多,因为那不是UserDetailsService.

的任务

默认的 UserDetailsUser 实现有 2 个构造函数,一个有 3 个参数,一个有 7 个参数。使用第二个根据您的业务规则正确填写 enabled,Spring 安全部门将按照应有的方式完成其余工作。