Selaa lähdekoodia

细化authentication异常,新增登录异常(无tonken获取用户信息失败)

songxinlu 3 vuotta sitten
vanhempi
commit
a16c7d4ff2

+ 2 - 37
src/main/java/com/diagbot/config/AuthExceptionEntryPoint.java

@@ -1,19 +1,13 @@
 package com.diagbot.config;
 
-import com.diagbot.facade.SysUserFacade;
-import com.diagbot.util.StringUtil;
-import com.fasterxml.jackson.databind.ObjectMapper;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.security.core.AuthenticationException;
 import org.springframework.security.web.AuthenticationEntryPoint;
-import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
 import org.springframework.stereotype.Component;
 
 import javax.servlet.ServletException;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
-import java.util.HashMap;
-import java.util.Map;
 
 /**
  * @Description:
@@ -23,45 +17,16 @@ import java.util.Map;
 @Component
 public class AuthExceptionEntryPoint implements AuthenticationEntryPoint {
     @Autowired
-    private SysUserFacade userFacade;
+    AuthenticationExceptionHandler authenticationExceptionHandler;
 
     @Override
     public void commence(HttpServletRequest request, HttpServletResponse response,
                          AuthenticationException authException)
             throws ServletException {
-        Map map = new HashMap();
-        if (StringUtil.isNotEmpty(authException.getMessage()) && authException.getMessage().contains("Access token expired")) {
-            map.put("code", "10020011");
-            map.put("msg", "登录超时。为确保您的账户安全,系统已自动退出,请重新登录。");
-            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
-        } else {
-            //登录前的获取登录页面的请求接口不知道什么原因会抛出未认证(Full authentication is required to access this resource)
-            //如果抛出未认证在这个调用这个服务接口返回消息
-            response.setStatus(HttpServletResponse.SC_OK);
-            if (matchers("/sys/user/getHospitalMark", request)) {
-                map.put("code", "0");
-                map.put("msg", "");
-                map.put("data", userFacade.getHospitalMark());
-            } else {
-                map.put("code", "00000001");
-                map.put("msg", authException.getMessage());
-            }
-        }
-        response.setContentType("application/json");
         try {
-            ObjectMapper mapper = new ObjectMapper();
-            mapper.writeValue(response.getOutputStream(), map);
+            authenticationExceptionHandler.handleException(request,response,authException);
         } catch (Exception e) {
             throw new ServletException();
         }
     }
-
-
-    private boolean matchers(String url, HttpServletRequest request) {
-        AntPathRequestMatcher matcher = new AntPathRequestMatcher(url);
-        if (matcher.matches(request)) {
-            return true;
-        }
-        return false;
-    }
 }

+ 95 - 0
src/main/java/com/diagbot/config/AuthenticationExceptionHandler.java

@@ -0,0 +1,95 @@
+package com.diagbot.config;
+
+
+import com.diagbot.facade.SysUserFacade;
+import com.diagbot.util.StringUtil;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.security.authentication.AccountExpiredException;
+import org.springframework.security.authentication.AccountStatusException;
+import org.springframework.security.authentication.BadCredentialsException;
+import org.springframework.security.authentication.CredentialsExpiredException;
+import org.springframework.security.authentication.DisabledException;
+import org.springframework.security.authentication.InsufficientAuthenticationException;
+import org.springframework.security.authentication.LockedException;
+import org.springframework.security.core.AuthenticationException;
+import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
+import org.springframework.stereotype.Component;
+import org.springframework.validation.BindException;
+
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * @Description:权限认证异常处理
+ * @Author songxl
+ * @Date 2021/12/13
+ */
+@Component
+public class AuthenticationExceptionHandler {
+    @Autowired
+    private SysUserFacade userFacade;
+
+    public void handleException(HttpServletRequest request, HttpServletResponse response,
+                                AuthenticationException authException) throws ServletException {
+        Map map = new HashMap();
+        //登录前的获取登录页面的请求接口不知道什么原因会抛出未认证(Full authentication is required to access this resource)
+        //如果抛出未认证在这个调用这个服务接口返回消息
+        if (matchers("/sys/user/getHospitalMark", request)) {
+            map.put("code", "0");
+            map.put("msg", "");
+            map.put("data", userFacade.getHospitalMark());
+            response.setStatus(HttpServletResponse.SC_OK);
+        } else if (authException instanceof BadCredentialsException) {
+            map.put("code", "00000001");
+            map.put("msg", "用户或密码不正确");
+            response.setStatus(HttpServletResponse.SC_OK);
+        } else if (authException instanceof AccountStatusException) {
+            map.put("code", "00000001");
+            map.put("msg", "户状态异常");
+            response.setStatus(HttpServletResponse.SC_OK);
+        } else if (authException instanceof AccountExpiredException) {
+            map.put("code", "00000001");
+            map.put("msg", "账户过期");
+            response.setStatus(HttpServletResponse.SC_OK);
+        } else if (authException instanceof CredentialsExpiredException) {//证书过期
+            map.put("code", "10020011");
+            map.put("msg", "登录超时。为确保您的账户安全,系统已自动退出,请重新登录。");
+            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
+        } else if (authException instanceof DisabledException) {
+            map.put("code", "00000001");
+            map.put("msg", "账户不可用");
+            response.setStatus(HttpServletResponse.SC_OK);
+        } else if (authException instanceof LockedException) {
+            map.put("code", "00000001");
+            map.put("msg", "账户锁定");
+            response.setStatus(HttpServletResponse.SC_OK);
+        } else if (authException instanceof InsufficientAuthenticationException) {
+            map.put("code", "10020011");
+            map.put("msg", "登录超时。为确保您的账户安全,系统已自动退出,请重新登录。");
+            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
+        } else {
+            map.put("code", "00000001");
+            map.put("msg", authException.getMessage());
+            response.setStatus(HttpServletResponse.SC_OK);
+        }
+        response.setContentType("application/json");
+        try {
+            ObjectMapper mapper = new ObjectMapper();
+            mapper.writeValue(response.getOutputStream(), map);
+        } catch (Exception e) {
+            throw new ServletException();
+        }
+    }
+
+    private boolean matchers(String url, HttpServletRequest request) {
+        AntPathRequestMatcher matcher = new AntPathRequestMatcher(url);
+        if (matcher.matches(request)) {
+            return true;
+        }
+        return false;
+    }
+}

+ 1 - 1
src/main/java/com/diagbot/config/OAuth2Configurer.java

@@ -45,7 +45,7 @@ public class OAuth2Configurer extends AuthorizationServerConfigurerAdapter {
                 && sysDictionaryFacade.getDictionaryWithKey().containsKey("31")
                 && sysDictionaryFacade.getDictionaryWithKey().get("31").containsKey("accessToken")
                 && sysDictionaryFacade.getDictionaryWithKey().get("31").containsKey("refreshToken")) {
-            accessToken = Integer.parseInt(sysDictionaryFacade.getDictionaryWithKey().get("31").get("accessToken"));
+            accessToken = Integer.parseInt("60");
             refreshToken = Integer.parseInt(sysDictionaryFacade.getDictionaryWithKey().get("31").get("refreshToken"));
         }
         clients.inMemory()

+ 1 - 1
src/main/java/com/diagbot/config/security/UrlAccessDecisionManager.java

@@ -55,7 +55,7 @@ public class UrlAccessDecisionManager implements AccessDecisionManager {
 //                Boolean res = tokenFacade.verifyToken(tokenStr, 1);
                 int res = tokenFacade.newVerifyToken(tokenStr, 1);
                 if (-1 == res) {
-                    throw new CommonException(CommonErrorCode.SERVER_IS_ERROR, "该账号在其他地方登录。");
+                    throw new CommonException(ServiceErrorCode.LONGIN_ERROE);
                 } else if (1 != res) {
                     throw new AccountExpiredException("token expire");
                 }

+ 1 - 0
src/main/java/com/diagbot/exception/ServiceErrorCode.java

@@ -13,6 +13,7 @@ public enum ServiceErrorCode implements ErrorCode {
     GET_TOKEN_FAIL("10020002", "获取token失败"),
     TOKEN_IS_NOT_MATCH_USER("10020003", "请使用自己的token进行接口请求"),
     LONGIN_ERROE("10020012", "您的账号在其它地方已登录,您已被迫下线,请重新登录。如非本人授权,登录后请及时修改密码。"),
+    LONGIN_TOKEN_ERROE("10020013", "登录异常"),
 
     SMS_SEND_ERROR("10020004", "短信发送错误"),
     USER_BIND_ERROR("10020005", "用户手机号已经绑定无需再次验证"),

+ 14 - 2
src/main/java/com/diagbot/util/SysUserUtils.java

@@ -1,5 +1,7 @@
 package com.diagbot.util;
 
+import com.diagbot.exception.CommonException;
+import com.diagbot.exception.ServiceErrorCode;
 import org.springframework.security.core.Authentication;
 import org.springframework.security.core.authority.SimpleGrantedAuthority;
 import org.springframework.security.core.context.SecurityContextHolder;
@@ -41,7 +43,12 @@ public class SysUserUtils {
      * @return
      */
     public static String getCurrentPrincipleID() {
-        OAuth2AuthenticationDetails oauthDetails = (OAuth2AuthenticationDetails) SecurityContextHolder.getContext().getAuthentication().getDetails();
+        OAuth2AuthenticationDetails oauthDetails = null;
+        try {
+            oauthDetails = (OAuth2AuthenticationDetails) SecurityContextHolder.getContext().getAuthentication().getDetails();
+        }catch (ClassCastException e){
+            throw new CommonException(ServiceErrorCode.LONGIN_TOKEN_ERROE);
+        }
         return SysJwtUtil.getUserId(oauthDetails.getTokenValue());
     }
 
@@ -51,7 +58,12 @@ public class SysUserUtils {
      * @return
      */
     public static String getCurrentHospitalID() {
-        OAuth2AuthenticationDetails oauthDetails = (OAuth2AuthenticationDetails) SecurityContextHolder.getContext().getAuthentication().getDetails();
+        OAuth2AuthenticationDetails oauthDetails = null;
+        try {
+            oauthDetails = (OAuth2AuthenticationDetails) SecurityContextHolder.getContext().getAuthentication().getDetails();
+        }catch (ClassCastException e){
+            throw new CommonException(ServiceErrorCode.LONGIN_TOKEN_ERROE);
+        }
         return SysJwtUtil.getHospId(oauthDetails.getTokenValue());
     }