[英]Throw and handle custom exception during authentication Spring Security + WebFlux
I'm trying to throw a custom exception in WebFlux during authentication, and handle it with a ControllerAdvice ( @ExceptionHandler
). 我正在尝试在身份验证期间在WebFlux中引发自定义异常,并使用ControllerAdvice( @ExceptionHandler
)处理它。 Unfortunately, it doesn't get propagated, I'm getting either HTTP 500 if I throw the exception, or HTTP 401 if I return the exception as Mono.error() 不幸的是,它不会传播,如果抛出异常,则返回HTTP 500;如果将异常返回为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
}
Is there any way to help the exception to make it to the ExceptionHandler? 有什么方法可以帮助将异常添加到ExceptionHandler?
The UserDetailsService
(both reactive and non-reactive ) has as a job to retrieve the user based on the username
. UserDetailsService
( 反应式和非反应式 )都具有根据username
检索用户的任务。 Nothing more and nothing less. 一无所有,一无所有。 Checking if the user is enabled is delegated to a UserDetailsChecker
which calls some methods on the UserDetails
implementation and will react accordingly. 将检查是否启用了用户委托给UserDetailsChecker
,后者在UserDetails
实现上调用某些方法,并将相应地做出反应。 Don't try to do more in here as that isn't the task of the UserDetailsService
. 不要在这里尝试做更多的事情,因为那不是UserDetailsService
的任务。
The default UserDetails
, User
implementation has 2 constructors, one with 3 and one with 7 parameters. 默认的UserDetails
, User
实现有2个构造函数,一个带有3个构造函数,一个带有7个参数。 Use the second one to fill the enabled
properly according to your business rules and Spring Security will do the rest as it should. 使用第二个来根据您的业务规则正确填充已enabled
,其余的将由Spring Security来完成。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.