如何自定义授权码有效期?
解读
在国内基于 Spring Security OAuth2(或 Spring Authorization Server)做 第三方登录、开放平台、SSO 时,授权码(authorization_code)默认 5 分钟过期。
面试官问“如何自定义”,既考察你是否知道过期配置项,也考察你能否在不改源码的前提下优雅扩展、动态刷新、多租户差异化以及灰度发布等真实落地细节。
一句话:不仅要改得动,还要改得稳、改得活。
知识点
- 授权码生命周期管理接口:
OAuth2AuthorizationCode的getExpiresAt()由OAuth2AuthorizationCodeGenerator生成。 - 配置入口:
- 旧版 Spring Security OAuth2:
AuthorizationServerEndpointsConfigurer.authorizationCodeServices(...) - 新版 Spring Authorization Server:
OAuth2AuthorizationService+OAuth2TokenCustomizer<OAuth2AuthorizationCode>
- 旧版 Spring Security OAuth2:
- 关键 Bean:
OAuth2AuthorizationCodeGenerator(或自定义OAuth2AuthorizationCodeGenerator)OAuth2AuthorizationService的save(authorization)时把过期时间写死或动态计算
- 动态化手段:
- 实现
OAuth2AuthorizationCodeGenerator接口,重写generate(...),从 Redis / DB / Nacos 读取自定义 TTL - 利用
OAuth2TokenCustomizer<OAuth2AuthorizationCode>在令牌签发阶段 覆盖 expiresAt
- 实现
- 多租户场景:根据
client_id或tenant_id走不同策略,避免全局硬编码 - 安全红线:授权码有效期国内监管要求 ≤10 min,不得大于 600 s;生产必须 审计日志 + 监控告警
答案
步骤一:自定义 OAuth2AuthorizationCodeGenerator
@Component
public class TenantAwareAuthCodeGenerator implements OAuth2AuthorizationCodeGenerator {
@Autowired
private TenantConfigService tenantConfigService; // 读 Nacos/DB
@Override
public OAuth2AuthorizationCode generate(RegisteredClient registeredClient,
Authentication principal) {
Integer ttlSeconds = tenantConfigService.getAuthCodeTtl(registeredClient.getClientId());
Instant issuedAt = Instant.now();
Instant expiresAt = issuedAt.plusSeconds(ttlSeconds);
return new OAuth2AuthorizationCode(generateCode(), issuedAt, expiresAt);
}
}
步骤二:注入到 Spring Authorization Server 配置
@Bean
public OAuth2AuthorizationCodeGenerator authorizationCodeGenerator() {
return new TenantAwareAuthCodeGenerator();
}
@Bean
public OAuth2AuthorizationService authorizationService(JdbcTemplate jdbcTemplate,
RegisteredClientRepository clientRepository) {
JdbcOAuth2AuthorizationService service =
new JdbcOAuth2AuthorizationService(jdbcTemplate, clientRepository);
// 可选:添加 TokenCustomizer 做二次兜底
return service;
}
步骤三:配置中心兜底
在 Nacos 建立 oauth2.auth-code.ttl.{client_id}=300,支持热更新,灰度发布时只改配置即可,无需重启 Pod。
步骤四:监控与审计
通过 Micrometer 埋点 oauth2.auth.code.ttl 标签,接入 Prometheus + Grafana,超 600 s 直接告警到飞书群。
拓展思考
- 授权码有效期与登录态协同:若业务侧做了 滑块验证 或 短信二次验证,可把 TTL 缩短到 120 s,防止验证码被重放。
- 分布式场景幂等:高并发下同一
client_id多次申请授权码,利用 Redis SETNX 做 code 唯一性锁,TTL 与授权码过期时间保持一致,避免脏数据。 - 审计合规:国内等保 2.0 要求 “操作可回溯”,需在
OAuth2AuthorizationService.save()处 同步写审计表(含 client_id、principal、expires_at、ip、ua),保存 6 个月以上。 - 未来升级:Spring Authorization Server 1.3 计划提供
OAuth2AuthorizationCodeRequestValidator官方扩展点,可彻底替代自定义 Generator,保持代码整洁。