【问题标题】:Access token Refresh - Best practices访问令牌刷新 - 最佳实践
【发布时间】:2019-09-09 17:50:24
【问题描述】:

我正在为现有的第三方 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;
}

上面的代码有效。但这是一种好的做法吗?或者还有其他更好的方法吗?

谢谢。

【问题讨论】:

    标签: java rest oauth access-token spring-restcontroller


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      我建议使用expiryTime,因为您知道您的 access-token 将在一小时后过期。请尝试以下操作。

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

      【讨论】:

        猜你喜欢
        • 2020-11-09
        • 1970-01-01
        • 2012-08-02
        • 2015-05-24
        • 1970-01-01
        • 2019-03-23
        • 2011-08-13
        • 2020-05-02
        • 2021-10-27
        相关资源
        最近更新 更多