spring aop访问请求日志,接口验签,参数验证


@Slf4j
@Aspect
@Order(2)
@Configuration
public class AuthCheckerAspect {

    private ThreadLocal<HashMap<String, Object>> currentThreadLocal = new ThreadLocal();

    @Value("${yylc.auth.appKey}")
    private String appKey;
    @Value("${yylc.auth.appSecret}")
    private String appSecret;

    @Pointcut("execution(* com.consume.yylc.controller.api..*.*(..)) && @within(com.consume.yylc.common.annotation.AuthChecker)")
    public void authCheckerPointcut() {
    }

    /*
     * 方法调用前触发
     * @param joinPoint
     */
    @Before("authCheckerPointcut()")
    public void doBeforeAuthChecker(JoinPoint joinPoint) {
        HashMap<String, Object> hash = new HashMap<>();
        hash.put("beginTimeMillis", System.currentTimeMillis());
        currentThreadLocal.set(hash);
    }


    /*
     *
     * @Title:doAfterInServiceLayer
     * @Description: 方法调用后触发
     *  记录结束时间
     * @param joinPoint*/

    @After("authCheckerPointcut()")
    public void doAfterAuthChecker(JoinPoint joinPoint) {
        long beginTimeMillis = (long) currentThreadLocal.get().get("beginTimeMillis");
        long endTimeMillis = System.currentTimeMillis();

        log.info("-------------------->验签用时:" + (endTimeMillis - beginTimeMillis) + "ms");
    }


    /*
     *
     * @Title:doAround
     * @Description: 环绕触发
     * @return
     * @throws Throwable
     */
    @Around("authCheckerPointcut()")
    public Object doAround(ProceedingJoinPoint pjoinPoint) throws Throwable {

        // 接收到请求,记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        HttpServletResponse response = attributes.getResponse();

        String uri = request.getRequestURI();
        String method = request.getMethod();

        log.info("--------------------> uri=" + uri + "; 参数验签开始......");
        if ("POST".equals(method)) {

            Object[] paramsArray = pjoinPoint.getArgs();
            Object param1 = paramsArray[0];

            String body = "";
            if (param1 instanceof JSONObject) {
                body = ((JSONObject) param1).toJSONString();
            } else {
                SerializeConfig config = SerializeConfig.getGlobalInstance();
                body = JSON.toJSONString(param1, config, SerializerFeature.SortField);//@JSONField(serialize = false)
            }

            if (!SignUtils.validSign(body, request, appSecret)) {
                response.setHeader("Content-Type", "application/json;charset=UTF-8");

                //422 Unprocessable Entry - 请求数据验证错误
                response.setStatus(422);

                log.info("--------------------> uri=" + uri + "; 参数验签失败......");

                return new ApiResult(422, "请求数据验证错误");

            } else {
                return pjoinPoint.proceed();
            }
        } else {
            log.info("--------------------> uri=" + uri + "; 参数验签失败......");
            return new ApiResult(422, "请求方式有误");
        }
    }

}

@Slf4j
@Aspect
@Order(1)
@Component
public class WebRequestLogAspect {

    private ThreadLocal<RequestLogs> currentThreadLocal = new ThreadLocal<RequestLogs>();

    @Autowired
    private IRequestLogsService requestLogsService;

    @Pointcut(value = "execution(* com.consume.yylc.controller..*.*(..)) && @annotation(com.consume.yylc.common.annotation.WebRequestLog)")
    public void webRequestLogPoint() {
    }

    @Before("webRequestLogPoint() && @annotation(webRequestLog)")
    public void doBefore(JoinPoint joinPoint, WebRequestLog webRequestLog) {
        try {

            LocalDateTime beginTime = LocalDateTime.now();

            // 接收到请求,记录请求内容
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = attributes.getRequest();
            String beanName = joinPoint.getSignature().getDeclaringTypeName();
            String methodName = joinPoint.getSignature().getName();
            String uri = request.getRequestURI();
            String remoteAddr = getIpAddr(request);
            String method = request.getMethod();
            String params = "";
            if ("POST".equals(method)) {
                Object[] paramsArray = joinPoint.getArgs();
                params = argsArrayToString(paramsArray);
            } else {
                Map<?, ?> paramsMap = (Map<?, ?>) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
                params = paramsMap.toString();
            }

            log.info("===============>接口请求数据: uri=" + uri + "; beanName=" + beanName + "; ip=" + remoteAddr + ";" +
                    "; methodName=" + methodName + "; params=" + params);

            RequestLogs optLog = new RequestLogs();
            optLog.setUrl(uri);
            optLog.setIp(remoteAddr);
            optLog.setParams(params != null ? params : "");
            optLog.setCreateTime(beginTime);
            optLog.setInterfaceName(webRequestLog.interfaceEnum().getInterfaceName());
            optLog.setBusinessId(getBusinessId(joinPoint, webRequestLog));
            currentThreadLocal.set(optLog);

        } catch (Exception e) {
            log.error("===============>接口请求日志记录失败doBefore()***", e);
        }
    }

    @AfterReturning(returning = "result", pointcut = "webRequestLogPoint()")
    public void doAfterReturning(Object result) {
        try {
            RequestLogs optLog = currentThreadLocal.get();
            optLog.setResponse(result.toString());
            long beginTime = optLog.getCreateTime().toInstant(ZoneOffset.of("+8")).toEpochMilli();
            long costTime = (System.currentTimeMillis() - beginTime) / 1000;
            optLog.setCostTime((int) costTime);

            ApiResult apiResult = (ApiResult) result;
            optLog.setCode(apiResult.getCode().toString());

            log.info("===============>接口url:" + optLog.getUrl() + "    响应数据:" + result);

            requestLogsService.save(optLog);
        } catch (Exception e) {
            log.error("===============>接口请求日志记录失败doAfterReturning()", e);
        }
    }


    /**
     * @param joinPoint
     * @param e
     */
    @AfterThrowing(pointcut = "webRequestLogPoint()", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, Throwable e) {

        try {
            // 接收到请求,记录请求内容
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = attributes.getRequest();
            String beanName = joinPoint.getSignature().getDeclaringTypeName();
            String methodName = joinPoint.getSignature().getName();
            String uri = request.getRequestURI();
            String remoteAddr = getIpAddr(request);
            String params = "";

            log.error("===============>接口请求出现异常");
            log.error("uri=" + uri + "; beanName=" + beanName + "; ip=" + remoteAddr + ";" +
                    "; methodName=" + methodName + "; params=" + params);
            log.error("异常信息:" + e.getMessage());
            log.error("==============================");

        } catch (Exception ee) {
            log.error("===============>接口请求日志记录失败doAfterReturning()***", ee);
        }

    }


    private String getBusinessId(JoinPoint joinPoint, WebRequestLog requestLog) {
        String businessId = requestLog.businessId();
        if (businessId == "") {
            return "";
        }

        try {
            ExpressionParser parser = new SpelExpressionParser();
            EvaluationContext ec = new StandardEvaluationContext();
            int i = 0;
            for (Object obj : joinPoint.getArgs()) {
                ec.setVariable("arg" + (i++), obj);
            }
            if (businessId.contains("arg")) {
                businessId = parser.parseExpression(businessId).getValue(ec, java.lang.String.class);
            } else {
                return businessId;
            }
        } catch (Exception e) {
            log.error("解析SpEL表达式异常", e);
        }
        return businessId;
    }


    /**
     * 获取登录用户远程主机ip地址
     *
     * @param request
     * @return
     */
    private String getIpAddr(HttpServletRequest request) {

        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        final String[] arr = ip.split(",");
        for (final String str : arr) {
            if (!"unknown".equalsIgnoreCase(str)) {
                ip = str;
            }
            break;
        }

        return ip;
    }

    /**
     * 请求参数拼装
     *
     * @param paramsArray
     * @return
     */
    private String argsArrayToString(Object[] paramsArray) {
        String params = "";
        if (paramsArray != null && paramsArray.length > 0) {
            for (int i = 0; i < paramsArray.length; i++) {
                String body;
                Object curParam = paramsArray[i];

                if (curParam instanceof HttpServletRequest || curParam instanceof HttpServletResponse) {
                    continue;
                }

                if (curParam instanceof JSONObject) {
                    body = ((JSONObject) curParam).toJSONString();
                } else {
                    SerializeConfig config = SerializeConfig.getGlobalInstance();
                    body = JSON.toJSONString(curParam, config, SerializerFeature.SortField);//@JSONField(serialize = false)
                }
                params += body + " ";
            }
        }
        return params.trim();
    }
}

@Slf4j
@ControllerAdvice
@ResponseBody
public class GlobalDefaultException {

    @ExceptionHandler(Exception.class)
    public ApiResult handle(HttpServletRequest req, Exception e) {

        log.error("===================错误的异常请求url " + req.getRequestURL(),e);

        if(e instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException ee=(MethodArgumentNotValidException)e;
            //按需重新封装需要返回的错误信息
            List<ArgumentInvalidResult> invalidArguments = new ArrayList<>();
            //解析原错误信息,封装后返回,此处返回非法的字段名称,原始值,错误信息
            for (FieldError error : ee.getBindingResult().getFieldErrors()) {
                ArgumentInvalidResult invalidArgument = new ArgumentInvalidResult();
                invalidArgument.setDefaultMessage(error.getDefaultMessage());
                invalidArgument.setField(error.getField());
                invalidArgument.setRejectedValue(error.getRejectedValue());
                invalidArguments.add(invalidArgument);
            }

            return new ApiResult(422,"参数传入有问题",invalidArguments);

        }else if (e instanceof BusinessException) {
            BusinessException businessException = (BusinessException) e;
            log.error("==============业务逻辑异常 " + businessException.getMsg(),e);
            return new ApiResult(ResultInfoEnum.BUSINESS_ERROR.getCode(),
                    ResultInfoEnum.BUSINESS_ERROR.getMsg());
        } else if (e instanceof DataDoException) {
            DataDoException dataDoException = (DataDoException) e;
            log.error("=============sql,数据库操作异常 " + dataDoException.getMsg(),e);
            return new ApiResult(ResultInfoEnum.SQL_ERROR.getCode(), ResultInfoEnum.SQL_ERROR.getMsg());
        } else {
            log.error("============系统异常" + e.getMessage(),e);
            return new ApiResult(ResultInfoEnum.SYSTEM_ERROR.getCode(), ResultInfoEnum.SYSTEM_ERROR.getMsg());
        }
    }

}
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 214,717评论 6 496
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,501评论 3 389
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 160,311评论 0 350
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,417评论 1 288
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,500评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,538评论 1 293
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,557评论 3 414
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,310评论 0 270
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,759评论 1 307
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,065评论 2 330
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,233评论 1 343
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,909评论 5 338
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,548评论 3 322
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,172评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,420评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,103评论 2 365
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,098评论 2 352

推荐阅读更多精彩内容