Jackson 支持

Spring Security 为持久化 Spring Security 相关类提供了 Jackson 3 支持。这可以提高在使用分布式会话(即会话复制、Spring Session 等)时序列化 Spring Security 相关类的性能。

Jackson 2 支持仍然可用,但已弃用并将在未来版本中移除,因此建议您迁移到 Jackson 3。

要使用它,请将 SecurityJacksonModules.getModules(ClassLoader) 注册到 JsonMapper.Builder (jackson-databind)。

  • Java

  • Kotlin

ClassLoader loader = getClass().getClassLoader();
JsonMapper mapper = JsonMapper.builder()
        .addModules(SecurityJacksonModules.getModules(loader))
        .build();

// ... use JsonMapper as normally ...
SecurityContext context = new SecurityContextImpl();
// ...
String json = mapper.writeValueAsString(context);
val loader = javaClass.classLoader
val mapper = JsonMapper.builder()
    .addModules(SecurityJacksonModules.getModules(loader))
    .build()

// ... use JsonMapper as normally ...
val context: SecurityContext = SecurityContextImpl()
// ...
val json: String = mapper.writeValueAsString(context)

如上所述使用 SecurityJacksonModules 能够自动包含类型信息并配置一个 PolymorphicTypeValidator 来处理类名的验证。

如果需要,您可以将自定义类添加到验证处理中。

  • Java

  • Kotlin

ClassLoader loader = getClass().getClassLoader();
BasicPolymorphicTypeValidator.Builder builder = BasicPolymorphicTypeValidator.builder()
        .allowIfSubType(MyCustomType.class);
JsonMapper mapper = JsonMapper.builder()
        .addModules(SecurityJacksonModules.getModules(loader, builder))
        .build();
val loader = javaClass.classLoader
val builder = BasicPolymorphicTypeValidator.builder()
        .allowIfSubType(MyCustomType::class)
val mapper = JsonMapper.builder()
    .addModules(SecurityJacksonModules.getModules(loader, builder))
    .build()

以下 Spring Security 模块提供 Jackson 支持:

© . This site is unofficial and not affiliated with VMware.