
本文档旨在指导开发者如何在Spring Security中缓存OAuth2自省请求,以提高资源服务器的稳定性和性能,减少对认证服务器的依赖。通过自定义OpaqueTokenIntrospector并利用缓存机制,可以有效降低401错误,提升用户体验。本文将提供详细的代码示例和步骤说明,帮助你轻松实现自省请求的缓存。
在使用Spring Security构建OAuth2资源服务器时,经常需要通过自省端点验证令牌的有效性。当认证服务器不稳定时,频繁的自省请求可能导致资源服务器出现大量401错误。为了解决这个问题,我们可以通过缓存自省请求的结果来减少对认证服务器的依赖。
以下是如何实现这一目标的步骤:
1. 暴露OpaqueTokenIntrospector Bean
首先,需要在Spring Security配置中暴露一个OpaqueTokenIntrospector类型的Bean。这将允许我们自定义自省逻辑。
@Configuration
public class SecurityConfig {
@Value("${spring.security.oauth2.resourceserver.opaquetoken.introspection-uri}")
private String introspectionUri;
@Value("${spring.security.oauth2.resourceserver.opaquetoken.client-id}")
private String clientId;
@Value("${spring.security.oauth2.resourceserver.opaquetoken.client-secret}")
private String clientSecret;
@Bean
public OpaqueTokenIntrospector introspector() {
return new CustomOpaqueTokenIntrospector(this.introspectionUri, this.clientId, this.clientSecret);
}
// 其他配置...
}2. 创建自定义的OpaqueTokenIntrospector
接下来,创建一个自定义的OpaqueTokenIntrospector类,该类将负责缓存自省请求的结果。
import org.springframework.security.oauth2.core.OAuth2AuthenticatedPrincipal;
import org.springframework.security.oauth2.server.resource.introspection.NimbusOpaqueTokenIntrospector;
import org.springframework.security.oauth2.server.resource.introspection.OpaqueTokenIntrospector;
import javax.cache.Cache;
import javax.cache.CacheManager;
import javax.cache.Caching;
import javax.cache.configuration.MutableConfiguration;
import javax.cache.expiry.Duration;
import javax.cache.expiry.TouchedExpiryPolicy;
import javax.cache.spi.CachingProvider;
import java.time.Instant;
public class CustomOpaqueTokenIntrospector implements OpaqueTokenIntrospector {
private final OpaqueTokenIntrospector introspector;
private final Cache<String, OAuth2AuthenticatedPrincipal> accessTokenCache;
public CustomOpaqueTokenIntrospector(String uri, String clientId, String clientSecret) {
this.introspector = new NimbusOpaqueTokenIntrospector(uri, clientId, clientSecret);
CachingProvider cachingProvider = Caching.getCachingProvider();
CacheManager cacheManager = cachingProvider.getCacheManager();
MutableConfiguration<String, OAuth2AuthenticatedPrincipal> configuration =
new MutableConfiguration<String, OAuth2AuthenticatedPrincipal>()
.setTypes(String.class, OAuth2AuthenticatedPrincipal.class)
.setExpiryPolicyFactory(TouchedExpiryPolicy.factoryOf(Duration.ofSeconds(1800))) // 设置缓存过期时间为30分钟
.setStoreByValue(false);
accessTokenCache = cacheManager.createCache("accessTokenCache", configuration);
}
@Override
public OAuth2AuthenticatedPrincipal introspect(String token) {
OAuth2AuthenticatedPrincipal principal = accessTokenCache.get(token);
if (principal != null) {
// 检查token是否过期
if (principal.getAttribute("exp") != null
&& ((Instant) principal.getAttribute("exp")).isAfter(Instant.now())) {
return principal; // 从缓存返回
} else {
accessTokenCache.remove(token); // 如果token已过期,则从缓存中移除
}
}
// 从自省端点获取token信息
principal = introspector.introspect(token);
accessTokenCache.put(token, principal); // 将结果放入缓存
return principal;
}
}代码解释:
3. 配置Spring Security
确保你的Spring Security配置使用自定义的OpaqueTokenIntrospector Bean。
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Autowired
private OpaqueTokenIntrospector introspector;
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(authorize -> authorize
.requestMatchers("/public/**").permitAll()
.anyRequest().authenticated()
)
.oauth2ResourceServer(oauth2 -> oauth2
.opaqueToken(opaqueToken -> opaqueToken
.introspector(introspector)
)
);
return http.build();
}
}注意事项:
总结
通过自定义OpaqueTokenIntrospector并利用缓存机制,可以有效地缓存OAuth2自省请求,从而提高资源服务器的稳定性和性能。 请根据你的应用需求调整缓存配置,并确保在生产环境中进行适当的异常处理。 这个方法可以显著减少对认证服务器的依赖,并提升用户体验。
以上就是如何在Spring Security中缓存自省请求的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号