1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980 |
- package com.zanxiang.sdk.adapter;
- import com.zanxiang.common.enums.DeviceTypeEnum;
- import com.zanxiang.common.enums.HttpStatusEnum;
- import com.zanxiang.common.exception.CustomException;
- import com.zanxiang.common.utils.StringUtils;
- import com.zanxiang.mybatis.entity.GameExt;
- import com.zanxiang.sdk.annotation.UnSignCheck;
- import com.zanxiang.sdk.service.IGameExtService;
- import com.zanxiang.sdk.util.SignUtil;
- import lombok.extern.slf4j.Slf4j;
- import org.apache.logging.log4j.util.Strings;
- import org.springframework.stereotype.Component;
- import org.springframework.stereotype.Service;
- import org.springframework.web.method.HandlerMethod;
- import org.springframework.web.servlet.HandlerInterceptor;
- import javax.annotation.Resource;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import java.util.Objects;
- /**
- * @author : lingfeng
- * @time : 2022-09-28
- * @description : 拦截器
- */
- @Component
- @Service
- @Slf4j
- public class WebHandlerAdapter implements HandlerInterceptor {
- @Resource
- private IGameExtService gameExtService;
- @Override
- public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
- HandlerMethod handlerMethod = (HandlerMethod) handler;
- //排除签名认证接口注解
- UnSignCheck unSignCheck = handlerMethod.getMethod().getAnnotation(UnSignCheck.class);
- //接口签名验证
- if (unSignCheck == null) {
- return this.signCheck(request);
- }
- return Boolean.TRUE;
- }
- private boolean signCheck(HttpServletRequest request) throws Exception {
- //游戏id和密钥
- String gameId = request.getHeader("gameId");
- String sign = request.getHeader("sign");
- String timestamp = request.getHeader("timestamp");
- String os = request.getHeader("os");
- String deviceType = request.getHeader("deviceType");
- //必传参数判断
- if (StringUtils.isAnyEmpty(gameId, sign, timestamp, os, deviceType)) {
- log.error("非法参数, 请求头中缺少必传参数");
- throw new CustomException(HttpStatusEnum.INVALID_PARAMS);
- }
- //前端类型检测
- DeviceTypeEnum deviceTypeEnum = DeviceTypeEnum.getByDeviceType(Integer.valueOf(deviceType));
- if (deviceTypeEnum == null) {
- throw new CustomException(HttpStatusEnum.INVALID_PARAMS);
- }
- //签名验证
- GameExt gameExt = gameExtService.getByGameAppId(gameId);
- if (gameExt == null || Strings.isBlank(gameExt.getAppKey())) {
- log.error("非法参数, 游戏id对应的前端密钥appKey不存在");
- throw new CustomException(HttpStatusEnum.INVALID_PARAMS);
- }
- String str = "appKey=" + gameExt.getAppKey() + "&gameId=" + gameId + "×tamp=" + timestamp;
- String mySign = SignUtil.MD5(str);
- //签名对比
- if (!Objects.equals(mySign, sign)) {
- log.error("非法参数, 签名错误, mySign : {}, sign : {}, str : {}", mySign, sign, str);
- throw new CustomException(HttpStatusEnum.INVALID_PARAMS);
- }
- return Boolean.TRUE;
- }
- }
|