Application scenarios
SpringSecurityOAuth2 has a weird design, that is, it encapsulates all the belongings related to access_token into the OAuth2AccessToken, and then when saved, it will directly serialize the object into bytes and write it to the database. We want to read the database directly in the resource server to retrieve the access_token to verify the validity of the token, but we do not want to introduce SpringSecurity-related dependency polluting jar packages. At this time, you can copy the source code of the only implementation class DefaultOAuth2AccessToken in SpringSecurity into our project, and then read byte[] through JDBC, and restore the DefaultOAuth2AccessToken object through the JDK's own deserialization mechanism. At this time, you will encounter a problem, that is, the original OAuth2AccessToken package starts with org.springframework.security, and after we copy the source code, the package name starts with the package cn.com.XXXX, which we define ourselves. In this way, when deserializing, even if the fields of the two classes are exactly the same, the deserialization failure will be caused by the different fully qualified names of the class information stored in the byte stream.
Solution
We can define the subclass inherits the JDK's ObjectInputStream, and then override the readClassDescriptor() method:
@Override protected ObjectStreamClass readClassDescriptor() throws IOException, ClassNotFoundException {ObjectStreamClass read = super.readClassDescriptor();if (read.getName().startsWith("original package name")) {Class type = Class.forName(read.getName().replace("new package name"));return ObjectStreamClass.lookup(type);}return read;}This way, there will be no errors when deserializing. The principle is not complicated. In fact, when parsing the byte stream, the class that should be parsed as org.springframework.security.oauth2.common.DefautOAuthToken is replaced with the cn.com.XXXXXX.DefaultOAuthToken we copied the source code to achieve the purpose of "deception". In this scenario, we can only use the authorization service of SpringSecurityOAuth2 without introducing the SpringSecurity framework in the resource provider. The resource provider reads the database directly to verify the validity of the token, rather than querying the authorized service.
Summarize
The above is the entire content of this article about the full-qualified name resolution of modified classes during JDK deserialization. I hope it will be helpful to everyone. Interested friends can continue to refer to other related topics on this site. If there are any shortcomings, please leave a message to point it out. Thank you friends for your support for this site!