Java 访问令牌刷新-最佳实践
我正在为现有的第三方RESTAPI编写一个包装器第三方的访问令牌一小时后到期。因此,我不想每次都获取新令牌,并决定使用旧令牌,如果它因未经授权的异常而失败,我希望获取新的访问令牌,然后再次调用。。我写了下面的代码Java 访问令牌刷新-最佳实践,java,rest,oauth,access-token,spring-restcontroller,Java,Rest,Oauth,Access Token,Spring Restcontroller,我正在为现有的第三方RESTAPI编写一个包装器第三方的访问令牌一小时后到期。因此,我不想每次都获取新令牌,并决定使用旧令牌,如果它因未经授权的异常而失败,我希望获取新的访问令牌,然后再次调用。。我写了下面的代码 public Store getVendor(String url,boolean tokenreseted) throws Exception { Store store =null; try { store = (Store) RestClient
public Store getVendor(String url,boolean tokenreseted) throws Exception {
Store store =null;
try {
store = (Store) RestClient.get(url, headers, queryparam, Store.class);
}
catch (UnauthorizedException e) {
if(!tokenreseted) { //Try with new Access token.
accessToken=getAccessToken();
return getVendor(url,true);
}
else
throw new Exception("UnauthorizedException exception", e);
}
catch (Exception e) {
throw new Exception("Error occured while getting storeIds",e);
}
return store;
}
以上代码有效。。但这是一种良好的做法吗?或者还有其他更好的方法吗
谢谢。我建议您使用
expiryTime
,因为您知道您的访问令牌将在一小时后过期。尝试以下方法
到期时间
对象
,然后调用API使用org.springframework.security.oauth2.client.OAuth2RestTemplate 以下是可以使用的代码:
@Bean
public OAuth2RestTemplate rteClient(OAuth2ClientContext oauth2ClientContext) throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException {
OAuth2RestTemplate rteClient = new OAuth2RestTemplate(rte(), oauth2ClientContext);
rteClient.setAccessTokenProvider(buildAccessTokenProvider());
return rteClient;
}
private OAuth2ProtectedResourceDetails rte() {
ClientCredentialsResourceDetails rte = new ClientCredentialsResourceDetails();
rte.setGrantType("client_credentials");
rte.setAuthenticationScheme(AuthenticationScheme.header);
rte.setClientId("clientId");
rte.setClientSecret("clientSecret");
rte.setAccessTokenUri("http://..");
return rte;
}
private ClientCredentialsAccessTokenProvider buildAccessTokenProvider() throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException {
ClientCredentialsAccessTokenProvider accessTokenProvider = new ClientCredentialsAccessTokenProvider();
return accessTokenProvider;
}
自动连接上述bean以使用令牌调用api。在打电话之前,它会先考虑到期时间