码农知识堂 - 1000bd
  •   Python
  •   PHP
  •   JS/TS
  •   JAVA
  •   C/C++
  •   C#
  •   GO
  •   Kotlin
  •   Swift
  • @ResponseBodyAdvice & @RequestBodyAdivce失效


    背景

    最近项目要有向外部提供服务的能力,但是考虑到数据安全问题,要对接口进行加解密;实现加解密的方案有很多,比如过滤器、拦截器、继承RequestResponseBodyMethodProcessor什么的,不过我最近正在了解@ResponseBodyAdvice @RequestBodyAdvice这俩注解,本着在实践中应用的目的,就准备使用这两个注解来实现加解密功能。
    然而,配置好后,请求怎么都进不到这两个注解的类里。摸索了一天的时间,@RestController 和@ResponseBody 都加了,也确认已经扫描进容器中管理了,可就是无法生效。

    原因

    后来发现项目中之前有对所有的controller进行返回结果的统一包装,使用的是继承RequestResponseBodyMethodProcessor类来实现;
    刚刚@ResponseBodyAdvice和@RequestBodyAdvice一直无法生效,就在RequestResponseBodyMethodProcessor这里面做了加密的动作,后来不经意间,把这个类在WebMvcConfigurer中导入的代码注掉了,惊奇的发现@ResponseBodyAdvice @RequestBodyAdvice这俩注解生效了。
    所以初步定位 @ResponseBodyAdvice @RequestBodyAdvice 和RequestResponseBodyMethodProcessor 会冲突导致不生效。

    解决

    RequestResponseBodyMethodProcessor 里的逻辑抽取到@ResponseBodyAdvice里,本来这个也是对返回结果进行增强的,所以放到这里也非常合理。
    同时扩展了加密的逻辑。

    核心代码

    
    @ControllerAdvice
    public class ResponseProcessor implements ResponseBodyAdvice {
        private ObjectMapper om = new ObjectMapper();
        @Autowired
        EncryptProperties encryptProperties;
    
        @Override
        public boolean supports(MethodParameter methodParameter, Class> aClass) {
            return methodParameter.hasMethodAnnotation(Encrypt.class);
        }
    
        @Override
        public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType, Class> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
            byte[] keyBytes = encryptProperties.getKey().getBytes();
            try {
                if(!methodParameter.hasMethodAnnotation(NoResponseWrapperAnnotation.class)){
                    body = new ResponseWrapper<>(body);
                }
                body = AESUtils.encrypt(JSONObject.toJSONString(body),encryptProperties.getKey());
    
            } catch (Exception e) {
                e.printStackTrace();
            }
            return body;
        }
    }
    ```
    
    
    ```java
    @ControllerAdvice
    public class RequestProcessor extends RequestBodyAdviceAdapter {
        @Autowired
        private EncryptProperties encryptProperties;
        @Override
        public boolean supports(MethodParameter methodParameter, Type targetType, Class> converterType) {
            return methodParameter.hasMethodAnnotation(Decrypt.class) || methodParameter.hasParameterAnnotation(Decrypt.class);
        }
    
        @Override
        public HttpInputMessage beforeBodyRead(final HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class> converterType) throws IOException {
            byte[] body = new byte[inputMessage.getBody().available()];
            inputMessage.getBody().read(body);
            try {
                String decrypt = AESUtils.decrypt(new String(body), encryptProperties.getKey());
                final ByteArrayInputStream bais = new ByteArrayInputStream(decrypt.getBytes());
                return new HttpInputMessage() {
                    @Override
                    public InputStream getBody() throws IOException {
                        return bais;
                    }
    
                    @Override
                    public HttpHeaders getHeaders() {
                        return inputMessage.getHeaders();
                    }
                };
            } catch (Exception e) {
                e.printStackTrace();
            }
            return super.beforeBodyRead(inputMessage, parameter, targetType, converterType);
        }
    }
    ```
    
    ```java
    public class AESUtils {
        private static final String KEY_ALGORITHM = "AES";
        private static final String DEFAULT_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";//默认的加密算法
    
        public static String getKey(int len){
            if(len % 16 != 0){
                System.out.println("长度要为16的整数倍");
                return null;
            }
    
            char[] chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".toCharArray();
            char[] uuid = new char[len];
    
            if (len > 0) {
                for (int i = 0; i < len; i++) {
                    int x = (int) (Math.random() * (len - 0 + 1) + 0);
                    uuid[i] = chars[x % chars.length];
                }
            }
    
            return new String(uuid);
        }
    
    
        public static String byteToHexString(byte[] bytes){
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < bytes.length; i++) {
                String strHex=Integer.toHexString(bytes[i]);
                if(strHex.length() > 3){
                    sb.append(strHex.substring(6));
                } else {
                    if(strHex.length() < 2){
                        sb.append("0" + strHex);
                    } else {
                        sb.append(strHex);
                    }
                }
            }
            return  sb.toString();
        }
    
        /**
         * AES 加密操作
         *
         * @param content 待加密内容
         * @param key 加密密码
         * @return 返回Base64转码后的加密数据
         */
        public static String encrypt(String content, String key) {
            try {
                Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);// 创建密码器
    
                byte[] byteContent = content.getBytes("utf-8");
    
                cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(key));// 初始化为加密模式的密码器
    
                byte[] result = cipher.doFinal(byteContent);// 加密
    
                return org.apache.commons.codec.binary.Base64.encodeBase64String(result);//通过Base64转码返回
            } catch (Exception ex) {
                ex.printStackTrace();
            }
    
            return null;
        }
    
        /**
         * AES 解密操作
         *
         * @param content
         * @param key
         * @return
         */
        public static String decrypt(String content, String key) {
    
            try {
                //实例化
                Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
    
                //使用密钥初始化,设置为解密模式
                cipher.init(Cipher.DECRYPT_MODE, getSecretKey(key));
    
                //执行操作
                byte[] result = cipher.doFinal(org.apache.commons.codec.binary.Base64.decodeBase64(content));
    
                return new String(result, "utf-8");
            } catch (Exception ex) {
                ex.printStackTrace();
            }
    
            return null;
        }
    
        private static SecretKeySpec getSecretKey(final String key) throws UnsupportedEncodingException {
            //返回生成指定算法密钥生成器的 KeyGenerator 对象
    //        KeyGenerator kg = null;
    
            //            kg = KeyGenerator.getInstance(KEY_ALGORITHM);
    //
    //            //AES 要求密钥长度为 128
    //            kg.init(128, new SecureRandom(key.getBytes()));
    //
    //            //生成一个密钥
    //            SecretKey secretKey = kg.generateKey();
    
            return new SecretKeySpec(Arrays.copyOf(key.getBytes("utf-8"), 16), KEY_ALGORITHM);// 转换为AES专用密钥
    
        }
    }
    ```
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
  • 相关阅读:
    面试经典sql(大数据):同时在线人数
    【【萌新的SOC学习之SD卡读写TXT文本实验】】
    双十一买什么蓝牙耳机?价廉物美的蓝牙耳机推荐
    [c++ STL]set使用详解
    通讯协议学习之路:RS422协议理论
    java利用EasyExcel实现导入功能,并返回错误信息的所属行列
    Mysql安装 终端配置 navicat连接
    中视频伙伴计划开通收益功能的方法和使用介绍
    Vue3 使用createWebHistory 页面刷新变成白页,报错 404, 解决方法
    配置github
  • 原文地址:https://blog.csdn.net/weixin_37545216/article/details/133952101
    • 最新文章
    • 【JVM】编译执行与解释执行的区别是什么?JVM 使用哪种方式?
      用 Hashids 优雅解决 C 端自增 ID 暴露问题
      V8引擎 精品漫游指南--Ignition篇(上) 指令 栈帧 槽位 调用约定 内存布局 基础内容
      LLVM Pass快速入门(四):代码插桩
      milkup:桌面端 markdown AI续写和即时渲染
      基于项目工程构建SBOM(软件物料清单)的研究
      鸿蒙应用开发UI基础第二节:鸿蒙应用程序框架核心解析与实操
      .NET 中如何快速实现 List 集合去重?
      扣子Coze实战:从0到1打造抖音+小红书热点监控智能体
      浅谈数据访问层
    • 热门文章
    • 十款代码表白小特效 一个比一个浪漫 赶紧收藏起来吧!!!
      奉劝各位学弟学妹们,该打造你的技术影响力了!
      五年了,我在 CSDN 的两个一百万。
      Java俄罗斯方块,老程序员花了一个周末,连接中学年代!
      面试官都震惊,你这网络基础可以啊!
      你真的会用百度吗?我不信 — 那些不为人知的搜索引擎语法
      心情不好的时候,用 Python 画棵樱花树送给自己吧
      通宵一晚做出来的一款类似CS的第一人称射击游戏Demo!原来做游戏也不是很难,连憨憨学妹都学会了!
      13 万字 C 语言从入门到精通保姆级教程2021 年版
      10行代码集2000张美女图,Python爬虫120例,再上征途
    小工具 小游戏
    Copyright © 2022 侵权请联系2656653265@qq.com    京ICP备2022015340号-1

    京公网安备 11010502049817号