UsernameNotFoundException

UsernameNotFoundException

如何处理UsernameNotFoundException

在春季安全性中,当找不到用户名时,UserDetailsService实现将引发UsernameNotFoundException。例如这样:

   @Override
   @Transactional
   public UserDetails loadUserByUsername(java.lang.String username) throws UsernameNotFoundException {
       logger.info("Load user by username: {}", username);
       User user = userRepository.findUserByUsername(username).orElseThrow(
                   () -> new UsernameNotFoundException("User Not Found with -> username or email: " + username));

       return UserPrinciple.build(user);
   }


我想建立一个自定义的“找不到用户的REST响应”。
我应该如何捕获/处理此异常?我已经在WebSecurityConfigurerAdapter实现中实现了处理程序方法:

  private static void handleException(HttpServletRequest req, HttpServletResponse rsp, AuthenticationException e)
           throws IOException {
       PrintWriter writer = rsp.getWriter();
       writer.println(new ObjectMapper().writeValueAsString(new AuthResponse("", null, null, null, null,
               "Authentication failed.", false)));
       rsp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
   }


但是此方法应等待AuthenticationException异常,并且在运行时异常类型为java.lang.NullPointerException,因此我无法强制转换或检索初始的UsernameNotFoundException

任何意见,将不胜感激。
许多问候:)。

最佳答案

我不知道您的项目的结构,但是在这种情况下,通常的解决方案是使用@ControllerAdvice机制(分离的类或在控制器中):

@ControllerAdvice
public class CustomExceptionHandler {

    @ExceptionHandler(value = UsernameNotFoundException.class)
    public ResponseEntity handle(final UsernameNotFoundException exception) {
        ...//set headers, response attributes and response body
    }
}

09-26 04:02