spring security oauth2 集成异常处理

  1. Java 8 date/time type java.time.Instant not supported by default:

自己new的ObjectMapper对象没有注册JavaTimeModule。

解决方法:

java 复制代码
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(new JavaTimeModule());
  1. 刷新token时,反序列化对象异常

异常可能有:

shell 复制代码
The class with java.lang.Long and name of java.lang.Long is not in the allowlist

相关对象添加注解

java 复制代码
@JsonDeserialize
@JsonIgnoreProperties(ignoreUnknown = true)

第二个注解使反序列化时忽略没有的属性

shell 复制代码
Unexpected token (START_OBJECT), expected START_ARRAY:need Array value to contain `As.WRAPPER_ARRAY` type information for class java.util.Map
...
you can also enable default typing.

这是由于序列化和反序列化策略不一致导致的。

  • WRAPPER_ARRAY:以数组的方式,Class Type 为第一个元素,Json字符串为第二个元素。
json 复制代码
[
    "info.leve.******.Person", 
    {
        "name": "leve", 
        "age": 18
    }
]
  • WRAPPER_OBJECT:以对象的形式,Class Type 为key, Json字符串为value。
json 复制代码
{
    "info.kleven.******.Person": {
        "name": "kleven", 
        "age": 18
    }
}
  • PROPERTY: 以属性的的方式,在Json字符串中体现为:"@class"为key,Class Type 为value。
json 复制代码
{
    "@class": "info.kleven.******.Person", 
    "name": "kleven", 
    "age": 18
}
  • EXISTING_PROPERTY: 序列化后的字符串不包含Class Type。
json 复制代码
{
    "name": "kleven", 
    "age": 18
}

spring security 使用的是PROPERTY方式,下面设置反序列化参数:

java 复制代码
/**
     * 保存token的service
     * @return 实例
     */
    @Bean
    public OAuth2AuthorizationService authorizationService() {
        var service = new JdbcOAuth2AuthorizationService(jdbcOperation, registeredClientRepository);
        JdbcOAuth2AuthorizationService.OAuth2AuthorizationRowMapper rowMapper =
                new JdbcOAuth2AuthorizationService.OAuth2AuthorizationRowMapper(registeredClientRepository);
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.registerModule(new JavaTimeModule());
        //以属性的的方式,在Json字符串中体现为:"@class"为key,Class Type 为value。
        objectMapper.activateDefaultTyping(objectMapper.getPolymorphicTypeValidator(),
                ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
        rowMapper.setObjectMapper(objectMapper);
        service.setAuthorizationRowMapper(rowMapper);
        return service;
    }
相关推荐
闪电悠米40 分钟前
黑马点评-Redis 消息队列-03_stream_consumer_group
开发语言·数据库·redis·分布式·缓存·junit·lua
DIY源码阁1 小时前
JavaSwing航班订票管理系统 - MySQL版
数据库·mysql
浪客灿心3 小时前
项目篇:模块设计与实现
数据库·c++
IT空门:门主3 小时前
Spring 注入三剑客:@Resource、@Autowired、@RequiredArgsConstructor 到底该用哪个?
java·后端·spring
南部余额3 小时前
Spring WebClient 从入门到精通
java·后端·spring
摇滚侠3 小时前
Spring 零基础入门到进阶 基于注解管理 Bean 38-43
xml·java·后端·spring·intellij-idea
流星白龙4 小时前
【MySQL高阶】26.事务(1)
数据库·mysql
云烟成雨TD4 小时前
Spring AI 1.x 系列【47】 MCP Annotations 模块
java·人工智能·spring
三十..5 小时前
Redis 核心原理与高可用架构实践
运维·数据库·redis
这个DBA有点耶5 小时前
索引优化深潜(下):索引合并、ICP 与索引设计的实战法则
数据库·mysql·架构