Home > Software engineering >  Making a request to AWS APIGateway API (with IAM permissions)
Making a request to AWS APIGateway API (with IAM permissions)

Time:12-14

I'm a bit inexperienced with Java so that may be my main issue but I'm trying to make an API request to an API that was generated by AWS's API Gateway. The API can only be executed by specific IAM roles. The issue I'm having is that I can't figure out how to pass the AWS access and secret access key in my request. Below is my code, I was trying to do this with the core Java 11 HTTPClient library.

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpResponse;
import java.net.http.HttpRequest;

class Main {

  public static void main(String[] args) throws Exception {
    HttpClient client = HttpClient.newHttpClient();

    // create a request
    HttpRequest request = HttpRequest.newBuilder()
      .uri(URI.create("https://abc123.execute-api.us-east-1.amazonaws.com/prod/controlplane/model/a1"))
      .header("accept", "application/json")
      .build();

    HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

    // the response:
    System.out.println(response);
    System.out.println(response.body());

  }
}

Running this gets me the following error since I didn't pass the AWS access keys.

Response:
(GET https://abc123.execute-api.us-east-1.amazonaws.com/prod/controlplane/model/a1) 403

{"message":"Missing Authentication Token"}

Anyone know how I can pass my AWS access keys to the request? (Preferably as an env var but I'll settle for hardcoded). It would be pretty easy for me to do in Python but I haven't found a way to do this here yet.

CodePudding user response:

You can pass the AWS access and secret access key in your request in Java Http client library by using the AWS Signature Version 4 signing process. This process requires you to create a signature using your AWS access key, secret access key, and the request parameters. You can then add the signature to the request header.

An example code as to how we can get the signature is here

  • Related