AWS APIGW Signature使用示例代码

1. 引入SDK依赖包

        
            org.apache.httpcomponents
            httpclient
            4.5.12
        
        
        
            software.amazon.awssdk
            signer
            2.17.35
        

2. 调用请求Demo

import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClientBuilder;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.signer.Aws4Signer;
import software.amazon.awssdk.auth.signer.params.Aws4SignerParams;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.http.SdkHttpMethod;
import software.amazon.awssdk.regions.Region;

import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.time.Instant;

public class Aws4SignerDemo {
    private static final String HOST = "https://your-apigw-domain";
    private static final String REGION = "cn-northwest-1";
    private static final String AK = "BKBA4WFLST4Cd5O7WE3Pc";
    private static final String SK = "AmslC6UAqe0LS0J7/773vFHl6DSt9nfV96o5eBxD";

    public static void main(String[] args) throws Exception {
        String path = "/v1/person/create";
        URI uri = URI.create(HOST + path);
        String requestBody = "{\"name\": \"111\",\"age\": \"22\"}"
        SdkHttpFullRequest signedRequest = getSignature(uri, requestBody);

        String response = doPost(uri, requestBody, signedRequest);

        System.out.println(response);
    }

    private static SdkHttpFullRequest getSignature(URI uri, String requestBody){
        Aws4Signer signer = Aws4Signer.create();
        SdkHttpFullRequest.Builder requestBuilder = SdkHttpFullRequest.builder()
                .method(SdkHttpMethod.POST)
                .uri(uri);
        requestBuilder.putHeader("Host", uri.getHost());
        requestBuilder.putHeader("X-Amz-Date", Instant.now().toString());
        byte[] payload = requestBody.getBytes();
        requestBuilder.contentStreamProvider(() -> SdkBytes.fromByteArray(payload).asInputStream());

        Aws4SignerParams signingParams = Aws4SignerParams.builder()
                .awsCredentials(AwsBasicCredentials.create(AK,SK))
                .signingName("execute-api")
                .signingRegion(Region.of(REGION))
                .build();
        return signer.sign(requestBuilder.build(), signingParams);
    }

    private static String doPost(URI uri,String requestBody, SdkHttpFullRequest signedRequest) throws Exception {
        HttpClient httpClient = HttpClientBuilder.create()
                .setRetryHandler(new DefaultHttpRequestRetryHandler(3, false))
                .build();
        HttpPost request = new HttpPost(uri);
        request.setHeader(HttpHeaders.HOST, uri.getHost());
        request.setHeader("X-Amz-Date", signedRequest.firstMatchingHeader("X-Amz-Date").orElse(null));
        request.setHeader("Authorization",signedRequest.firstMatchingHeader("Authorization").orElse(null));
        request.setHeader("Content-Type", "application/json");
        request.setEntity(new StringEntity(requestBody, StandardCharsets.UTF_8));
        String result = null;
        HttpResponse response = httpClient.execute(request);
        byte[] responseBody = response.getEntity() != null ?
                SdkBytes.fromInputStream(response.getEntity().getContent()).asByteArray() : null;
        if (responseBody != null) {
            result = new String(responseBody);
        }
        return result;
    }

}

3. APIGW需要配置对应的API使用Signature鉴权

---
swagger: "2.0"
info:
  description: "test"
host: "your-apigw-domain"
basePath: "/v3"
schemes:
- "https"
paths:
  /person/create:
    post:
      produces:
      - "application/json"
      security:
      - sigv4: []
      x-amazon-apigateway-request-validator: "Validate body"
securityDefinitions:
  sigv4:
    type: "apiKey"
    name: "Authorization"
    in: "header"
    x-amazon-apigateway-authtype: "awsSigv4"
x-amazon-apigateway-policy:
  Version: "2012-10-17"
  Statement:
  - Sid: "compjv3"
    Effect: "Allow"
    Principal:
      AWS: "arn:aws-cn:iam::172238194437:user/username"
    Action: "execute-api:Invoke"
    Resource:
    - "arn:aws-cn:execute-api:cn-northwest-1:172238194437:11qx76lfea/v1/POST/person/create"
    Condition:
      IpAddress:
        aws:SourceIp:
        - "0.0.0.0/0"
x-amazon-apigateway-request-validators:
  Validate body:
    validateRequestParameters: false
    validateRequestBody: true

你可能感兴趣的:(aws,云计算)