Browse Source

去掉开放接口对与header字段的强制依赖,注释切面对于header字段的校验;修改time与platform两个header字段取值的方法,简化数字与枚举的转换

luoshi 4 years ago
parent
commit
ed6c4576d3

+ 1 - 1
themis-backend/src/main/java/com/qmth/themis/backend/api/TBUserController.java

@@ -190,7 +190,7 @@ public class TBUserController {
         if (user.getEnable().intValue() == 0) {
         if (user.getEnable().intValue() == 0) {
             throw new BusinessException(ExceptionResultEnum.USER_ENABLE);
             throw new BusinessException(ExceptionResultEnum.USER_ENABLE);
         }
         }
-        Platform platform = Platform.valueOf(ServletUtil.getRequestPlatform());
+        Platform platform = ServletUtil.getRequestPlatform();
         String deviceId = ServletUtil.getRequestDeviceId();
         String deviceId = ServletUtil.getRequestDeviceId();
         //添加用户鉴权缓存
         //添加用户鉴权缓存
         AuthDto authDto = cacheService.addAccountCache(user.getId());
         AuthDto authDto = cacheService.addAccountCache(user.getId());

+ 7 - 5
themis-backend/src/main/java/com/qmth/themis/backend/aspect/ApiControllerAspect.java

@@ -27,6 +27,7 @@ import java.util.Objects;
 @Aspect
 @Aspect
 @Component
 @Component
 public class ApiControllerAspect {
 public class ApiControllerAspect {
+
     private final static Logger log = LoggerFactory.getLogger(ApiControllerAspect.class);
     private final static Logger log = LoggerFactory.getLogger(ApiControllerAspect.class);
 
 
     /**
     /**
@@ -65,17 +66,18 @@ public class ApiControllerAspect {
                     }
                     }
                 }
                 }
                 if (jsonOut) {
                 if (jsonOut) {
-                    log.info("============参数key:{},参数value===========:{}", JacksonUtil.parseJson(paramsName), JacksonUtil.parseJson(args));
+                    log.info("============参数key:{},参数value===========:{}", JacksonUtil.parseJson(paramsName),
+                            JacksonUtil.parseJson(args));
                 } else {
                 } else {
                     for (int i = 0; i < args.length; i++) {
                     for (int i = 0; i < args.length; i++) {
                         log.info("============参数key:{},参数value===========:{}", paramsName[i], args[i]);
                         log.info("============参数key:{},参数value===========:{}", paramsName[i], args[i]);
                     }
                     }
                 }
                 }
             }
             }
-            log.info("============platform===========:{}", ServletUtil.getRequestPlatform());
-            log.info("============deviceId===========:{}", ServletUtil.getRequestDeviceId());
-            log.info("============Authorization===========:{}", ServletUtil.getRequestAuthorizationForAspect());
-            log.info("============time===========:{}", ServletUtil.getRequestTimeForTime());
+            //log.info("============platform===========:{}", ServletUtil.getRequestPlatform());
+            //log.info("============deviceId===========:{}", ServletUtil.getRequestDeviceId());
+            //log.info("============Authorization===========:{}", ServletUtil.getRequestAuthorizationForAspect());
+            //log.info("============time===========:{}", ServletUtil.getRequestTimeForTime());
             Object proceed = joinPoint.proceed();
             Object proceed = joinPoint.proceed();
             long end = System.currentTimeMillis();
             long end = System.currentTimeMillis();
             log.info("============耗时============:{}秒", (end - start) / 1000);
             log.info("============耗时============:{}秒", (end - start) / 1000);

+ 18 - 19
themis-backend/src/main/java/com/qmth/themis/backend/interceptor/AuthInterceptor.java

@@ -34,6 +34,7 @@ import java.util.Set;
  * @Date: 2020/6/27
  * @Date: 2020/6/27
  */
  */
 public class AuthInterceptor implements HandlerInterceptor {
 public class AuthInterceptor implements HandlerInterceptor {
+
     private final static Logger log = LoggerFactory.getLogger(AuthInterceptor.class);
     private final static Logger log = LoggerFactory.getLogger(AuthInterceptor.class);
 
 
     @Resource
     @Resource
@@ -56,19 +57,18 @@ public class AuthInterceptor implements HandlerInterceptor {
         if (url.equalsIgnoreCase(SystemConstant.ERROR)) {
         if (url.equalsIgnoreCase(SystemConstant.ERROR)) {
             throw new BusinessException(ExceptionResultEnum.NOT_FOUND);
             throw new BusinessException(ExceptionResultEnum.NOT_FOUND);
         }
         }
-        Platform platform = Platform.valueOf(ServletUtil.getRequestPlatform());
+        Platform platform = ServletUtil.getRequestPlatform();
         String deviceId = ServletUtil.getRequestDeviceId();
         String deviceId = ServletUtil.getRequestDeviceId();
         String authorization = ServletUtil.getRequestAuthorization();
         String authorization = ServletUtil.getRequestAuthorization();
-        String time = ServletUtil.getRequestTime();
-        log.info("platform:{},deviceId:{},authorization:{},method:{},time:{}", platform, deviceId, authorization, method, time);
+        long time = ServletUtil.getRequestTime();
+        log.info("platform:{},deviceId:{},authorization:{},method:{},time:{}", platform, deviceId, authorization,
+                method, time);
         Long userId = null;
         Long userId = null;
-        Long timestamp = Long.parseLong(time);
-        if (!SystemConstant.expire(timestamp.longValue())) {
-            final SignatureInfo info = SignatureInfo
-                    .parse(method.toLowerCase(), url, timestamp, authorization);
+        if (!SystemConstant.expire(time)) {
+            final SignatureInfo info = SignatureInfo.parse(method.toLowerCase(), url, time, authorization);
             //测试
             //测试
-//        final SignatureInfo info = SignatureInfo
-//                .parse(authorization);
+            //        final SignatureInfo info = SignatureInfo
+            //                .parse(authorization);
             if (Objects.nonNull(info) && info.getType() == SignatureType.TOKEN) {
             if (Objects.nonNull(info) && info.getType() == SignatureType.TOKEN) {
                 String sessionId = info.getInvoker();
                 String sessionId = info.getInvoker();
                 TBSession tbSession = (TBSession) redisUtil.getUserSession(sessionId);
                 TBSession tbSession = (TBSession) redisUtil.getUserSession(sessionId);
@@ -76,7 +76,8 @@ public class AuthInterceptor implements HandlerInterceptor {
                     throw new BusinessException(ExceptionResultEnum.LOGIN_NO);
                     throw new BusinessException(ExceptionResultEnum.LOGIN_NO);
                 } else {
                 } else {
                     if (info.validate(tbSession.getAccessToken()) && info.getTimestamp() < tbSession.getExpireTime()
                     if (info.validate(tbSession.getAccessToken()) && info.getTimestamp() < tbSession.getExpireTime()
-                            && platform.name().equalsIgnoreCase(tbSession.getPlatform()) && Objects.equals(deviceId, tbSession.getDeviceId())) {
+                            && platform.name().equalsIgnoreCase(tbSession.getPlatform()) && Objects
+                            .equals(deviceId, tbSession.getDeviceId())) {
                         userId = Long.parseLong(tbSession.getIdentity());
                         userId = Long.parseLong(tbSession.getIdentity());
                         Long expireTime = tbSession.getExpireTime();
                         Long expireTime = tbSession.getExpireTime();
                         //手机端的token时长为一个月,所以会出现缓存没有的情况
                         //手机端的token时长为一个月,所以会出现缓存没有的情况
@@ -99,9 +100,9 @@ public class AuthInterceptor implements HandlerInterceptor {
                         }
                         }
                         request.setAttribute(SystemConstant.ORG, authDto.getTbOrg());
                         request.setAttribute(SystemConstant.ORG, authDto.getTbOrg());
                         //系统管理员拥有所有权限
                         //系统管理员拥有所有权限
-//                    if (authDto.getRoleCodes().contains(RoleEnum.SUPER_ADMIN.name())) {
-//                        return true;
-//                    }
+                        //                    if (authDto.getRoleCodes().contains(RoleEnum.SUPER_ADMIN.name())) {
+                        //                        return true;
+                        //                    }
                         //系统公用接口不拦截
                         //系统公用接口不拦截
                         List<String> sysUrls = dictionaryConfig.systemUrlDomain().getUrls();
                         List<String> sysUrls = dictionaryConfig.systemUrlDomain().getUrls();
                         int sysCount = (int) sysUrls.stream().filter(s -> {
                         int sysCount = (int) sysUrls.stream().filter(s -> {
@@ -132,15 +133,13 @@ public class AuthInterceptor implements HandlerInterceptor {
     }
     }
 
 
     @Override
     @Override
-    public void postHandle(HttpServletRequest request,
-                           HttpServletResponse response,
-                           Object o, ModelAndView modelAndView) throws Exception {
+    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object o,
+            ModelAndView modelAndView) throws Exception {
 
 
     }
     }
 
 
     @Override
     @Override
-    public void afterCompletion(HttpServletRequest request,
-                                HttpServletResponse response,
-                                Object o, Exception e) throws Exception {
+    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object o, Exception e)
+            throws Exception {
     }
     }
 }
 }

+ 1 - 1
themis-business/src/main/java/com/qmth/themis/business/service/impl/TEMobileServiceImpl.java

@@ -81,7 +81,7 @@ public class TEMobileServiceImpl implements TEMobileService {
         if (ExamRecordStatusEnum.FINISHED.equals(sta) || ExamRecordStatusEnum.PERSISTED.equals(sta)) {
         if (ExamRecordStatusEnum.FINISHED.equals(sta) || ExamRecordStatusEnum.PERSISTED.equals(sta)) {
             throw new BusinessException(ExceptionResultEnum.EXAM_ALREADY_FINISHED);
             throw new BusinessException(ExceptionResultEnum.EXAM_ALREADY_FINISHED);
         }
         }
-        Platform platform = Platform.valueOf(ServletUtil.getRequestPlatform());
+        Platform platform = ServletUtil.getRequestPlatform();
         String deviceId = ServletUtil.getRequestDeviceId();
         String deviceId = ServletUtil.getRequestDeviceId();
         AuthDto authDto = (AuthDto) redisUtil.get(SystemConstant.studentOauth + "::" + es.getStudentId());
         AuthDto authDto = (AuthDto) redisUtil.get(SystemConstant.studentOauth + "::" + es.getStudentId());
         // 生成token
         // 生成token

+ 23 - 11
themis-business/src/main/java/com/qmth/themis/business/util/ServletUtil.java

@@ -3,9 +3,11 @@ package com.qmth.themis.business.util;
 import com.qmth.themis.business.constant.SystemConstant;
 import com.qmth.themis.business.constant.SystemConstant;
 import com.qmth.themis.common.contanst.Constants;
 import com.qmth.themis.common.contanst.Constants;
 import com.qmth.themis.common.enums.ExceptionResultEnum;
 import com.qmth.themis.common.enums.ExceptionResultEnum;
+import com.qmth.themis.common.enums.Platform;
 import com.qmth.themis.common.exception.BusinessException;
 import com.qmth.themis.common.exception.BusinessException;
 import com.qmth.themis.common.util.Result;
 import com.qmth.themis.common.util.Result;
 import com.qmth.themis.common.util.ResultUtil;
 import com.qmth.themis.common.util.ResultUtil;
+import org.apache.commons.lang3.StringUtils;
 import org.springframework.web.context.request.RequestContextHolder;
 import org.springframework.web.context.request.RequestContextHolder;
 import org.springframework.web.context.request.ServletRequestAttributes;
 import org.springframework.web.context.request.ServletRequestAttributes;
 
 
@@ -57,17 +59,21 @@ public class ServletUtil {
      *
      *
      * @return
      * @return
      */
      */
-    public static String getRequestPlatform() {
+    public static Platform getRequestPlatform() {
         HttpServletRequest request = getRequest();
         HttpServletRequest request = getRequest();
         // 从header中获取platform
         // 从header中获取platform
-        String platform = request.getHeader(Constants.HEADER_PLATFORM);
+        String value = request.getHeader(Constants.HEADER_PLATFORM);
         // 如果header中不存在platform,则从参数中获取platform
         // 如果header中不存在platform,则从参数中获取platform
-        if (Objects.isNull(platform)) {
-            platform = request.getParameter(Constants.HEADER_PLATFORM);
-            if (Objects.isNull(platform)) {
+        if (Objects.isNull(value)) {
+            value = request.getParameter(Constants.HEADER_PLATFORM);
+            if (Objects.isNull(value)) {
                 throw new BusinessException(ExceptionResultEnum.PLATFORM_INVALID);
                 throw new BusinessException(ExceptionResultEnum.PLATFORM_INVALID);
             }
             }
         }
         }
+        Platform platform = Platform.findByName(value);
+        if (platform == null) {
+            throw new BusinessException(ExceptionResultEnum.PLATFORM_INVALID);
+        }
         return platform;
         return platform;
     }
     }
 
 
@@ -79,10 +85,10 @@ public class ServletUtil {
     public static String getRequestDeviceId() {
     public static String getRequestDeviceId() {
         HttpServletRequest request = getRequest();
         HttpServletRequest request = getRequest();
         // 从header中获取deviceId
         // 从header中获取deviceId
-        String deviceId = request.getHeader(Constants.HEADER_DEVICE_ID);
+        String deviceId = StringUtils.trimToNull(request.getHeader(Constants.HEADER_DEVICE_ID));
         // 如果header中不存在deviceId,则从参数中获取deviceId
         // 如果header中不存在deviceId,则从参数中获取deviceId
         if (Objects.isNull(deviceId)) {
         if (Objects.isNull(deviceId)) {
-            deviceId = request.getParameter(Constants.HEADER_DEVICE_ID);
+            deviceId = StringUtils.trimToNull(request.getParameter(Constants.HEADER_DEVICE_ID));
             if (Objects.isNull(deviceId)) {
             if (Objects.isNull(deviceId)) {
                 throw new BusinessException(ExceptionResultEnum.DEVICE_ID_INVALID);
                 throw new BusinessException(ExceptionResultEnum.DEVICE_ID_INVALID);
             }
             }
@@ -95,7 +101,7 @@ public class ServletUtil {
      *
      *
      * @return
      * @return
      */
      */
-    public static String getRequestTime() {
+    public static long getRequestTime() {
         HttpServletRequest request = getRequest();
         HttpServletRequest request = getRequest();
         // 从header中获取time
         // 从header中获取time
         String time = request.getHeader(Constants.HEADER_TIME);
         String time = request.getHeader(Constants.HEADER_TIME);
@@ -106,7 +112,11 @@ public class ServletUtil {
                 throw new BusinessException(ExceptionResultEnum.TIME_INVALID);
                 throw new BusinessException(ExceptionResultEnum.TIME_INVALID);
             }
             }
         }
         }
-        return time;
+        try {
+            return Long.parseLong(time);
+        } catch (Exception e) {
+            throw new BusinessException(ExceptionResultEnum.TIME_INVALID);
+        }
     }
     }
 
 
     /**
     /**
@@ -211,7 +221,8 @@ public class ServletUtil {
      * @return
      * @return
      */
      */
     public static HttpServletRequest getRequest() {
     public static HttpServletRequest getRequest() {
-        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
+        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder
+                .getRequestAttributes();
         return servletRequestAttributes.getRequest();
         return servletRequestAttributes.getRequest();
     }
     }
 
 
@@ -221,7 +232,8 @@ public class ServletUtil {
      * @return
      * @return
      */
      */
     public static HttpServletResponse getResponse() {
     public static HttpServletResponse getResponse() {
-        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
+        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder
+                .getRequestAttributes();
         return servletRequestAttributes.getResponse();
         return servletRequestAttributes.getResponse();
     }
     }
 
 

+ 1 - 1
themis-exam/src/main/java/com/qmth/themis/exam/api/TEStudentController.java

@@ -190,7 +190,7 @@ public class TEStudentController {
         if (teStudent.getEnable().intValue() == 0) {
         if (teStudent.getEnable().intValue() == 0) {
             throw new BusinessException(ExceptionResultEnum.STUDENT_ENABLE);
             throw new BusinessException(ExceptionResultEnum.STUDENT_ENABLE);
         }
         }
-        Platform platform = Platform.valueOf(ServletUtil.getRequestPlatform());
+        Platform platform = ServletUtil.getRequestPlatform();
         String deviceId = ServletUtil.getRequestDeviceId();
         String deviceId = ServletUtil.getRequestDeviceId();
         //添加用户鉴权缓存
         //添加用户鉴权缓存
         AuthDto authDto = cacheService.addStudentCache(teStudent.getId());
         AuthDto authDto = cacheService.addStudentCache(teStudent.getId());

+ 4 - 6
themis-exam/src/main/java/com/qmth/themis/exam/interceptor/AuthInterceptor.java

@@ -16,7 +16,6 @@ import com.qmth.themis.common.exception.BusinessException;
 import com.qmth.themis.common.signature.SignatureInfo;
 import com.qmth.themis.common.signature.SignatureInfo;
 import com.qmth.themis.common.signature.SignatureType;
 import com.qmth.themis.common.signature.SignatureType;
 import com.qmth.themis.exam.config.DictionaryConfig;
 import com.qmth.themis.exam.config.DictionaryConfig;
-import org.apache.commons.lang3.StringUtils;
 import org.slf4j.Logger;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.slf4j.LoggerFactory;
 import org.springframework.web.servlet.HandlerInterceptor;
 import org.springframework.web.servlet.HandlerInterceptor;
@@ -59,20 +58,19 @@ public class AuthInterceptor implements HandlerInterceptor {
         if (url.equalsIgnoreCase(SystemConstant.ERROR)) {
         if (url.equalsIgnoreCase(SystemConstant.ERROR)) {
             throw new BusinessException(ExceptionResultEnum.NOT_FOUND);
             throw new BusinessException(ExceptionResultEnum.NOT_FOUND);
         }
         }
-        Platform platform = Platform.valueOf(ServletUtil.getRequestPlatform());
+        Platform platform = ServletUtil.getRequestPlatform();
         String deviceId = ServletUtil.getRequestDeviceId();
         String deviceId = ServletUtil.getRequestDeviceId();
         String authorization = ServletUtil.getRequestAuthorization();
         String authorization = ServletUtil.getRequestAuthorization();
-        String time = ServletUtil.getRequestTime();
+        long time = ServletUtil.getRequestTime();
         log.info("Start authorization: url:{}, method:{}, platform:{}, deviceId:{}, authorization:{}, time:{}", url,
         log.info("Start authorization: url:{}, method:{}, platform:{}, deviceId:{}, authorization:{}, time:{}", url,
                 method, platform, deviceId, authorization, time);
                 method, platform, deviceId, authorization, time);
         //校验时间戳是否过期
         //校验时间戳是否过期
-        long timestamp = StringUtils.isNumeric(time) ? Long.parseLong(time) : 0L;
-        if (SystemConstant.expire(timestamp)) {
+        if (SystemConstant.expire(time)) {
             log.warn("Authorization faile: time expired, server time=" + System.currentTimeMillis());
             log.warn("Authorization faile: time expired, server time=" + System.currentTimeMillis());
             //throw new BusinessException(ExceptionResultEnum.AUTHORIZATION_ERROR);
             //throw new BusinessException(ExceptionResultEnum.AUTHORIZATION_ERROR);
         }
         }
         //校验签名信息
         //校验签名信息
-        final SignatureInfo info = SignatureInfo.parse(method.toLowerCase(), url, timestamp, authorization);
+        final SignatureInfo info = SignatureInfo.parse(method.toLowerCase(), url, time, authorization);
         if (info == null) {
         if (info == null) {
             log.warn("Authorization faile: signature decode error");
             log.warn("Authorization faile: signature decode error");
             throw new BusinessException(ExceptionResultEnum.AUTHORIZATION_ERROR);
             throw new BusinessException(ExceptionResultEnum.AUTHORIZATION_ERROR);