Sfoglia il codice sorgente

登录、权限相关问题修正

songxinlu 3 anni fa
parent
commit
c60b970fcf

+ 37 - 0
src/main/java/com/diagbot/config/AccessDeniedExceptionPoint.java

@@ -0,0 +1,37 @@
+package com.diagbot.config;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.springframework.security.access.AccessDeniedException;
+import org.springframework.security.web.access.AccessDeniedHandler;
+import org.springframework.stereotype.Component;
+
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * @Description:
+ * @Author songxl
+ * @Date 2021/11/30
+ */
+@Component
+public class AccessDeniedExceptionPoint implements AccessDeniedHandler {
+    @Override
+    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse response, AccessDeniedException e) throws IOException, ServletException {
+        Map map = new HashMap();
+        //响应状态码统一为200
+        response.setStatus(HttpServletResponse.SC_OK);
+        map.put("code", "00000001");
+        map.put("msg","没有该权限");
+        response.setContentType("application/json");
+        try {
+            ObjectMapper mapper = new ObjectMapper();
+            mapper.writeValue(response.getOutputStream(), map);
+        } catch (Exception e1) {
+            throw new ServletException();
+        }
+    }
+}

+ 6 - 14
src/main/java/com/diagbot/config/AuthExceptionEntryPoint.java

@@ -5,8 +5,10 @@ import com.diagbot.exception.CommonException;
 import com.diagbot.exception.ServiceErrorCode;
 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.stereotype.Component;
 
 import javax.servlet.ServletException;
 import javax.servlet.http.HttpServletRequest;
@@ -19,27 +21,17 @@ import java.util.Map;
  * @Author songxl
  * @Date 2021/11/30
  */
+@Component
 public class AuthExceptionEntryPoint implements AuthenticationEntryPoint {
-
+    @Autowired
+    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 {
-            response.setStatus(HttpServletResponse.SC_OK);
-            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();
         }

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

@@ -0,0 +1,90 @@
+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)
+        //如果抛出未认证在这个调用这个服务接口返回消息
+        //响应状态码统一为200
+        response.setStatus(HttpServletResponse.SC_OK);
+        if (matchers("/sys/user/getHospitalMark", request)) {
+            map.put("code", "0");
+            map.put("msg", "");
+            map.put("data", userFacade.getHospitalMark());
+        } else if (authException instanceof BadCredentialsException) {
+            map.put("code", "00000001");
+            map.put("msg", "用户或密码不正确");
+        } else if (authException instanceof AccountStatusException) {
+            if (authException instanceof LockedException) {
+                map.put("code", "00000001");
+                map.put("msg", "账户锁定");
+            } else if (authException instanceof AccountExpiredException) {//账户过期
+                map.put("code", "10020011");
+                map.put("msg", "登录超时。为确保您的账户安全,系统已自动退出,请重新登录。");
+            } else if (authException instanceof CredentialsExpiredException) {//证书过期
+                map.put("code", "10020011");
+                map.put("msg", "登录超时。为确保您的账户安全,系统已自动退出,请重新登录。");
+            } else if (authException instanceof DisabledException) {
+                map.put("code", "00000001");
+                map.put("msg", "账户不可用");
+            } else {
+                map.put("code", "00000001");
+                map.put("msg", "用户状态异常");
+            }
+        } else if (authException instanceof InsufficientAuthenticationException) {
+            map.put("code", "10020011");
+            map.put("msg", "登录超时。为确保您的账户安全,系统已自动退出,请重新登录。");
+        } else {
+            map.put("code", "00000001");
+            map.put("msg", authException.getMessage());
+        }
+        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;
+    }
+}

+ 223 - 0
src/main/java/com/diagbot/config/MyJwtTokenStore.java

@@ -0,0 +1,223 @@
+package com.diagbot.config;
+
+import com.diagbot.util.DateUtil;
+import com.diagbot.util.RedisUtils;
+import org.springframework.core.io.ClassPathResource;
+import org.springframework.core.io.Resource;
+import org.springframework.security.core.Authentication;
+import org.springframework.security.jwt.Jwt;
+import org.springframework.security.jwt.JwtHelper;
+import org.springframework.security.jwt.crypto.sign.RsaVerifier;
+import org.springframework.security.jwt.crypto.sign.SignatureVerifier;
+import org.springframework.security.oauth2.common.DefaultExpiringOAuth2RefreshToken;
+import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
+import org.springframework.security.oauth2.common.DefaultOAuth2RefreshToken;
+import org.springframework.security.oauth2.common.OAuth2AccessToken;
+import org.springframework.security.oauth2.common.OAuth2RefreshToken;
+import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
+import org.springframework.security.oauth2.common.util.JsonParser;
+import org.springframework.security.oauth2.common.util.JsonParserFactory;
+import org.springframework.security.oauth2.provider.OAuth2Authentication;
+import org.springframework.security.oauth2.provider.approval.Approval;
+import org.springframework.security.oauth2.provider.approval.ApprovalStore;
+import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
+import org.springframework.security.oauth2.provider.token.store.JwtClaimsSetVerifier;
+import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
+import org.springframework.security.oauth2.provider.approval.Approval.ApprovalStatus;
+import org.springframework.util.FileCopyUtils;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Date;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Map;
+
+/**
+ * @Description:token续签
+ * @Author songxl
+ * @Date 2021/12/17
+ */
+public class MyJwtTokenStore extends JwtTokenStore {
+    private JwtAccessTokenConverter jwtTokenEnhancer;
+    private ApprovalStore approvalStore;
+    private JsonParser objectMapper = JsonParserFactory.create();
+    private JwtClaimsSetVerifier jwtClaimsSetVerifier = new NoOpJwtClaimsSetVerifier();
+    private SignatureVerifier verifier;
+    private RedisUtils redisUtils;
+    public MyJwtTokenStore(JwtAccessTokenConverter jwtTokenEnhancer,RedisUtils redisUtils) {
+        super(jwtTokenEnhancer);
+        verifier = createVerifier();
+        this.jwtTokenEnhancer = jwtTokenEnhancer;
+        this.redisUtils = redisUtils;
+    }
+
+    private SignatureVerifier createVerifier() {
+        Resource resource = new ClassPathResource("public.cert");
+        String publicKey;
+        try {
+            publicKey = new String(FileCopyUtils.copyToByteArray(resource.getInputStream()));
+        } catch (IOException e) {
+            throw new RuntimeException(e);
+        }
+        return new RsaVerifier(publicKey);
+    }
+
+    public void setApprovalStore(ApprovalStore approvalStore) {
+        this.approvalStore = approvalStore;
+    }
+
+    public OAuth2Authentication readAuthentication(OAuth2AccessToken token) {
+        return this.readAuthentication(token.getValue());
+    }
+
+
+    public void storeAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication) {
+    }
+
+    public OAuth2AccessToken readAccessToken(String tokenValue) {
+        DefaultOAuth2AccessToken accessToken = (DefaultOAuth2AccessToken) this.convertAccessToken(tokenValue);
+        OAuth2AccessToken newAccessToken = updateTokenOutTime(accessToken);
+        if (this.jwtTokenEnhancer.isRefreshToken(accessToken)) {
+            throw new InvalidTokenException("Encoded token is a refresh token");
+        } else {
+            return newAccessToken;
+        }
+    }
+
+    private OAuth2AccessToken updateTokenOutTime(DefaultOAuth2AccessToken accessToken) {
+        if(accessToken.getAdditionalInformation()!=null&&accessToken.getAdditionalInformation().containsKey("user_id")){
+            //通过用户id获取redis存储的token过期时间
+            Object userIdObj = accessToken.getAdditionalInformation().get("user_id");
+            Integer value =(Integer) redisUtils.get("user:refreshToken:outTime_" + userIdObj);
+            if (value!=null){
+                //更新token过期时间为明天
+                accessToken.setExpiration(DateUtil.addDay(new Date(),1));
+                //将这个时间重新存到redis
+                redisUtils.set("user:refreshToken:outTime_" + userIdObj, value, value);
+            }
+        }
+        return accessToken;
+    }
+
+    private OAuth2AccessToken convertAccessToken(String tokenValue) {
+        return this.jwtTokenEnhancer.extractAccessToken(tokenValue, decode(tokenValue));
+    }
+
+    public void removeAccessToken(OAuth2AccessToken token) {
+    }
+
+    public void storeRefreshToken(OAuth2RefreshToken refreshToken, OAuth2Authentication authentication) {
+    }
+
+    public OAuth2RefreshToken readRefreshToken(String tokenValue) {
+        OAuth2AccessToken encodedRefreshToken = this.convertAccessToken(tokenValue);
+        OAuth2RefreshToken refreshToken = this.createRefreshToken(encodedRefreshToken);
+        if (this.approvalStore != null) {
+            OAuth2Authentication authentication = this.readAuthentication(tokenValue);
+            if (authentication.getUserAuthentication() != null) {
+                String userId = authentication.getUserAuthentication().getName();
+                String clientId = authentication.getOAuth2Request().getClientId();
+                Collection<Approval> approvals = this.approvalStore.getApprovals(userId, clientId);
+                Collection<String> approvedScopes = new HashSet();
+                Iterator var9 = approvals.iterator();
+
+                while(var9.hasNext()) {
+                    Approval approval = (Approval)var9.next();
+                    if (approval.isApproved()) {
+                        approvedScopes.add(approval.getScope());
+                    }
+                }
+
+                if (!approvedScopes.containsAll(authentication.getOAuth2Request().getScope())) {
+                    return null;
+                }
+            }
+        }
+
+        return refreshToken;
+    }
+
+    private OAuth2RefreshToken createRefreshToken(OAuth2AccessToken encodedRefreshToken) {
+        if (!this.jwtTokenEnhancer.isRefreshToken(encodedRefreshToken)) {
+            throw new InvalidTokenException("Encoded token is not a refresh token");
+        } else {
+            return (OAuth2RefreshToken)(encodedRefreshToken.getExpiration() != null ? new DefaultExpiringOAuth2RefreshToken(encodedRefreshToken.getValue(), encodedRefreshToken.getExpiration()) : new DefaultOAuth2RefreshToken(encodedRefreshToken.getValue()));
+        }
+    }
+
+    public OAuth2Authentication readAuthenticationForRefreshToken(OAuth2RefreshToken token) {
+        return this.readAuthentication(token.getValue());
+    }
+
+    public void removeRefreshToken(OAuth2RefreshToken token) {
+        this.remove(token.getValue());
+    }
+
+    public void removeAccessTokenUsingRefreshToken(OAuth2RefreshToken refreshToken) {
+    }
+
+    public OAuth2AccessToken getAccessToken(OAuth2Authentication authentication) {
+        return null;
+    }
+
+    public Collection<OAuth2AccessToken> findTokensByClientIdAndUserName(String clientId, String userName) {
+        return Collections.emptySet();
+    }
+
+    public Collection<OAuth2AccessToken> findTokensByClientId(String clientId) {
+        return Collections.emptySet();
+    }
+
+    public void setTokenEnhancer(JwtAccessTokenConverter tokenEnhancer) {
+        this.jwtTokenEnhancer = tokenEnhancer;
+    }
+
+    private void remove(String token) {
+        if (this.approvalStore != null) {
+            OAuth2Authentication auth = this.readAuthentication(token);
+            String clientId = auth.getOAuth2Request().getClientId();
+            Authentication user = auth.getUserAuthentication();
+            if (user != null) {
+                Collection<Approval> approvals = new ArrayList();
+                Iterator var6 = auth.getOAuth2Request().getScope().iterator();
+
+                while(var6.hasNext()) {
+                    String scope = (String)var6.next();
+                    approvals.add(new Approval(user.getName(), clientId, scope, new Date(), ApprovalStatus.APPROVED));
+                }
+
+                this.approvalStore.revokeApprovals(approvals);
+            }
+        }
+
+    }
+
+    protected Map<String, Object> decode(String token) {
+        try {
+            Jwt jwt = JwtHelper.decodeAndVerify(token,verifier);
+            String claimsStr = jwt.getClaims();
+            Map<String, Object> claims = this.objectMapper.parseMap(claimsStr);
+            if (claims.containsKey("exp") && claims.get("exp") instanceof Integer) {
+                Integer intValue = (Integer)claims.get("exp");
+                claims.put("exp", new Long((long)intValue));
+            }
+
+            jwtClaimsSetVerifier.verify(claims);
+            return claims;
+        } catch (Exception var6) {
+            throw new InvalidTokenException("Cannot convert access token to JSON", var6);
+        }
+    }
+
+
+    private class NoOpJwtClaimsSetVerifier implements JwtClaimsSetVerifier {
+        private NoOpJwtClaimsSetVerifier() {
+        }
+
+        public void verify(Map<String, Object> claims) throws InvalidTokenException {
+        }
+    }
+}

+ 13 - 4
src/main/java/com/diagbot/config/ResourceServerConfigurer.java

@@ -1,5 +1,6 @@
 package com.diagbot.config;
 
+import com.diagbot.util.RedisUtils;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.beans.factory.annotation.Autowired;
@@ -30,12 +31,19 @@ import java.io.IOException;
 @ComponentScan({"com.diagbot.config"})
 public class ResourceServerConfigurer extends ResourceServerConfigurerAdapter {
     Logger log = LoggerFactory.getLogger(ResourceServerConfigurer.class);
-
+    @Autowired
+    private AuthExceptionEntryPoint authExceptionEntryPoint;
+    @Autowired
+    private AccessDeniedExceptionPoint accessDeniedExceptionPoint;
+    @Autowired
+    private RedisUtils redisUtils;
     @Override
     public void configure(HttpSecurity http) throws Exception {
         http.cors()
                 .and()
-                .exceptionHandling().authenticationEntryPoint(new AuthExceptionEntryPoint())
+                .exceptionHandling().authenticationEntryPoint(authExceptionEntryPoint)
+                .and()
+                .exceptionHandling().accessDeniedHandler(accessDeniedExceptionPoint)
                 .and()
                 .csrf().disable()
                 .authorizeRequests()
@@ -262,8 +270,9 @@ public class ResourceServerConfigurer extends ResourceServerConfigurerAdapter {
     @Override
     public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
         log.info("Configuring ResourceServerSecurityConfigurer");
-        resources.resourceId("user-service").tokenStore(new JwtTokenStore(jwtTokenEnhancerClient()));
-        resources.authenticationEntryPoint(new AuthExceptionEntryPoint());
+        resources.resourceId("user-service").tokenStore(new MyJwtTokenStore(jwtTokenEnhancerClient(),redisUtils));
+        resources.authenticationEntryPoint(authExceptionEntryPoint);
+        resources.accessDeniedHandler(accessDeniedExceptionPoint);
     }
     @Autowired
     private CustomAccessTokenConverter customAccessTokenConverter;

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

@@ -1,8 +1,6 @@
 package com.diagbot.config.security;
 
-import com.diagbot.exception.CommonErrorCode;
 import com.diagbot.exception.CommonException;
-import com.diagbot.exception.ErrorCode;
 import com.diagbot.exception.ServiceErrorCode;
 import com.diagbot.facade.TokenFacade;
 import com.diagbot.util.HttpUtils;
@@ -37,12 +35,17 @@ public class UrlAccessDecisionManager implements AccessDecisionManager {
         HttpServletRequest request = ((FilterInvocation) object).getHttpRequest();
         String url, method;
         String tokenStr = HttpUtils.getHeaders(request).get("Authorization");
+        if (!request.getMethod().equals("OPTIONS") && StringUtil.isEmpty(tokenStr)) {
+            tokenStr = HttpUtils.getHeaders(request).get("authorization");
+        }
         //用户是否被顶掉校验
         if (StringUtil.isNotEmpty(tokenStr) && !matchNotCheckUrl(request)) {
             tokenStr = tokenStr.replaceFirst("Bearer ", "");
             int res = tokenFacade.newVerifyToken(tokenStr, 1);
             if (-1 == res) {
                 throw new CommonException(ServiceErrorCode.LONGIN_ERROE);
+            } else if (-2 == res) {
+                throw new CommonException(ServiceErrorCode.USER_POWER_UP);
             }
         }
         if (matchPermitAllUrl(request)) {
@@ -51,13 +54,12 @@ public class UrlAccessDecisionManager implements AccessDecisionManager {
         if ("anonymousUser".equals(authentication.getPrincipal())) {
             throw new AccessDeniedException("no right");
         } else {
-
             if (StringUtil.isNotEmpty(tokenStr)) {
                 tokenStr = tokenStr.replaceFirst("Bearer ", "");
 //                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");
                 }

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

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

+ 9 - 1
src/main/java/com/diagbot/facade/SysDictionaryFacade.java

@@ -60,5 +60,13 @@ public class SysDictionaryFacade extends SysDictionaryInfoServiceImpl {
         }
         return res;
     }
-
+    public long getAccessTokenOutTime() {
+        long accessToken = 24 * 3600*1l;
+        if (getDictionaryWithKey() != null
+                && getDictionaryWithKey().containsKey("31")
+                && getDictionaryWithKey().get("31").containsKey("accessToken")) {
+            accessToken = Long.parseLong(getDictionaryWithKey().get("31").get("accessToken"));
+        }
+        return accessToken;
+    }
 }

+ 3 - 0
src/main/java/com/diagbot/facade/SysUserFacade.java

@@ -244,6 +244,9 @@ public class SysUserFacade extends SysUserServiceImpl {
         jwtStore.setAccessToken(jwt.getAccess_token());
         jwtStore.setRefreshToken(jwt.getRefresh_token());
         tokenFacade.createToken(jwtStore);
+        //每次登录在redis缓存该用户登录成功的token;缓存时间为token有效时间
+        long accessTokenTime = sysDictionaryFacade.getAccessTokenOutTime();
+        redisUtils.set("user:refreshToken:outTime_" + user.getId(), accessTokenTime, accessTokenTime);
         /***
          * 未经过MD5加密密码复杂度判断
          */

+ 1 - 1
src/main/java/com/diagbot/service/impl/SysTokenServiceImpl.java

@@ -175,7 +175,7 @@ public class SysTokenServiceImpl implements SysTokenService {
                 }
             }
         } else {
-            res = -1;
+            res = -2;       //redis取不到token原因是因为用户权限修改被清空掉了,如果是到时钱被清空会先提示用户登录超时
         }
 
         return res;

+ 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());
     }