Spring Security OAuth2中Resource Server JwtDecoder时钟偏移量设置

部署运行你感兴趣的模型镜像

一、问题描述

在集成 Spring Security OAuth2Resource Server 并采用 JWT 模式后,实际使用过程中发现 JWT 的失效时间(exp)并不是严格按照令牌中的 exp 属性来判定。多次测试后发现,JWT 实际失效时间比 exp 属性晚了约1分钟。这意味着,令牌过期后,服务端仍会有一分钟的“宽限期”允许访问。这种行为可能导致安全隐患,尤其是在对令牌有效期要求严格的场景下。

二、如何修改JwtDecoder的时间偏移量

通过分析 Spring Security OAuth2 的源码,包括 OAuth2ResourceServerConfigurer、JwtConfigurer、JwtDecoder 以及 NimbusJwtDecoder,发现 JWT 的时间校验逻辑由 JwtTimestampValidator 控制。默认情况下,JwtTimestampValidator 会有60秒的时钟偏移量(Clock Skew),用于容忍服务器之间的时间不同步。
在这里插入图片描述

NimbusJwtDecoder 支持自定义 JwtValidator,而 JwtTimestampValidator 的构造方法可以传入 Duration 类型的偏移量。
在这里插入图片描述

要严格按照 JWT 的 exp 属性判定令牌有效期,可以将时钟偏移量设置为0,只需将其设置为 Duration.ZERO 即可,具体做法如下:

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.jwt.JwtTimestampValidator;
import org.springframework.security.oauth2.jwt.JwtValidators;
import org.springframework.security.oauth2.jwt.NimbusJwtDecoder;

import java.time.Duration;

@Configuration
public class MyJwtDecoderConfig implements BeanPostProcessor {

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof NimbusJwtDecoder nimbusJwtDecoder) {
            // 设置JwtValidator的时间偏移量为0,令JWT严格按照exp属性判定有效期
            nimbusJwtDecoder.setJwtValidator(JwtValidators.createDefaultWithValidators(new JwtTimestampValidator(Duration.ZERO)));
            return nimbusJwtDecoder;
        }
        return bean;
    }
}

您可能感兴趣的与本文相关的镜像

Seed-Coder-8B-Base

Seed-Coder-8B-Base

文本生成
Seed-Coder

Seed-Coder是一个功能强大、透明、参数高效的 8B 级开源代码模型系列,包括基础变体、指导变体和推理变体,由字节团队开源

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

罗小爬EX

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值