Selaa lähdekoodia

# fix: 登录失败返回账号或密码错误(BadCredentialsException + 认证异常全局处理)

yangyi 2 viikkoa sitten
vanhempi
sitoutus
6ca91c8ae1

+ 6 - 0
src/main/java/space/anyi/serve/handler/GlobalExceptionHandler.java

@@ -2,6 +2,7 @@ package space.anyi.serve.handler;
 
 import jakarta.validation.ConstraintViolationException;
 import org.springframework.http.HttpStatus;
+import org.springframework.security.core.AuthenticationException;
 import org.springframework.validation.BindException;
 import org.springframework.validation.FieldError;
 import org.springframework.web.bind.MethodArgumentNotValidException;
@@ -62,6 +63,11 @@ public class GlobalExceptionHandler {
         return Response.error("参数不合法",fieldErrors);
     }
 
+    @ExceptionHandler(AuthenticationException.class)
+    public Response<String> handleAuthenticationException(AuthenticationException ex) {
+        return Response.error(ex.getMessage());
+    }
+
     @ExceptionHandler(Exception.class)
     public Response handlerException(Exception e){
         return Response.error(e.getMessage());

+ 3 - 3
src/main/java/space/anyi/serve/service/impl/UserDetailsServiceImpl.java

@@ -1,8 +1,8 @@
 package space.anyi.serve.service.impl;
 
+import org.springframework.security.authentication.BadCredentialsException;
 import org.springframework.security.core.userdetails.UserDetails;
 import org.springframework.security.core.userdetails.UserDetailsService;
-import org.springframework.security.core.userdetails.UsernameNotFoundException;
 import org.springframework.stereotype.Service;
 import space.anyi.serve.entity.auth.JwtUserDetails;
 import space.anyi.serve.entity.user.User;
@@ -18,13 +18,13 @@ public class UserDetailsServiceImpl implements UserDetailsService {
     }
 
     @Override
-    public UserDetails loadUserByUsername(String account) throws UsernameNotFoundException {
+    public UserDetails loadUserByUsername(String account) throws BadCredentialsException {
         User user = userService.lambdaQuery()
                 .eq(User::getAccount, account)
                 .eq(User::getEnable, User.ENABLE_ON)
                 .one();
         if (user == null) {
-            throw new UsernameNotFoundException("账号或密码错误");
+            throw new BadCredentialsException("账号或密码错误");
         }
         return new JwtUserDetails(user);
     }