使用Apache HttpComponents Client签署AWS HTTP请求

时间:2015-11-17 14:59:59

标签: java amazon-web-services elasticsearch apache-httpcomponents jest

我尝试向受IAM访问策略保护的AWS Elasticsearch域发出HTTP请求。我需要sign这些请求由AWS授权。 我正在使用Jest,后者又使用Apache HttpComponents Client

这似乎是一个常见的用例,我想知道是否存在某种类型的库,我可以在Apache HttpComponents客户端上使用它来签署所有请求。

2 个答案:

答案 0 :(得分:12)

我想我找到了! :)

这个项目似乎完全符合我的要求:aws-signing-request-interceptor,描述为“签署AWS请求的Apache客户端请求拦截器。最初是为了使用Jest客户端支持AWS的Elasticsearch服务而创建的。 “

编辑:我forked the project以满足我的需求(Java 7,临时STS凭证),并且它运行良好。

以下是使用示例(此处没有STS临时凭证):

String region = "us-east-1";
String service = "es";
String url = "???"; // put the AWS ElasticSearch endpoint here

DefaultAWSCredentialsProviderChain awsCredentialsProvider = new DefaultAWSCredentialsProviderChain();
final AWSSigner awsSigner = new AWSSigner(awsCredentialsProvider, region, service, () -> new LocalDateTime(DateTimeZone.UTC));

JestClientFactory factory = new JestClientFactory() {
    @Override
    protected HttpClientBuilder configureHttpClient(HttpClientBuilder builder) {
        builder.addInterceptorLast(new AWSSigningRequestInterceptor(awsSigner));
        return builder;
    }
};
factory.setHttpClientConfig(new HttpClientConfig.Builder(url)
        .multiThreaded(true)
        .build());
JestClient client = factory.getObject();

答案 1 :(得分:2)

这在异步请求的情况下不起作用。

更新

忽略我以前的评论。它也可以在为异步请求添加拦截器之后工作:

final AWSSigningRequestInterceptor requestInterceptor = new AWSSigningRequestInterceptor(awsSigner);
            factory = new JestClientFactory() {
                @Override
                protected HttpClientBuilder configureHttpClient(HttpClientBuilder builder) {
                    builder.addInterceptorLast(requestInterceptor);
                    return builder;
                }
                @Override
                protected HttpAsyncClientBuilder configureHttpClient(HttpAsyncClientBuilder builder) {
                    builder.addInterceptorLast(requestInterceptor);
                    return builder;
                }
            };