0


Feign请求及响应拦截器

feign请求拦截,处理head、param、body参数,附加解密定制化处理,也可以使用原生解码器;

package com.config;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import com.utils.EncryptAES;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import feign.Util;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Slf4j
@Configuration
public class FeignClientConfig {
    @Bean
    public RequestInterceptor headerInterceptor() {
        //重写请求拦截器
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate requestTemplate) {
                //设置单独处理feign请求
                requestTemplate.header("feign-aes", "true");
                
                ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                if (attributes == null) {
                    return;
                }
                
                //处理head
                HttpServletRequest request = attributes.getRequest();
                Enumeration<String> headerNames = request.getHeaderNames();
                if (null != headerNames) {
                    while (headerNames.hasMoreElements()) {
                        String name = headerNames.nextElement();
                        String values = request.getHeader(name);
                        requestTemplate.header(name, values);
                    }
                }

                //处理RequestParam
                Map<String, Collection<String>> queries = requestTemplate.queries();

                if (null != queries) {
                    Map<String, Collection<String>> newQueries = new HashMap<>();
                    for (Map.Entry<String, Collection<String>> entry : queries.entrySet()) {
                        Collection<String> value = new ArrayList<>();
                        Collection<String> pram = entry.getValue();
                        value.add(EncryptAES.encryptAES((List)pram.get(0)));
                        newQueries.put(entry.getKey(), value);
                    }
                    requestTemplate.queries(null);// 替换原有对象 原对象设为空,否则会追加
                    requestTemplate.queries(newQueries);// 替换原有对象
                }

                //处理请求body
                String method = requestTemplate.method();
                if (null != requestTemplate.body()) {
                    int length = requestTemplate.body().length;
                    if (0 < length) {
                        String body = requestTemplate.requestBody().asString();
                        if (StringUtils.isNotBlank(body)) {
                            String decryptStr = EncryptAES.encryptAES(body);
                            Map<String, Object> map = Maps.newHashMap();
                            map.put("encryData", decryptStr);
                            String jsonString = JSON.toJSONString(map);
                            byte[] bodyData = jsonString.getBytes(Util.UTF_8);// 替换请求体
                            requestTemplate.body(bodyData, Util.UTF_8);
                        }
                    }
                }
                log.info("FeignClient request headers:{}.", requestTemplate.headers());

            }
        };
    }

}

feign响应拦截,处理head、param、body参数,附加解密定制化处理,也可以使用原生解码器;

package com.config;

import com.alibaba.fastjson.JSON;
import com.utils.EncryptAES;
import feign.FeignException;
import feign.Response;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.support.SpringDecoder;

import java.io.IOException;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class FeignClientResponseInterceptor extends SpringDecoder {

    public FeignClientResponseInterceptor(ObjectFactory<HttpMessageConverters> messageConverters) {
        super(messageConverters);
    }

    @Override
    public Object decode(final Response response, Type type) throws IOException, FeignException {
        Map<String, Collection<String>> requestHeadMap = response.request().headers();
        //设置单独处理feign请求
        List<String> strings = (List<String>) requestHeadMap.get("feign-aes");
        String header = strings.get(0);
        Response.Body body = response.body();
        String resultStr = "";
        if ("true".equals(header)) {
            String bodyString = IOUtils.toString(body.asReader(StandardCharsets.UTF_8));
            HashMap<String, String> hashMap = JSON.parseObject(bodyString, HashMap.class);
            String value = hashMap.get("value");
            String decryptAES = EncryptAES.decryptAES(value);
            resultStr = decryptAES;
        }
        Object o = super.decode(response.toBuilder().body(resultStr, StandardCharsets.UTF_8).build(), type);
        return o;
    }

}

附件加解密工具(支持格式化\r\n、\r\t)等格式化代码加解密,五年验证品质保证

package com.utils;

import lombok.extern.slf4j.Slf4j;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.SecureRandom;
import java.util.Base64;

@Slf4j
public class EncryptAES {
    private static final String ENCODING = "UTF-8";
    private static final String PASSWORD = "PASSWORD_KEY"; //加密秘钥

    /**
     * 对字符串加密
     */
    public static String encryptAES(String content) {
        byte[] encryptResult = encrypt(content);
        String encryptResultStr = parseByte2HexStr(encryptResult);
        // BASE64位加密
        encryptResultStr = strEncrypt(encryptResultStr);
        return encryptResultStr;
    }

    /**
     * 对字符串解密
     */
    public static String decryptAES(String content) {
        // BASE64位解密
        try {
            String decrypt = strDecrypt(content);
            byte[] decryptFrom = parseHexStr2Byte(decrypt);
            byte[] decryptResult = decrypt(decryptFrom);
            return new String(decryptResult);
        } catch (Exception e) {
            log.error("解密异常", e);
            return null;
        }
    }

    /**
     * 加密
     */
    private static byte[] encrypt(String content) {
        try {
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            // 注意这句是关键,防止linux下 随机生成key。用其他方式在Windows上正常,但Linux上会有问题
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            secureRandom.setSeed(PASSWORD.getBytes());
            kgen.init(128, secureRandom);
            SecretKey secretKey = kgen.generateKey();
            byte[] enCodeFormat = secretKey.getEncoded();
            SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
            Cipher cipher = Cipher.getInstance("AES");// 创建密码器
            byte[] byteContent = content.getBytes("utf-8");
            cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
            byte[] result = cipher.doFinal(byteContent);
            return result; // 加密
        } catch (Exception e) {
            log.error("加密异常", e);
        }
        return null;
    }

    /**
     * 解密
     */
    private static byte[] decrypt(byte[] content) {
        try {
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            // 防止linux下 随机生成key
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            secureRandom.setSeed(PASSWORD.getBytes());
            kgen.init(128, secureRandom);
            SecretKey secretKey = kgen.generateKey();
            byte[] enCodeFormat = secretKey.getEncoded();
            SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
            Cipher cipher = Cipher.getInstance("AES");// 创建密码器
            cipher.init(Cipher.DECRYPT_MODE, key);// 初始化
            byte[] result = cipher.doFinal(content);
            return result; // 解密
        } catch (Exception e) {
            log.error("解密异常", e);
        }
        return null;
    }

    /**
     * 加密字符串
     */
    private static String strEncrypt(String str) {
        String result = str;
        if (str != null && str.length() > 0) {
            try {
                byte[] encodeByte = str.getBytes(ENCODING);
                result = new String(Base64.getEncoder().encode(encodeByte));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        // base64加密超过一定长度会自动换行 需要去除换行符
        return result.replaceAll("\r\n", "").replaceAll("\r", "").replaceAll("\n", "");
    }

    /**
     * 解密字符串
     */
    private static String strDecrypt(String str) {
        try {
            byte[] encodeByte = Base64.getDecoder().decode(str.getBytes());
            return new String(encodeByte);
        } catch (Exception e) {
            log.error("IO 异常", e);
            return str;
        }
    }

    /**
     * 将二进制转换成16进制
     */
    private static String parseByte2HexStr(byte buf[]) {
        StringBuffer sb = new StringBuffer();

        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }

        return sb.toString();
    }

    /**
     * 将16进制转换为二进制
     */
    private static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1) {
            return null;
        }
        byte[] result = new byte[hexStr.length() / 2];

        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }

}
标签: java postman json

本文转载自: https://blog.csdn.net/fivehundredyearsago/article/details/125236686
版权归原作者 五百年前FHYA 所有, 如有侵权,请联系我们删除。

“Feign请求及响应拦截器”的评论:

还没有评论