1

谁能告诉为什么这不起作用?当我从单元测试中运行代码时,代码运行良好。安全设置完美,我们的服务就像我期望的那样运行良好。

但是,当我将它部署到我们的应用程序服务器(weblogic)时,我的服务每次都失败,因为我的令牌没有得到设置。每次send(final ServiceAPInvoice invoice)调用我的方法时,我都通过设置令牌来使其工作。

我的问题是为什么在我们的 Weblogic 环境中部署令牌时,我的构造函数没有设置令牌?是什么导致了这个问题?OAuthSecurityContextHolder 是一个静态类。这会影响我的问题吗?如果每次调用我的发送方法时设置令牌,我还会遇到问题吗?我还没有注意到任何问题,但还没有进行任何负载测试

我正在使用 Spring 的 OAuthRestTemplate (1.0),并且我有未过期的令牌需要设置。

这就是魔法发生的地方。我不得不稍微重命名代码以使其通用,所以希望我没有任何拼写错误:

public class ServiceRestTemplate {

private final OAuthRestTemplate serviceOAuthRestTemplate;

private final String apUri;

private final String arUri;

private final String tokenValue;

private final String tokenSecret;

public ServiceRestTemplate(final OAuthRestTemplate serviceOAuthRestTemplate,
                          final String apUri,
                          final String arUri,
                          final String tokenValue,
                          final String tokenSecret) {
    this.serviceOAuthRestTemplate = serviceOAuthRestTemplate;
    this.apUri = apUri;
    this.arUri = arUri;
    this.tokenSecret = tokenSecret;
    this.tokenValue = tokenValue;
    setContext(tokenValue, tokenSecret); // I expected this to be enough to setup my tokens 1 time
}

private void setContext(final String tokenValue, final String tokenSecret) {
    final OAuthConsumerToken accessToken = new OAuthConsumerToken();
    accessToken.setAccessToken(true);
    accessToken.setResourceId(serviceOAuthRestTemplate.getResource().getId());
    accessToken.setValue(tokenValue);
    accessToken.setSecret(tokenSecret);

    final OAuthSecurityContextImpl securityContext = new OAuthSecurityContextImpl();
    if (securityContext.getAccessTokens() == null) {
        securityContext.setAccessTokens(new HashMap<String, OAuthConsumerToken>());
    }
    if (!securityContext.getAccessTokens().containsKey(accessToken.getResourceId())) {
        securityContext.getAccessTokens().put(accessToken.getResourceId(), accessToken);
    }

    OAuthSecurityContextHolder.setContext(securityContext);
}

@Override
public ServiceWebResponse send(final ServiceAPInvoice invoice) {
    setContext(this.tokenValue, this.tokenSecret); // This line of code is the workaround to fixed my issue. 
    final ServiceWebResponse serviceResponse = serviceOAuthRestTemplate.postForObject(apUri,
                                                                                   invoice,
                                                                               ServiceWebResponse.class);
    return serviceResponse;
}
}
4

0 回答 0