当前位置:   article > 正文

AWS APIGW Signature使用示例代码_aws-sdk-auth-signer

aws-sdk-auth-signer

1. 引入SDK依赖包

  1. <dependency>
  2. <groupId>org.apache.httpcomponents</groupId>
  3. <artifactId>httpclient</artifactId>
  4. <version>4.5.12</version>
  5. </dependency>
  6. <!-- AWS SDK for Java Signing -->
  7. <dependency>
  8. <groupId>software.amazon.awssdk</groupId>
  9. <artifactId>signer</artifactId>
  10. <version>2.17.35</version>
  11. </dependency>

2. 调用请求Demo

  1. import org.apache.http.HttpHeaders;
  2. import org.apache.http.HttpResponse;
  3. import org.apache.http.client.HttpClient;
  4. import org.apache.http.client.methods.HttpPost;
  5. import org.apache.http.entity.StringEntity;
  6. import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
  7. import org.apache.http.impl.client.HttpClientBuilder;
  8. import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
  9. import software.amazon.awssdk.auth.signer.Aws4Signer;
  10. import software.amazon.awssdk.auth.signer.params.Aws4SignerParams;
  11. import software.amazon.awssdk.core.SdkBytes;
  12. import software.amazon.awssdk.http.SdkHttpFullRequest;
  13. import software.amazon.awssdk.http.SdkHttpMethod;
  14. import software.amazon.awssdk.regions.Region;
  15. import java.net.URI;
  16. import java.nio.charset.StandardCharsets;
  17. import java.time.Instant;
  18. public class Aws4SignerDemo {
  19. private static final String HOST = "https://your-apigw-domain";
  20. private static final String REGION = "cn-northwest-1";
  21. private static final String AK = "BKBA4WFLST4Cd5O7WE3Pc";
  22. private static final String SK = "AmslC6UAqe0LS0J7/773vFHl6DSt9nfV96o5eBxD";
  23. public static void main(String[] args) throws Exception {
  24. String path = "/v1/person/create";
  25. URI uri = URI.create(HOST + path);
  26. String requestBody = "{\"name\": \"111\",\"age\": \"22\"}"
  27. SdkHttpFullRequest signedRequest = getSignature(uri, requestBody);
  28. String response = doPost(uri, requestBody, signedRequest);
  29. System.out.println(response);
  30. }
  31. private static SdkHttpFullRequest getSignature(URI uri, String requestBody){
  32. Aws4Signer signer = Aws4Signer.create();
  33. SdkHttpFullRequest.Builder requestBuilder = SdkHttpFullRequest.builder()
  34. .method(SdkHttpMethod.POST)
  35. .uri(uri);
  36. requestBuilder.putHeader("Host", uri.getHost());
  37. requestBuilder.putHeader("X-Amz-Date", Instant.now().toString());
  38. byte[] payload = requestBody.getBytes();
  39. requestBuilder.contentStreamProvider(() -> SdkBytes.fromByteArray(payload).asInputStream());
  40. Aws4SignerParams signingParams = Aws4SignerParams.builder()
  41. .awsCredentials(AwsBasicCredentials.create(AK,SK))
  42. .signingName("execute-api")
  43. .signingRegion(Region.of(REGION))
  44. .build();
  45. return signer.sign(requestBuilder.build(), signingParams);
  46. }
  47. private static String doPost(URI uri,String requestBody, SdkHttpFullRequest signedRequest) throws Exception {
  48. HttpClient httpClient = HttpClientBuilder.create()
  49. .setRetryHandler(new DefaultHttpRequestRetryHandler(3, false))
  50. .build();
  51. HttpPost request = new HttpPost(uri);
  52. request.setHeader(HttpHeaders.HOST, uri.getHost());
  53. request.setHeader("X-Amz-Date", signedRequest.firstMatchingHeader("X-Amz-Date").orElse(null));
  54. request.setHeader("Authorization",signedRequest.firstMatchingHeader("Authorization").orElse(null));
  55. request.setHeader("Content-Type", "application/json");
  56. request.setEntity(new StringEntity(requestBody, StandardCharsets.UTF_8));
  57. String result = null;
  58. HttpResponse response = httpClient.execute(request);
  59. byte[] responseBody = response.getEntity() != null ?
  60. SdkBytes.fromInputStream(response.getEntity().getContent()).asByteArray() : null;
  61. if (responseBody != null) {
  62. result = new String(responseBody);
  63. }
  64. return result;
  65. }
  66. }

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

  1. ---
  2. swagger: "2.0"
  3. info:
  4. description: "test"
  5. host: "your-apigw-domain"
  6. basePath: "/v3"
  7. schemes:
  8. - "https"
  9. paths:
  10. /person/create:
  11. post:
  12. produces:
  13. - "application/json"
  14. security:
  15. - sigv4: []
  16. x-amazon-apigateway-request-validator: "Validate body"
  17. securityDefinitions:
  18. sigv4:
  19. type: "apiKey"
  20. name: "Authorization"
  21. in: "header"
  22. x-amazon-apigateway-authtype: "awsSigv4"
  23. x-amazon-apigateway-policy:
  24. Version: "2012-10-17"
  25. Statement:
  26. - Sid: "abcv1"
  27. Effect: "Allow"
  28. Principal:
  29. AWS: "arn:aws-cn:iam::172238194437:user/username"
  30. Action: "execute-api:Invoke"
  31. Resource:
  32. - "arn:aws-cn:execute-api:cn-northwest-1:172238194437:11qx76lfea/v1/POST/person/create"
  33. Condition:
  34. IpAddress:
  35. aws:SourceIp:
  36. - "0.0.0.0/0"
  37. x-amazon-apigateway-request-validators:
  38. Validate body:
  39. validateRequestParameters: false
  40. validateRequestBody: true

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/AllinToyou/article/detail/707026
推荐阅读
相关标签
  

闽ICP备14008679号