oAuth客户端未缓存令牌



我正试图使用以下代码在春季启动中创建一个oAuth客户端。我尝试记录getoken方法。根据文档和代码,它还必须缓存令牌,我检查了其中的源代码,检查令牌是否为空,或者它试图调用的令牌是否过期。但对我来说,每个呼叫都会用一个新的令牌进行响应。你能告诉我为什么不缓存它吗?它与上下文有关吗?

@Bean
@ConfigurationProperties("app.oauth2.client")
protected ClientCredentialsResourceDetails oAuthDetails() {
return new ClientCredentialsResourceDetails();
}
@Bean
protected OAuth2RestTemplate restTemplate() {
return new OAuth2RestTemplate(oAuthDetails());
}

来自Spring源代码

/**
* Acquire or renew an access token for the current context if necessary. This method will be called automatically
* when a request is executed (and the result is cached), but can also be called as a standalone method to
* pre-populate the token.
* 
* @return an access token
*/
public OAuth2AccessToken getAccessToken() throws UserRedirectRequiredException {
OAuth2AccessToken accessToken = context.getAccessToken();
if (accessToken == null || accessToken.isExpired()) {
try {
accessToken = acquireAccessToken(context);
}
catch (UserRedirectRequiredException e) {
context.setAccessToken(null); // No point hanging onto it now
accessToken = null;
String stateKey = e.getStateKey();
if (stateKey != null) {
Object stateToPreserve = e.getStateToPreserve();
if (stateToPreserve == null) {
stateToPreserve = "NONE";
}
context.setPreservedState(stateKey, stateToPreserve);
}
throw e;
}
}
return accessToken;
}

缓存机制是针对Oauth2 RFC的,因为该标准提供了安全边界来保护任何中间人攻击、CSRF、XSS。。。。

因此oauth2规范包含以下身份验证概念:

  1. 客户端凭据

  2. 授权码

  3. 访问令牌和刷新令牌

您的用例是访问令牌、刷新令牌用例(Oauth2是围绕这个概念构建的(,因此对于每个访问令牌,您都有一个到期日期,以及服务器为获得新的acces_token而发布的刷新令牌(到期日期更长(。

因此,缓存部分不尊重oauth2标准,因为这可能会导致安全问题,例如中间人攻击。

根据您的问题,客户应该能够自己:

  1. 将访问令牌发送到后端

  2. 如果访问令牌过期或无效,则请求新的刷新令牌

最新更新