問題描述
OAuth2RestTemplate 過期後不刷新令牌 (OAuth2RestTemplate doesnt refresh the token after it expired)
我正在使用 Spring OAuth2RestTemplate,並且令牌在過期後不會刷新。下面是我的令牌提供者。我錯過了什麼?任何指針都會有幫助。
@Bean
public AccessTokenProvider clientAccessTokenProvider() {
ClientCredentialsAccessTokenProvider accessTokenProvider = new ClientCredentialsAccessTokenProvider();
accessTokenProvider.setRequestFactory(getClientHttpRequestFactory());
return accessTokenProvider;
}
參考解法
方法 1:
ClientCredentialsAccessTokenProvider doesn't not support "Refresh Token" according to spring boot oAuth implementation.
I fixed the problem by checking the expiry and setting the token in oAuthContext to null before making the rest call.
private void checkTokenExpiry() {
OAuth2ClientContext oAuth2ClientContext = oAuth2RestOperations.getOAuth2ClientContext();
if (oAuth2ClientContext == null) {
return;
}
OAuth2AccessToken accessToken = oAuth2ClientContext.getAccessToken();
if (accessToken != null && (accessToken.getExpiresIn() > 5000 || accessToken
.isExpired())) { //5 seconds
log.info("Token expired");
oAuth2RestOperations.getOAuth2ClientContext()
.setAccessToken(null); //to re‑fetch the token
}
}