配置Spring Security JWT时暴露authenticationManagerBean报错如何解决?
错误原因
该错误的根因是Jackson序列化失败,具体触发逻辑如下:authenticationManagerBean()方法返回的是WebSecurityConfigurerAdapter.AuthenticationManagerDelegator代理类,这个类没有可供Jackson序列化的公开属性,而Jackson默认开启了SerializationFeature.FAIL_ON_EMPTY_BEANS配置,遇到无有效序列化属性的类时会直接抛出异常。
常见触发序列化的场景:
- Controller中注入的
AuthenticationManager字段被加了Lombok的@Getter注解,或被直接作为接口返回值的一部分,接口响应时触发序列化 authenticationManagerBean()方法被加了@Cacheable等序列化相关注解,缓存持久化时触发序列化
解决方案
按优先级推荐以下3种方案:
- 切断序列化触发路径(最推荐)
检查所有AuthenticationManager相关的代码:
- 移除Controller中
authenticationManager字段的@Getter注解,不要将该类对象作为接口返回值暴露 - 移除
authenticationManagerBean()方法上的@Cacheable等会触发序列化的额外注解
- 调整Jackson配置
如果确实有特殊场景需要兼容空Bean序列化,可在项目配置文件中关闭对应校验规则:
application.yml配置示例:
spring: jackson: serialization: FAIL_ON_EMPTY_BEANS: false
application.properties配置示例:
spring.jackson.serialization.FAIL_ON_EMPTY_BEANS=false
- 使用新版AuthenticationManager暴露方式
Spring Security 5.7+ 已废弃WebSecurityConfigurerAdapter,可以改用官方推荐的方式直接获取原生AuthenticationManager,避免代理类序列化问题:
@Bean public AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception { return config.getAuthenticationManager(); }
内容的提问来源于stack exchange,提问作者Jayanta Baishya
相关产品推荐
相关产品推荐

