简体   繁体   中英

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 ). 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()

@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?

The UserDetailsService (both 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 which calls some methods on the UserDetails implementation and will react accordingly. Don't try to do more in here as that isn't the task of the UserDetailsService .

The default UserDetails , User implementation has 2 constructors, one with 3 and one with 7 parameters. Use the second one to fill the enabled properly according to your business rules and Spring Security will do the rest as it should.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM