All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.nxyfan.framework.common.safe.EncryptResponseBodyAdvice Maven / Gradle / Ivy

package com.nxyfan.framework.common.safe;

import java.lang.reflect.Method;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerExecutionChain;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import com.alibaba.fastjson.JSON;
import com.nxyfan.framework.common.annotation.CommonApiSafe;
import com.nxyfan.framework.common.cache.CommonCacheOperator;
import com.nxyfan.framework.common.constant.CommonConstant;
import com.nxyfan.framework.common.prop.CommonProperties;
import com.nxyfan.framework.common.util.CommonCryptogramUtil;
import com.nxyfan.framework.common.util.CommonServletUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;

/** 
 *
 * Describe: 对响应的数据进行加密
 * Author: Administrator  
 * Create Time: 2024年4月25日 下午2:25:23 
 * Copyright @ 2024 51LIFE  
 */
@ControllerAdvice
public class EncryptResponseBodyAdvice implements ResponseBodyAdvice {

	@Resource
    private CommonProperties commonProperties;
	
	@Override
    public boolean supports(MethodParameter methodParameter, Class> aClass) {
//		HttpServletResponse response = CommonServletUtil.getResponse();
//		if(Convert.toBool(response.getHeader("Content-Safe"), false)) {
//			return true;
//		}
//		boolean supports = false;
//		String apiSecureUrls = this.commonProperties.getApiSecureUrls();
//		if(StrUtil.isNotBlank(apiSecureUrls)) {
//			List urlsList = Convert.toList(String.class, apiSecureUrls);
//			HttpServletRequest request = CommonServletUtil.getRequest();
//	        String url = request.getServletPath();
//	        String allUrl = StrUtil.replace(url, url.lastIndexOf("/") + 1, url.length(), "**");
//	        supports = urlsList.contains(url) || urlsList.contains(allUrl);
//		}
//    	return methodParameter.hasMethodAnnotation(CommonApiSafe.class) || supports;
    	boolean supports = false;
		HttpServletRequest request = CommonServletUtil.getRequest();
		String apiSecureUrls = this.commonProperties.getApiSecureUrls();
		if(StrUtil.isNotBlank(apiSecureUrls)) {
			List urlsList = Convert.toList(String.class, apiSecureUrls);
	        String url = request.getServletPath();
	        String allUrl = StrUtil.replace(url, url.lastIndexOf("/") + 1, url.length(), "**");
	        supports = urlsList.contains(url) || urlsList.contains(allUrl);
		}
		if(!supports) {
			if("handleException".equals(methodParameter.getExecutable().getName())) {
				// 进入全局异常
				try {
					// 获取spring容器中的RequestMappingHandlerMapping
		        	RequestMappingHandlerMapping requestMappingHandlerMapping = SpringUtil.getBean("requestMappingHandlerMapping");
		        	// RequestMappingHandlerMapping是对应url和处理类方法的一个类
					HandlerExecutionChain handlerChain = requestMappingHandlerMapping.getHandler(request);
					// 通过处理链找到对应的HandlerMethod类
	                HandlerMethod handler = (HandlerMethod) handlerChain.getHandler();
	                // 获取HandlerMethod中method
	                Method method = handler.getMethod();
	                // 获取是否存在CommonApiSafe注解
	                supports = method.isAnnotationPresent(CommonApiSafe.class);
				}catch (Exception e) {
					e.printStackTrace();
				}
			}else {
				// 无异常
				supports = methodParameter.hasMethodAnnotation(CommonApiSafe.class);
			}
		}
    	return supports;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType, Class> aClass, ServerHttpRequest request, ServerHttpResponse serverHttpResponse) {
    	// 设置响应头
    	HttpServletResponse response = CommonServletUtil.getResponse();
    	if(!response.containsHeader("Content-Safe")) {
			response.addHeader("Content-Safe", "true");
		}
    	// 拿到响应的数据
        String json = JSON.toJSONString(body);
        // 拿到用户主键
        String userFlow = request.getHeaders().getFirst("Yfwn-Key");
        if(ObjectUtil.isEmpty(userFlow)) {
        	// 进行默认加密返回
            return CommonCryptogramUtil.doSm2Encrypt(json);
        }
        CommonCacheOperator commonCacheOperator = SpringUtil.getBean(CommonCacheOperator.class);
        // 获取用户信息
        Object userCacheValue = commonCacheOperator.get(CommonConstant.REDIS_INTERFACE_USER_KEY + userFlow);
        if(ObjectUtil.isEmpty(userCacheValue)) {
        	// 进行默认加密返回
            return CommonCryptogramUtil.doSm2Encrypt(json);
        }
        InterfaceUser user = Convert.convert(InterfaceUser.class, userCacheValue);
        if(ObjectUtil.isEmpty(user.getResponsePrivateKey()) || ObjectUtil.isEmpty(user.getResponsePublicKey())) {
        	// 进行默认加密返回
            return CommonCryptogramUtil.doSm2Encrypt(json);
        }
        // 进行加密返回
        return CommonCryptogramUtil.doSm2Encrypt(json, user.getResponsePublicKey(), user.getResponsePrivateKey());
    }
    
}