Welcome to Knowledge Base!

KB at your finger tips

This is one stop global knowledge base where you can learn about all the products, solutions and support features.

Categories
All
Cloud-AWS
Invoke an API Gateway private API using an load balancer

How can I invoke an API Gateway private API using an Application or Network Load balancer?

Last updated: 2022-11-03

I want to set up my API Gateway private API as a target behind a load balancer. Then, I want to access my private API from an Application or Network Load Balancer using my account or another AWS account. How do I set this up?

Short description

To access your private API using AWS Direct Connect or Amazon Route 53, see How to invoke a private API. You can also access an API Gateway private REST API in another AWS account using an interface VPC endpoint.

In the following set up, the private API is added as a target to the load balancer. This is done using the Amazon Virtual Private Cloud (Amazon VPC) endpoint elastic network interface IP address.

Important: Custom domain names are not supported for private APIs. As a workaround, you can invoke and attach the domain to a load balancer. Then, invoke the private API using the setup described in this article.

Resolution

Create an Amazon VPC endpoint

1.    Open the Amazon VPC console, choose Endpoints , and then choose Create endpoint .
Note: If you have any Amazon VPC endpoints already set up in your VPC using the API execute-api, then make sure that private DNS is disabled.

2.    For Services , choose com.amazonaws.com.your-region.execute-api .

3.    For VPC , choose your Amazon VPC.

4.    For Subnets , choose two subnets in different Availability Zones (AZ IDs), and then choose Create endpoint .

5.    Choose your endpoint, choose subnets , and copy the IP address . You use this IP address in another step.

For more information, see Create an interface VPC endpoint for API Gateway execute-api.

Create a private REST API and grant the Amazon VPC endpoint permission

1.    Open the API Gateway console, and then choose Create API .

2.    For REST API , choose Build .

3.    In Settings , enter the following:
For API name , enter a name for the API.
For Endpoint Type , choose Private .
For Endpoint IDs , enter and the endpoint ID that you created previously.

4.    Choose Create API .

5.    In the navigation pane, choose Resource Policy .

6.    In the resource policy editor, paste the following policy:
Note:
Replace vpce-<id> with your VPC endpoint ID.

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Deny",
      "Principal": "*",
      "Action": "execute-api:Invoke",
      "Resource": "arn:aws:execute-api:<region>:<account :<api-id>/*/*/*",
      "Condition": {
        "StringNotEquals": {
          "aws:sourceVpce": "vpce-081234d1ad408e"
        }
      }
    },
    {
      "Effect": "Allow",
      "Principal": "*",
      "Action": "execute-api:Invoke",
      "Resource": "arn:aws:execute-api:<region>:<account-id>:<api-id>/*/*/*"
    }
  ]
}

7.    Choose Save .

For more information, see Create a private API using the API Gateway console.

Create or import an AWS Certificate Manager public certificate

If you haven't already done so, do one of the following:

Request a public certificate.

-or-

Import a certificate

Create an Application Load Balancer or a Network Load Balancer

If you haven't already done so, do one of the following:

Create an Application Load Balancer

-or-

Create a Network Load Balancer

Create the target group

1.    Open the Amazon Elastic Compute Cloud (Amazon EC2) console.

2.    In the navigation pane, in Load Balancing , choose Load Balancers , choose Target Groups , and then choose Create target group .

3.    For target type , choose IP addresses .

4.    for Target group name , enter a name.

Application Load Balancer

For Protocol , choose HTTPS .
For Port , choose 443 .
For VPC , choose your VPC.
For Health check path, enter 200,403. (This makes sure that the VPC endpoint shows as Healthy in the target group)

Network Load Balancer

For Protocol , choose TLS .
For Port , choose 443 .
For VPC , choose your VPC.

5.    Choose Next .

6.    In Specify IPs , enter the IP address that you copied in the Create an interface Amazon VPC endpoint section, and choose Add IPv4 address .

7.    Choose Create target group .

Configure the load balancer

1.    Open the EC2 console.

2.    In the navigation pane, choose Load Balancers , and then choose Create Load Balancer .

Application Load Balancer

For Scheme , choose either Internet-facing or Internal depending on your configuration.
For Protocol , choose HTTPS .
For VPC and subnets , choose your VPC and subnets.

Network Load Balancer For Scheme , choose either Internet-facing or Internal depending on your configuration.
For Protocol , choose TLS .
For VPC and subnets , choose your VPC and subnets.
For Security policy , choose the default policy ELBSecurityPolicy-TLS (recommended) .
For Default SSL/TLS certificate , choose From ACM .
Choose the Select a certificate dropdown menu, and then choose your certificate.

3.    Choose Create load balancer .

Note: The load balancer targets should be the IP addresses of the elastic network interface that the VPC endpoint created. These were done in step 1. You can find those elastic network interfaces by selecting your VPC endpoint and opening the Subnets tab.

Create a record in an Amazon Route 53 public or private hosted zone

If you haven't already done so, do one of the following:

Create a public hosted zone

-or-

Create a private hosted zone

Then, create a CNAME record and associate it with your Application or Network Load Balancer.

Testing

For public load balancers, you can make a curl request from your local machine.

For private load balancers, launch a new EC2 instance in one of the subnets for your load balancer. Then, make a curl request similar to the following:

curl -v https://{custom-domain-name}/<stage-name>/<resource-path> -H 'Host: <api-id>.execute-api.<region>.amazonaws.com'

-or-

curl -v https://{custom-domain-name}/<stage-name>/<resource-path> -H 'x-apigw-api-id:{api-id}'

A successful request returns a 200 OK response code. An unsuccessful request returns a 403 Forbidden response code or a DNS resolution error. If you encounter any issues, see Troubleshoot your load balancers.


How do I connect to a private API Gateway over a Direct Connect connection?

How do I troubleshoot issues when connecting to an API Gateway private API endpoint?

Setting up CloudWatch logging for a REST API in API Gateway

Monitoring REST APIs with Amazon CloudWatch metrics

Did this article help?

Submit feedback

Do you need billing or technical support?

Contact AWS Support
Secure an API Gateway WebSocket API

How can I secure my Amazon API Gateway WebSocket API?

Last updated: 2022-11-04

I want to secure my Amazon API Gateway WebSocket API. How can I do this?

Short description

Amazon API Gateway supports the following methods for controlling and managing access to APIs:

  • AWS Identity and Access Management (IAM) authorization
  • AWS Lambda REQUEST authorizer function

Resolution

IAM authorization

For WebSocket APIs, make sure that your routes use an ARN in the following format:

arn:aws:execute-api:region:account-id:api-id/stage-name/route-key

For more information, see Using IAM authorization.

Lambda authorizer function

You can't use path variables (event.pathParameters) with Lambda authorizer functions for WebSocket APIs because the path is fixed. Make sure that the methodArn ends with "$connect" in the following format:

arn:aws:execute-api:region:account-id:api-id/stage-name/$connect

For more information, see Creating a Lambda REQUEST authorizer function.


How can I set up a custom domain name for my API Gateway API?

Did this article help?

Submit feedback

Do you need billing or technical support?

Contact AWS Support
Read article
Troubleshoot 410 GoneException errors with API Gateway WebSocket APIs

How can I troubleshoot 410 GoneException errors with Amazon API Gateway WebSocket APIs?

Last updated: 2022-11-03

I get a "410 GoneException" error when trying to post a message to my Amazon API Gateway WebSocket API similar to the following:

...
"errorMessage": "GoneException: 410" 
...

How do I troubleshoot this?

Short description

You might receive the "410 GoneException" error if:

  • A message was posted to the WebSocket API before the connection was established.
  • The connection has been terminated, or the connection doesn't exist anymore.
  • The client disconnected and then tried to reconnect using the same connectionId.

Note: For WebSocket APIs, the connectionId is required to send a callback response from the backend.

Resolution

To troubleshoot WebSocket API errors, turn on Amazon CloudWatch Logs.

Note: For Log level , choose INFO to generate execution logs for all requests.

Execution logs contain information that you can use to identify and troubleshoot most API errors. For example:

  • The requests that your API receives
  • The integration backend responses from your API
  • The response provided by AWS Lambda authorizers
  • The requestId for AWS integration endpoints

For more information about each type of logging, see CloudWatch log formats for API Gateway.

Before posting messages to WebSocket APIs, make sure that your connection is established by calling the getConnection operation using the AWS SDK ApiGatewayManagementApi.

Avoid making the postToConnection request from the Lambda function integrated with your $connect route. For example, if you want to post a message after the client connection is established, do the following:

  1. Create a child Lambda function that's asynchronously invoked by the parent function.
  2. On initiation of a new connection, the $connect route is invoked and the parent function invokes the child function passing the connectionId .
  3. The Lambda child function receives the connectionId and calls the getConnection operation to verify that the connection is valid. Then, the message is sent using the postToConnection method.

About WebSocket APIs in API Gateway

How can I pass a connectionId or custom token to VPC Link integration as a header for Amazon API Gateway WebSocket APIs?

Did this article help?

Submit feedback

Do you need billing or technical support?

Contact AWS Support
Read article
Troubleshoot Amazon API Gateway 500 errors with VPC link integration

How can I troubleshoot 500 errors with VPC link integration for Amazon API Gateway?

Last updated: 2022-11-01

I configured Amazon API Gateway with VPC Link integrations. When I call my API, I receive a configuration or internal error with an HTTP 500 status code. How do I resolve this issue?

Short description

AWS API gateway can fail to forward traffic to backend resources and return an HTTP 500 status code with VPC links if:

  • The VPC Link is in the Failed state, the endpoint service is deleted, or in the Rejected state.
  • The registered target for the target group is unhealthy or not in use.
    Note: If no traffic is sent over the VPC link for 60 days, then it becomes INACTIVE . For more information, see Working with VPC links for HTTP APIs.
  • Security groups don't allow traffic on specific ports.
  • The network access control list (ACL) is blocking the traffic.
  • The target isn't listening on the target ports.
  • The domain name certificate isn't matching with the TLS enabled Network Load Balancer (NLB) or Application Load Balancer (ALB).

If Amazon CloudWatch logging is activated for your API, then an error message indicating the cause of the error appears in the execution logs.

Example HTTP 500 error messages in CloudWatch logs

Thu Aug 04 17:48:21 UTC 2022 : Execution failed due to configuration error: There was an internal error while executing your request
Thu Aug 04 17:48:21 UTC 2022 : Method completed with status: 500

-or-

Thu Aug 04 19:50:21 UTC 2022 : Execution failed due to configuration error: Host name 'domain.com.com' 
does not match the certificate subject provided by the peer (CN=myinstance.com)
Thu Aug 04 19:50:21 UTC 2022 : Method completed with status: 500

Resolution

Confirm the cause of the error

If you haven't done so already, turn on CloudWatch logging for your REST API. Make sure that you configure execution logging.

Tip: When configuring the logging settings, for Log level , choose INFO . Then, choose Log full requests/responses data .

Identify what's causing the errors by viewing the REST APIs execution logs in CloudWatch.

Check for the error message in the execution logs and follow these resolution steps

"Execution failed due to configuration error: There was an internal error while executing your request"

  • Verify that the VPC Link load balancer exists and hasn't been deleted.
  • Verify that the VPC Link is in the AVAILABLE state. If the VPC Link is in the FAILED state, then you must create a new VPC link and associate it with your API. Note: Be sure to deploy the API after modifying the integration request.
  • Verify that the VPC Link endpoint connection is in the AVAILABLE state.
  • If the VPC ID is referenced with a stage variable, then verify that the VPC Link ID is correct.
  • Verify that the VPC Link load balancer is listening on the HTTP/HTTPS port that the request is configured for. Check that the listeners are configured for the correct port. Check the network ACLs and make sure that they aren't blocking the request.
  • Verify that the target group is accepting the request. Check network ACLs to make sure that traffic is allowed inbound and outbound. Check the security groups to make sure that traffic is allowed inbound for the configured ports.
  • If the request returns a 500 error, the connection might receive TCP RST packets. Verify that the backend server is up and running. Verify that the backend target has a service running on the target port. Verify that the backend target is listening on the target port.

"Execution failed due to configuration error: Host name 'domain.com.com' does not match the certificate subject provided by the peer (CN=myinstance.com)"

Make sure that the endpoint domain name matches the certificate that's returned by the TLS enabled load balancer target.

"Execution failed due to configuration error: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target"

This error means that the API Gateway can't find the root CA. Even if insecureSkipVerification is set to true on the integrations TlsConfig property, API Gateway performs basic certificate validation including:

  • The certificates expiration date.
  • The hostname.
  • The presence of a root certificate authority.

"Execution failed due to configuration error: Cannot verify ECDH ServerKeyExchange signature"

This error means that because a key and the corresponding certificate don't match, the TLS handshake fails. To resolve this, verify the contents of the files used for your configured certificate authorities, certificates, and keys.

"Execution failed due to an internal error"

This error occurs because Amazon API Gateway couldn't connect to the load balancer over the VPC Link due to target resets on the load balancer. To resolve this, set the timeout on the target to be higher than the default timeout (350 seconds) on the load balancer.

"Execution failed due to configuration error: Not a valid protocol version: {Text of string}"

This error means that the integration responded with an invalid HTTP response which doesn't adhere to the HTTP specification. This might indicate that the Integrated backend is sending invalid data back to Amazon API Gateway.

To troubleshoot this error, do the following:

  • Reproduce the request made from Amazon API Gateway. Test the service endpoint used by Amazon API Gateway by creating a VPC endpoint that's linked to the service endpoint ID. You can also run packet captures to review the response that's returned from the integrated backend.
  • Change the load balancers protocol to TLS or TCP depending on the targets response to avoid duplicate encryption.
  • Make sure that insecureSkipVerification is set to true on the integrations TlsConfig property.

Understanding VPC Links in Amazon API Gateway private Integrations

Working with VPC links for HTTP APIs

Monitoring REST API execution with Amazon CloudWatch metrics

Did this article help?

Submit feedback

Do you need billing or technical support?

Contact AWS Support
Read article
Troubleshoot API Gateway certificate issues for custom domains using TLS

How can I troubleshoot certificate chain and self-signed certificate issues for Amazon API Gateway with custom domains and mutual TLS enabled?

Last updated: 2022-11-01

I am using mutual Transport Layer Security (TLS) authentication with Amazon API Gateway with a custom domain name. I am getting certificate chain or self-signed certificate errors. How can I troubleshoot this?

Short description

Before you begin, make sure that you have:

  • Set up a custom domain name for Amazon API Gateway.
  • Created the certificate chain and self-signed certificate.
  • Imported the certificate chain and self-signed certificate into AWS Certificate Manager (ACM).
  • Configured your truststore and upload it to an Amazon Simple Storage Service (Amazon S3).

Resolution

For a list of specific error messages when invoking your Amazon API Gateway API, run a curl command similar to the following:

$ curl -v https://mtls.example.info/test-apigw-mtls --key self-signed.key --cert self-signed.pem:"example"

Client errors

"curl: (58) could not load PEM client certificate, OpenSSL error error:02001002:system library:fopen:No such file or directory, (no key found, wrong pass phrase, or wrong file format?"

This error means that the PEM file has the wrong name, location, or file format. For example, the certificate file format stored locally is .crt , but the .pem file was used instead in the API request. To resolve this, make sure that the local client certificate has the correct format and name.

"curl: (6) Could not resolve host: mtls.example.info"

The client wasn't able to resolve the domain name. Make sure that the domain name and configuration are correct.

"url: (58) schannel: Failed to import cert file self-signed.pem, last error is 0x80092002"

This error means that there is an issue with the local client .pem file. Make sure that the .pem file includes the correct name and format.

"curl: (58) unable to set private key file: 'self-signed.key' type PEM"

This error means that there is an issue with the local client file. Make sure that the private key provided in the HTTP request is not missing and correct.

Server errors

"Access denied. Reason: self-signed certificate."

Verify that the self-signed client certificate in the API request isn't altered or corrupted.

The following must match exactly:

  • The modulus of the private key ( private.key ) used to sign the self-signed certificate within the truststore in Amazon S3 ( bundle.crt or bundle.pem ).
  • The modulus from the client's certificate passed in the API request ( client.crt ).

To compare the two modulus, run the following OpenSSL commands:

$ openssl rsa -noout -modulus -in private.key
$ openssl x509 -noout -modulus -in bundle.crt
$ openssl x509 -noout -modulus -in client.crt

Note: To produce a shorter hash value for easier comparison, you can use PIPE to send the output modulus into a cryptographic hash function. For example: openssl sha1 .

$ openssl [operation] -noout -modulus -in [data] | openssl sha1

Valid command output examples:

2143831a73a8bb28467860df18550c696c03fbcb
2143831a73a8bb28467860df18550c696c03fbcb
2143831a73a8bb28467860df18550c696c03fbcb

To confirm data integrity, verify that there wasn't any data modification at the content level by running the following diff command:

$ diff client.crt bundle.crt

Introducing mutual TLS authentication for Amazon API Gateway

How do I troubleshoot HTTP 403 Forbidden errors from an API Gateway custom domain name that requires mutual TLS?

Did this article help?

Submit feedback

Do you need billing or technical support?

Contact AWS Support
Read article
Create a private integration using an ALB for an API Gateway HTTP API

How to create a private integration using an internal Application Load Balancer for an Amazon API Gateway HTTP API?

Last updated: 2022-10-28

I want to create a private integration using an internal Application Load Balance for an Amazon API Gateway HTTP API. How can I do this?

Resolution

Follow these instructions to create the Amazon Virtual Private Cloud (Amazon VPC) link, HTTP API, private integration, and deploy the HTTP API.

Note: If you receive errors when running AWS Command Line Interface (AWS CLI) commands, make sure that you’re using the most recent AWS CLI version.

1.    If you haven't already done so, follow the instructions to create an Application Load Balancer.

2.    Open the API Gateway console, and in the navigation pane choose VPC links .

3.    From VPC Links , choose Create .

(Optional) You can also create a VPC link by using the AWS CLI command create-vpc-link similar to the following:

aws apigatewayv2 create-vpc-link --name MyVpcLink \
    --subnet-ids subnet-aaaa subnet-bbbb \
    --security-group-ids sg1234 sg5678

4.    From Choose a VPC link version , choose VPC link for HTTP APIs .

5.    For Name , enter a name for your VPC link.

6.    Choose the VPC dropdown list, choose a VPC for your Application Load Balancer to connect to.

7. For Subnets , choose your subnets to include in the VPC link.

8.    For Security groups , choose the security groups for the VPC link, and then choose Create .

Create an HTTP API and route

1.    Open the API Gateway console, and then choose Create API .

2.    For HTTP API , choose Build .

3.    For API name , enter a name, and then choose Next .

4.    For Configure routes , choose Next .

5.    For Configure stages , choose Next , and then choose Create .

6.    In the navigation pane, choose Routes , and then choose Create .

7.    For Method , choose ANY .

8.    For path, enter /{proxy+} and choose Create .

Create a private integration and deploy the HTTP API

1.    Open the API Gateway console, and then choose your HTTP API.

2.    In the navigation pane, choose Integrations .

3.    For Integrations , choose Manage integrations , and then choose Create .

4.    For Attach this integration to a route, choose ANY /{proxy+} .

5.    For Integration target , choose Private resource .

6.    For Integration details , choose Select manually .

7.    For Target service , choose ALB/NLB .

8.    For Load balancer , choose your load balancer.

9.    For Listener , choose HTTP 80 .

10.    For VPC link , choose your VPC, and then choose Create .

11.    (Skip this step if auto deploy is active) Choose Deploy to deploy your HTTP API.

12.    For Invoke URL , copy the URL and paste it into a new browser window. For example, https://abcdef123.execute-api.us-east-1.amazonaws.com.

The HTTP API URL renders successfully in the browser window.


Amazon API Gateway HTTP API tutorials

How do I map the response status codes for API Gateway integrations in HTTP APIs?

Did this article help?

Submit feedback

Do you need billing or technical support?

Contact AWS Support
Read article