Spring Auth Server JwtGenerator类型转换异常:LinkedHashMap转OAuth2TokenFormat失败
问题详情
使用Spring Boot 3.1.1搭配spring-security-oauth2-authorization-server 1.1.1时,触发ClassCastException:
java.util.LinkedHashMap cannot be cast to org.springframework.security.oauth2.server.authorization.settings.OAuth2TokenFormat
异常发生在TokenSettings.getAccessTokenFormat()和JwtGenerator.generate()方法执行过程中。
复现场景
按照官方JPA示例创建RegisteredClient,将TokenSettings序列化为JSON后再反序列化,后续构建TokenSettings实例时触发上述异常,测试代码可稳定复现该问题。
解决方案
问题核心是Jackson序列化/反序列化TokenSettings时,无法正确识别OAuth2TokenFormat类型,需手动注册相关Jackson模块:
方案1:直接为ObjectMapper注册模块
import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.security.jackson2.SecurityJackson2Modules; import org.springframework.security.oauth2.server.authorization.jackson2.OAuth2AuthorizationServerJackson2Module; // 初始化ObjectMapper并注册所需模块 ObjectMapper objectMapper = new ObjectMapper(); objectMapper.registerModules( SecurityJackson2Modules.getModules(this.getClass().getClassLoader()), new OAuth2AuthorizationServerJackson2Module() );
方案2:通过Jackson自定义器配置(Spring Boot环境推荐)
在配置类中定义Jackson2ObjectMapperBuilderCustomizer,自动注入到Spring的ObjectMapper实例:
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.jackson2.SecurityJackson2Modules; import org.springframework.security.oauth2.server.authorization.jackson2.OAuth2AuthorizationServerJackson2Module; import org.springframework.http.converter.json.Jackson2ObjectMapperBuilderCustomizer; @Configuration public class JacksonConfig { @Bean public Jackson2ObjectMapperBuilderCustomizer authorizationServerJacksonCustomizer() { return builder -> builder.modules( SecurityJackson2Modules.getModules(this.getClass().getClassLoader()), new OAuth2AuthorizationServerJackson2Module() ); } }
内容的提问来源于stack exchange,提问作者Buks van der Lingen
相关产品推荐
相关产品推荐

