Modify the fully qualified name resolution of the class during JDK deserialization

Application scenario

Spring security oauth2 has a wonderful design, that is, it will work with access_ All the attributes related to the token are encapsulated in oauth2accesstoken. When saving, the object will be serialized into bytes and written to the database. In the resource server, we want to read the database directly to get access_ Token to verify the validity of the token. However, I don't want to introduce the dependency jar package of spring security. At this time, we can copy the source code of defaultoauth2accesstoken, the only implementation class of oauth2accesstoken in spring security, into our project, and then read byte [] through JDBC to restore the defaultoauth2accesstoken object through the JDK's own deserialization mechanism. At this time, you will encounter a problem, that is, the package of the original oauth2accesstoken is org springframework. Security, and after we copy the source code, the package name is the package CN defined by ourselves com. In this way, during deserialization, even if the fields of the two classes are exactly the same, the deserialization will fail because the fully qualified names of the class information stored in the byte stream are different.

Solution

We can define subclasses to inherit the objectinputstream of JDK, and then override the readclassdescriptor () method:

In this way, no error will be reported during deserialization. The principle is not complicated. In fact, when parsing the byte stream, it should be org. After parsing springframework. security. oauth2. common. The class of defautoauthtoken is replaced by CN. From the source code we copied com. XXXXXX. Defaultoauthtoken to achieve the purpose of "cheating". In this scenario, we can not introduce the spring security framework into the resource provider, but only use the authorization service of spring security oauth2. The resource provider directly reads the database to verify the validity of the token, rather than querying the authorization service.

summary

The above is all about the full qualified name resolution of the modified class during JDK deserialization. I hope it will be helpful to you. Interested friends can continue to refer to other related topics on this site. If there are deficiencies, please leave a message to point out. Thank you for your support!

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>