RedisHttpSession反序列化UID问题跟踪

news/2024/5/7 14:59:58
1.RedisHttpSession配置
package com.visy.configure;import org.springframework.context.annotation.Configuration;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;@Configuration
@EnableRedisHttpSession(maxInactiveIntervalInSeconds=100)
public class ConfigRedisSession {}
2.报错信息:
org.springframework.data.redis.serializer.SerializationException: Cannot deserialize;
nested exception is org.springframework.core.serializer.support.SerializationFailedException: 
Failed to deserialize payload. Is the byte array a result of corresponding serialization for DefaultDeserializer?; 
nested exception is java.io.InvalidClassException:
com.vz.common.model.User;
local class incompatible: stream classdesc serialVersionUID = 1, local class serialVersionUID = -6369326306393228118
3.问题跟踪
  • 注解源码
package org.springframework.session.data.redis.config.annotation.web.http;@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@Documented
@Import({RedisHttpSessionConfiguration.class})
@Configuration
public @interface EnableRedisHttpSession {int maxInactiveIntervalInSeconds() default 1800;String redisNamespace() default "";RedisFlushMode redisFlushMode() default RedisFlushMode.ON_SAVE;
}
  • Redis序列化器配置
package org.springframework.session.data.redis.config.annotation.web.http;@Configuration
@EnableScheduling
public class RedisHttpSessionConfiguration extends SpringHttpSessionConfiguration implements EmbeddedValueResolverAware, ImportAware {private Integer maxInactiveIntervalInSeconds = 1800;private ConfigureRedisAction configureRedisAction = new ConfigureNotifyKeyspaceEventsAction();private String redisNamespace = "";private RedisFlushMode redisFlushMode;private RedisSerializer<Object> defaultRedisSerializer;private Executor redisTaskExecutor;private Executor redisSubscriptionExecutor;private StringValueResolver embeddedValueResolver;public RedisHttpSessionConfiguration() {this.redisFlushMode = RedisFlushMode.ON_SAVE;}@Beanpublic RedisTemplate<Object, Object> sessionRedisTemplate(RedisConnectionFactory connectionFactory) {RedisTemplate<Object, Object> template = new RedisTemplate();template.setKeySerializer(new StringRedisSerializer());template.setHashKeySerializer(new StringRedisSerializer());if (this.defaultRedisSerializer != null) {//如果存在默认序列化器则使用template.setDefaultSerializer(this.defaultRedisSerializer);}template.setConnectionFactory(connectionFactory);return template;}//设置默认序列化器,寻找名称为”springSessionDefaultRedisSerializer“的RedisSerializer注入@Autowired( required = false)@Qualifier("springSessionDefaultRedisSerializer")public void setDefaultRedisSerializer(RedisSerializer<Object> defaultRedisSerializer) {this.defaultRedisSerializer = defaultRedisSerializer;}
}
  • 默认序列化器的默认值
package org.springframework.data.redis.core;public class RedisTemplate<K, V> extends RedisAccessor implements RedisOperations<K, V>, BeanClassLoaderAware {public void afterPropertiesSet() {super.afterPropertiesSet();boolean defaultUsed = false;if (this.defaultSerializer == null) {//默认序列化器是JdkSerializationRedisSerializerthis.defaultSerializer = new JdkSerializationRedisSerializer(this.classLoader != null ? this.classLoader : this.getClass().getClassLoader());}if (this.enableDefaultSerializer) {if (this.keySerializer == null) {this.keySerializer = this.defaultSerializer;defaultUsed = true;}if (this.valueSerializer == null) {this.valueSerializer = this.defaultSerializer;defaultUsed = true;}if (this.hashKeySerializer == null) {this.hashKeySerializer = this.defaultSerializer;defaultUsed = true;}if (this.hashValueSerializer == null) {this.hashValueSerializer = this.defaultSerializer;defaultUsed = true;}}if (this.enableDefaultSerializer && defaultUsed) {Assert.notNull(this.defaultSerializer, "default serializer null and not all serializers initialized");}if (this.scriptExecutor == null) {this.scriptExecutor = new DefaultScriptExecutor(this);}this.initialized = true;}
}
  • 反序列化过程

默认使用JdkSerializationRedisSerializer反序列化的过程

package org.springframework.data.redis.serializer;public class JdkSerializationRedisSerializer implements RedisSerializer<Object> {public Object deserialize(byte[] bytes) {if (SerializationUtils.isEmpty(bytes)) {return null;} else {try {//反序列化return this.deserializer.convert(bytes);} catch (Exception var3) {throw new SerializationException("Cannot deserialize", var3);}}}
}
package org.springframework.core.serializer.support;public class DeserializingConverter implements Converter<byte[], Object> {public Object convert(byte[] source) {ByteArrayInputStream byteStream = new ByteArrayInputStream(source);try {//反序列化return this.deserializer.deserialize(byteStream);} catch (Throwable var4) {throw new SerializationFailedException("Failed to deserialize payload. Is the byte array a result of corresponding serialization for " + this.deserializer.getClass().getSimpleName() + "?", var4);}}
}
package org.springframework.core.serializer;public class DefaultDeserializer implements Deserializer<Object> {public Object deserialize(InputStream inputStream) throws IOException {ObjectInputStream objectInputStream = new ConfigurableObjectInputStream(inputStream, this.classLoader);try {//读取对象return objectInputStream.readObject();} catch (ClassNotFoundException var4) {throw new NestedIOException("Failed to deserialize object type", var4);}}
}
package java.io;public class ObjectInputStream extends InputStream implements ObjectInput, ObjectStreamConstants {public final Object readObject()throws IOException, ClassNotFoundException {return readObject(Object.class);}private final Object readObject(Class<?> type) throws IOException, ClassNotFoundException {if (enableOverride) {return readObjectOverride();}if (! (type == Object.class || type == String.class))throw new AssertionError("internal error");// if nested read, passHandle contains handle of enclosing objectint outerHandle = passHandle;try {Object obj = readObject0(type, false);handles.markDependency(outerHandle, passHandle);ClassNotFoundException ex = handles.lookupException(passHandle);if (ex != null) {throw ex;}if (depth == 0) {vlist.doCallbacks();}return obj;} finally {passHandle = outerHandle;if (closed && depth == 0) {clear();}}}private Object readObject0(Class<?> type, boolean unshared) throws IOException {boolean oldMode = bin.getBlockDataMode();if (oldMode) {int remain = bin.currentBlockRemaining();if (remain > 0) {throw new OptionalDataException(remain);} else if (defaultDataEnd) {/** Fix for 4360508: stream is currently at the end of a field* value block written via default serialization; since there* is no terminating TC_ENDBLOCKDATA tag, simulate* end-of-custom-data behavior explicitly.*/throw new OptionalDataException(true);}bin.setBlockDataMode(false);}byte tc;while ((tc = bin.peekByte()) == TC_RESET) {bin.readByte();handleReset();}depth++;totalObjectRefs++;try {switch (tc) {case TC_NULL:return readNull();case TC_REFERENCE:// check the type of the existing objectreturn type.cast(readHandle(unshared));case TC_CLASS:if (type == String.class) {throw new ClassCastException("Cannot cast a class to java.lang.String");}return readClass(unshared);case TC_CLASSDESC:case TC_PROXYCLASSDESC:if (type == String.class) {throw new ClassCastException("Cannot cast a class to java.lang.String");}return readClassDesc(unshared);case TC_STRING:case TC_LONGSTRING:return checkResolve(readString(unshared));case TC_ARRAY:if (type == String.class) {throw new ClassCastException("Cannot cast an array to java.lang.String");}return checkResolve(readArray(unshared));case TC_ENUM:if (type == String.class) {throw new ClassCastException("Cannot cast an enum to java.lang.String");}return checkResolve(readEnum(unshared));case TC_OBJECT:if (type == String.class) {throw new ClassCastException("Cannot cast an object to java.lang.String");}return checkResolve(readOrdinaryObject(unshared));case TC_EXCEPTION:if (type == String.class) {throw new ClassCastException("Cannot cast an exception to java.lang.String");}IOException ex = readFatalException();throw new WriteAbortedException("writing aborted", ex);case TC_BLOCKDATA:case TC_BLOCKDATALONG:if (oldMode) {bin.setBlockDataMode(true);bin.peek();             // force header readthrow new OptionalDataException(bin.currentBlockRemaining());} else {throw new StreamCorruptedException("unexpected block data");}case TC_ENDBLOCKDATA:if (oldMode) {throw new OptionalDataException(true);} else {throw new StreamCorruptedException("unexpected end of block data");}default:throw new StreamCorruptedException(String.format("invalid type code: %02X", tc));}} finally {depth--;bin.setBlockDataMode(oldMode);}}private ObjectStreamClass readClassDesc(boolean unshared) throws IOException {byte tc = bin.peekByte();ObjectStreamClass descriptor;switch (tc) {case TC_NULL:descriptor = (ObjectStreamClass) readNull();break;case TC_REFERENCE:descriptor = (ObjectStreamClass) readHandle(unshared);// Should only reference initialized class descriptorsdescriptor.checkInitialized();break;case TC_PROXYCLASSDESC:descriptor = readProxyDesc(unshared);break;case TC_CLASSDESC:descriptor = readNonProxyDesc(unshared);break;default:throw new StreamCorruptedException(String.format("invalid type code: %02X", tc));}if (descriptor != null) {validateDescriptor(descriptor);}return descriptor;}private ObjectStreamClass readNonProxyDesc(boolean unshared) throws IOException {if (bin.readByte() != TC_CLASSDESC) {throw new InternalError();}ObjectStreamClass desc = new ObjectStreamClass();int descHandle = handles.assign(unshared ? unsharedMarker : desc);passHandle = NULL_HANDLE;ObjectStreamClass readDesc = null;try {readDesc = readClassDescriptor();} catch (ClassNotFoundException ex) {throw (IOException) new InvalidClassException("failed to read class descriptor").initCause(ex);}Class<?> cl = null;ClassNotFoundException resolveEx = null;bin.setBlockDataMode(true);final boolean checksRequired = isCustomSubclass();try {if ((cl = resolveClass(readDesc)) == null) {resolveEx = new ClassNotFoundException("null class");} else if (checksRequired) {ReflectUtil.checkPackageAccess(cl);}} catch (ClassNotFoundException ex) {resolveEx = ex;}// Call filterCheck on the class before reading anything elsefilterCheck(cl, -1);skipCustomData();try {totalObjectRefs++;depth++;desc.initNonProxy(readDesc, cl, resolveEx, readClassDesc(false));} finally {depth--;}handles.finish(descHandle);passHandle = descHandle;return desc;}
}
package java.io;public class ObjectStreamClass implements Serializable {void initNonProxy(ObjectStreamClass model,Class<?> cl,ClassNotFoundException resolveEx,ObjectStreamClass superDesc)throws InvalidClassException{long suid = Long.valueOf(model.getSerialVersionUID());ObjectStreamClass osc = null;if (cl != null) {osc = lookup(cl, true);if (osc.isProxy) {throw new InvalidClassException("cannot bind non-proxy descriptor to a proxy class");}if (model.isEnum != osc.isEnum) {throw new InvalidClassException(model.isEnum ?"cannot bind enum descriptor to a non-enum class" :"cannot bind non-enum descriptor to an enum class");}if (model.serializable == osc.serializable &&!cl.isArray() &&suid != osc.getSerialVersionUID()) {throw new InvalidClassException(osc.name,"local class incompatible: " +"stream classdesc serialVersionUID = " + suid +", local class serialVersionUID = " +osc.getSerialVersionUID());}if (!classNamesEqual(model.name, osc.name)) {throw new InvalidClassException(osc.name,"local class name incompatible with stream class " +"name \"" + model.name + "\"");}if (!model.isEnum) {if ((model.serializable == osc.serializable) &&(model.externalizable != osc.externalizable)) {throw new InvalidClassException(osc.name,"Serializable incompatible with Externalizable");}if ((model.serializable != osc.serializable) ||(model.externalizable != osc.externalizable) ||!(model.serializable || model.externalizable)) {deserializeEx = new ExceptionInfo(osc.name, "class invalid for deserialization");}}}this.cl = cl;this.resolveEx = resolveEx;this.superDesc = superDesc;name = model.name;this.suid = suid;isProxy = false;isEnum = model.isEnum;serializable = model.serializable;externalizable = model.externalizable;hasBlockExternalData = model.hasBlockExternalData;hasWriteObjectData = model.hasWriteObjectData;fields = model.fields;primDataSize = model.primDataSize;numObjFields = model.numObjFields;if (osc != null) {localDesc = osc;writeObjectMethod = localDesc.writeObjectMethod;readObjectMethod = localDesc.readObjectMethod;readObjectNoDataMethod = localDesc.readObjectNoDataMethod;writeReplaceMethod = localDesc.writeReplaceMethod;readResolveMethod = localDesc.readResolveMethod;if (deserializeEx == null) {deserializeEx = localDesc.deserializeEx;}domains = localDesc.domains;cons = localDesc.cons;}fieldRefl = getReflector(fields, localDesc);// reassign to matched fields so as to reflect local unshared settingsfields = fieldRefl.getFields();initialized = true;}
}
  • 报错来源
if (model.serializable == osc.serializable &&!cl.isArray() &&suid != osc.getSerialVersionUID()) {throw new InvalidClassException(osc.name,"local class incompatible: " +"stream classdesc serialVersionUID = " + suid +", local class serialVersionUID = " +osc.getSerialVersionUID());
}
4.解决方案

自定义一个序列化器,不要使用JdkSerializationRedisSerializer
以下是官方给出的自定义默认序列化器的配置方法,点击可查看

@Configuration
public class SessionConfig implements BeanClassLoaderAware {private ClassLoader loader;@Beanpublic RedisSerializer<Object> springSessionDefaultRedisSerializer() {//改用Jackson的序列化器return new GenericJackson2JsonRedisSerializer(objectMapper());}/*** Customized {@link ObjectMapper} to add mix-in for class that doesn't have default* constructors* @return the {@link ObjectMapper} to use*/private ObjectMapper objectMapper() {ObjectMapper mapper = new ObjectMapper();mapper.registerModules(SecurityJackson2Modules.getModules(this.loader));return mapper;}/** @see* org.springframework.beans.factory.BeanClassLoaderAware#setBeanClassLoader(java.lang* .ClassLoader)*/@Overridepublic void setBeanClassLoader(ClassLoader classLoader) {this.loader = classLoader;}}

http://www.mrgr.cn/p/12372365

相关文章

CISCN2023-华北-normal_snake

就得审java。 路由分析 老规矩,先看看路由:/read路由下传参data,pyload不能包含!!,然后用了yaml来load传入的参数。 稍作了解,这其实就是 SnakeYaml 反序列化漏洞,禁用了 yaml 的常用头 !!。 前面的!!是用于强制类型转化,强制转换为!!后指定的类型,其实这个和Fastjson的…

如何用Sublime Text实现正则查找与替换

比如将下面的汉字语义加上中括号[{"text": "微笑","path": "emot01.png"},{"text": "大笑","path": "emot02.png"},{"text": "鼓掌","path": "emot03.pn…

STM32之UASRT试验

一、实验目的 1.实现STM32F407开发板与上位机工具通讯,中断方式具体实现的效果:上电后,下位机主动发送hello world ,上位机收到并显示;上位机发送数字0~9 ,回复: zero ~ nine 2.通讯协议,后面补充 3.硬件使用野火开发版STM32F407 4.与开发板连接的接口是Usb转串口,根据…

什么是uniapp----分包

前言 还是同样的需求(uniapp的主包要求大小不得大于2MB),但是就算将能封装的都封装了还是会超过2MB,本文将介绍第二个优化点:分包开发 一、什么是分包开发? 有很多小伙伴一听分包开发认为就是多建几个文件夹,到时候引用就行了,说对对,但也不对,慢慢看下去就知道原因了…

80个在线小游戏源码

源码简介 搭建80个在线小游戏网站源码&#xff0c;解压即可食用&#xff0c;支持在本地浏览器打开。 安装教程 纯HTML&#xff0c;直接将压缩包上传网站目录解压即可 首页截图 源码下载 80个在线小游戏源码-小8源码屋

spring-接口大全

1. Bean 相关 1. InitializingBean InitializingBean接口为bean提供了初始化方法的方式,它只包括afterPropertiesSet方法,凡是继承该接口的类,在初始化bean的时候都会执行该方法。 demo @Component public class MyInitBean implements InitializingBean {public void after…

设计不外流,保护创意的同时锁住图纸安全!

在设计行业中,图纸和创意文稿的安全至关重要,因为它们体现了企业的创新能力和核心竞争力。华企盾DSC数据防泄密系统提供了一系列功能,可以有效地保护这些珍贵的设计和文档不被外泄。以下是如何利用华企盾DSC系统保障设计图纸安全的关键措施:全面的加密模式:华企盾DSC系统提…

告别写作难题:探索三款AI写作助手,让你的创作更高效

在互联网时代&#xff0c;写作已经成为了一项基本的技能。无论是个人博客、公众号文章、还是商业文案&#xff0c;写作都是必不可少的一环。但是&#xff0c;很多人在写作过程中会遇到各种各样的问题&#xff0c;比如缺乏灵感、语言表达不清、排版混乱等。这时候&#xff0c;AI…

dns服务器

DNS查询方式 dns服务器有两种查询方式:递归查询:在递归查询中,客户端向本地DNS服务器发送一个域名解析请求,并要求该DNS服务器负责完成整个解析过程。 如果本地DNS服务器拥有所请求的域名解析信息,则它会直接回复客户端,并负责向其他DNS服务器查询所需的信息。 如果本地D…

LM1875L-TB5-T 音频功率放大器 PDF中文资料_参数_引脚图

LM1875L-TB5-T 规格信息&#xff1a; 商品类型音频功率放大器 音频功率放大器的类型- 输出类型1-Channel (Mono) 作业电压16V ~ 60V 输出功率25W x 1 4Ω 额外特性过流保护,热保护 UTC LM1875是一款单片功率放大器&#xff0c;可为消费类音频应 用提供极低失真和高品质的…

安装1Panel管理面板

1Panel 是一个现代化、开源的 Linux 服务器运维管理面板。 安装部署:curl -sSL https://resource.fit2cloud.com/1panel/package/quick_start.sh -o quick_start.sh && bash quick_start.sh 手动安装dockerhttps://docker-practice.github.io/zh-cn/install/raspberr…

拖拽式工作流开发有什么突出优势?

在发展越来越快速的今天,拖拽式工作流开发得到了很多客户朋友的青睐与支持,是创收降本的得力助手。想要实现高效率的办公方式,可以试着了解低代码技术平台及拖拽式工作流开发的优势特点。具有好操作、好维护、够灵活、可视化界面操作等优势特点的低代码技术平台可以助力企业…

Mac读写U盘软件哪个好用 Mac读写U盘很慢怎么解决 macbookpro读取u盘

在使用Mac电脑时&#xff0c;读写U盘是一个常见的需求&#xff0c;特别是当U盘格式为NTFS时。选择适合的软件来实现这一操作至关重要。下面我们来看Mac读写U盘软件哪个好用&#xff0c;Mac读写U盘很慢怎么解决的相关内容。 一、Mac读写U盘软件哪个好用 在Mac上选择一款适合的…

深度相机(3D相机)

传统的RGB彩色相机称为2D相机&#xff0c; 只能得到2D的图像信息&#xff0c; 无法得到物体与相机的距离信息&#xff0c;也就是深度信息。 顾名思义&#xff0c; 深度相机除了获取2D信息&#xff0c;还能得到深度信息&#xff0c;也叫RGBD相机&#xff0c; 或3D相机。 顺便提…

小白PDF阅读器重排版时的自动提取背景色功能介绍及实现

小白PDF阅读器在1.35之前的版本对于有深色背景的页面重拍版时并不太完美。对于深色背景区域主要表现在不能分割排版和重排后页面元素割裂感明显。小白PDF阅读器在1.35版本主要针对这两个问题进行了优化! 最终效果对比图如下自动重排版彩色部分内容,并提取彩色背景自动提取背景…

Compilation Steps and Memory Layout of the C program

Table of ContentsTable of ContentsWhat are the four stages of the compilation process?Preprocessing Compilation Assembly LinkingWhat are the four stages of the compilation process? Normally compiling a C program is a multi-stage process and utilizes diff…

Unity读书系列《Unity3D游戏开发》——脚本(一)

文章目录 前言一、脚本模版及其拓展1、脚本模版2、拓展脚本模版 二、脚本的生命周期三、脚本的执行顺序四、脚本序列化1、序列化数据2、serializedObject3、监听部分元素修改事件 五、定时器与间隔定时器六、工作线程&#xff08;多线程&#xff09;总结 前言 脚本在Unity的重…

网络爬虫之爬虫原理

** 爬虫概述 Python网络爬虫是利用Python编程语言编写的程序&#xff0c;通过互联网爬取特定网站的信息&#xff0c;并将其保存到本地计算机或数据库中。 """ 批量爬取各城市房价走势涨幅top10和跌幅top10 """ ​ from lxml import etree impor…

Scala 04 —— Scala Puzzle 拓展

Scala 04 —— Scala Puzzle 拓展 文章目录 Scala 04 —— Scala Puzzle 拓展一、占位符二、模式匹配的变量和常量模式三、继承 成员声明的位置结果初始化顺序分析BMember 类BConstructor 类 四、缺省初始值与重载五、Scala的集合操作和集合类型保持一致性第一部分代码解释第二…

React 《组件间通信》

React组件通信概念:组件通信就是组件之间的数据传递, 根据组件嵌套关系的不同,有不同的通信手段和方法A-B 父子通信 B-C 兄弟通信 A-E 跨层通信父子通信-父传子基础实现 实现步骤父组件传递数据 - 在子组件标签上绑定属性 子组件接收数据 - 子组件通过props参数接收数据funct…