繁体   English   中英

访问令牌刷新 - 最佳实践

[英]Access token Refresh - Best practices

我正在为现有的第三方 REST api 编写一个包装器。 第三方的access-token在一个小时后过期。 所以我不想每次都获取新令牌并决定使用旧令牌,如果它因未授权异常而失败,我想获取新的访问令牌然后再次拨打电话..我为它编写了下面的代码。

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因为您知道您的访问令牌将在一小时内到期。 请尝试以下操作。

  1. 获取访问令牌。 使用令牌和expiryTime存储在一个Object
  2. 仅在 currentTime + 30 秒 < = expiryTime时生成请求。 30 秒是创建新访问令牌的小门槛。
  3. 如果没有,请创建一个新令牌并使用新令牌和expiryTime更新Object并调用 API。

使用 org.springframework.security.oauth2.client.OAuth2RestTemplate。 .. https://docs.spring.io/spring-security/oauth/apidocs/org/springframework/security/oauth2/client/OAuth2RestTemplate.html

下面是可以使用的代码:

@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。 它会在拨打电话之前处理到期..

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM