在执行redis.get(key)的时候,得到
{"@type":"com.alibaba.fastjson.JSONObject","appContext":"logback"}
说明:序列化之后发现json串中有"@type":"com.alibaba.fastjson.JSONObject",其中"@type"键对应的value指定任意反序列化类名,由此造成反序列化漏洞。
方法一
解决办法
String x = redis.get(key);
if(x.contains("com.alibaba.fastjson.JSONObject")){
com.alibaba.fastjson.JSONObject xJsonObject = JSON.parseObject(x, com.alibaba.fastjson.JSONObject.class);
if(xJsonObject==null){
return "";
}
x= xJsonObject.toString();
if(StringUtils.isBlank(x)){
return "";
}
}
System.out.println(x);
fastjson包
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.83</version>
</dependency>
方法二
工具类
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import java.lang.reflect.Type;
public class MyDeserializer implements JsonDeserializer<com.alibaba.fastjson.JSONObject> {
@Override
public com.alibaba.fastjson.JSONObject deserialize(JsonElement json, Type typeofT, JsonDeserializationContext context) throws JsonParseException {
String className = json.getAsJsonObject().get("@type").getAsString();
Class<?> clazz;
try {
clazz = Class.forName(className);
} catch (Exception e) {
throw new JsonParseException("Invalid class name: " + className, e);
}
return context.deserialize(json, clazz);
}
}
main方法
String x = "{\"@type\":\"com.alibaba.fastjson.JSONObject\",\"appContext\":\"logback\",\"insertTime\":\"10.4.73.184\"}";
Gson gson = new GsonBuilder().registerTypeAdapter(com.alibaba.fastjson.JSONObject.class,new MyDeserializer()).create();
CacheJson coq = gson.fromJson(x,CacheJson.class);
System.out.println("工具类="+JSONObject.toJSON(coq));
插件
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.8</version>
</dependency>
运行结果:
工具类={"insertTime":"10.4.73.184","ip":"10.4.73.184","appContext":"logback"}