Questions tagged with Amazon API Gateway

Content language: English

Sort by most recent

Browse through the questions and answers listed below or filter and sort to narrow down your results.

const crypto = require('crypto'); class AwsV4 { constructor(accessKeyID, secretAccessKey) { this.accessKeyID = accessKeyID; this.secretAccessKey = secretAccessKey; this.currentDateObject = new Date(); this.xAmzDate = this.getTimeStamp(this.currentDateObject); this.currentDate = this.getDate(this.currentDateObject); } setPath(path) { this.path = path; } setServiceName(serviceName) { this.serviceName = serviceName; } setRegionName(regionName) { this.regionName = regionName; } setPayload(payload) { this.payload = payload; } setRequestMethod(method) { this.httpMethodName = method; } addHeader(headerName, headerValue) { this.awsHeaders = this.awsHeaders || {}; this.awsHeaders[headerName] = headerValue; } prepareCanonicalRequest() { let canonicalURL = ''; canonicalURL += this.httpMethodName + '\n'; canonicalURL += this.path + '\n'; // Add the missing line to include the CanonicalQueryString canonicalURL += '' + '\n'; // Use an empty string as there are no query string parameters in this case let signedHeaders = ''; // Add x-amz-date header this.addHeader('x-amz-date', this.xAmzDate); // Sort headers lexicographically by header name (lowercase) const sortedHeaderKeys = Object.keys(this.awsHeaders).sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase())); for (const key of sortedHeaderKeys) { if (key !== 'Accept' && key !== 'Accept-Language' && key !== 'Content-Type') { signedHeaders += key.toLowerCase() + ';'; canonicalURL += key.toLowerCase() + ':' + this.awsHeaders[key] + '\n'; } } canonicalURL += '\n'; this.strSignedHeader = signedHeaders.slice(0, -1); canonicalURL += this.strSignedHeader + '\n'; canonicalURL += this.generateHex(this.payload); return canonicalURL; } prepareStringToSign(canonicalURL) { let stringToSign = ''; stringToSign += 'AWS4-HMAC-SHA256' + '\n'; stringToSign += this.xAmzDate + '\n'; stringToSign += this.currentDate + '/' + this.regionName + '/' + this.serviceName + '/' + 'aws4_request' + '\n'; stringToSign += this.generateHex(canonicalURL); return stringToSign; } calculateSignature(stringToSign) { const signatureKey = this.getSignatureKey(this.secretAccessKey, this.currentDate, this.regionName, this.serviceName); const signature = crypto.createHmac('sha256', signatureKey).update(stringToSign).digest('hex'); return signature; } getHeaders() { const canonicalURL = this.prepareCanonicalRequest(); const stringToSign = this.prepareStringToSign(canonicalURL); const signature = this.calculateSignature(stringToSign); const authorizationHeader = this.buildAuthorizationString(signature); this.awsHeaders['Authorization'] = authorizationHeader; this.awsHeaders['x-amz-date'] = this.xAmzDate; return this.awsHeaders; } getUpdatedHeaders() { this.setPath('/paapi5/getitems'); this.setServiceName('ProductAdvertisingAPI'); this.setRegionName('us-east-1'); this.setRequestMethod('POST'); this.setPayload(payloadJsonString); // Use the actual payload JSON string this.addHeader('Host', 'webservices.amazon.com'); this.addHeader('Content-Encoding', 'amz-1.0'); this.addHeader('Content-Type', 'application/json; charset=UTF-8'); this.addHeader('x-amz-date', this.xAmzDate); // Move this line up this.addHeader('X-Amz-Target', 'com.amazon.paapi5.v1.ProductAdvertisingAPIv1.GetItems'); const headers = this.getHeaders(); return { 'Authorization': headers['Authorization'], 'X-Amz-Date': headers['x-amz-date'] }; } buildAuthorizationString(signature) { return 'AWS4-HMAC-SHA256' + ' ' + 'Credential=' + this.accessKeyID + '/' + this.getDate(this.currentDateObject) + '/' + this.regionName + '/' + this.serviceName + '/' + 'aws4_request' + ' ' + 'SignedHeaders=' + this.strSignedHeader + ' ' + 'Signature=' + signature; } generateHex(data) { return crypto.createHash('sha256').update(data).digest('hex'); } getSignatureKey(key, date, regionName, serviceName) { const kSecret = 'AWS4' + key; const kDate = crypto.createHmac('sha256', kSecret).update(date).digest(); const kRegion = crypto.createHmac('sha256', kDate).update(regionName).digest(); const kService = crypto.createHmac('sha256', kRegion).update(serviceName).digest(); const kSigning = crypto.createHmac('sha256', kService).update('aws4_request').digest(); return kSigning; } getTimeStamp(date) { return date.toISOString().replace(/[:-]|\.\d{3}/g, ''); } getDate(date) { const year = date.getUTCFullYear(); const month = ('0' + (date.getUTCMonth() + 1)).slice(-2); const day = ('0' + date.getUTCDate()).slice(-2); return `${year}${month}${day}`; } } const awsV4 = new AwsV4('AKIAI6QL7ST37VECNI7A', 'ZnZS++sxYuDGxP8VOSEG2uZd8Qmtup9F51wHgOkw'); const payload = { "ItemIds": [ "B01M6V8CP4" ], "Resources": [ "CustomerReviews.Count", "CustomerReviews.StarRating", "Images.Variants.Large", "ItemInfo.Features", "Offers.Listings.Promotions", "Offers.Summaries.LowestPrice" ], "PartnerTag": "timstools03-20", "PartnerType": "Associates", "Marketplace": "www.amazon.com" }; const payloadJsonString = JSON.stringify(payload); // Pass the JSON string to setPayload() awsV4.setPayload(payloadJsonString); const updatedHeaders = awsV4.getUpdatedHeaders(); console.log(updatedHeaders);
0
answers
0
votes
6
views
asked 14 hours ago
I find different pieces of the puzzle I need to solve, but none of the examples I've found online show how to do multiple stages in a sam template (ie: Deploy dev, prod, and test) at the same time. And none show how to proxy to a URI that I've found. All of them show the gateway going to lambda as a proxy. But how do you do a standard http_proxy in the template? Sorry, new to SAM so trying to figure things out. I need 1 API gateway with multiple stages that http_proxies to a URI. Each stage goes to the same place, but different API keys used for each one as a stage variable. And I need it to be private with two VPCE's so I have to attach a resource policy to it as well. All in SAM :)
0
answers
0
votes
12
views
asked 16 hours ago
Hello, I have an API Gateway exposing a Java REST API. Each endpoint is integrated with a lambda function. There are several separate lambda functions, each one having its own handler. They are extending the same base class. The base class defines a static Hashmap inherited by each lambda function. One lambda function stores data in this Hashmap and another one is supposed to get the data. Each Lambda function is triggered by a separate HTTP request. This works as expected when deployed in a CDI container as a singleton. But, when deployed to AWS, with the API Gateway, the lambda function supposed to get the data stored by the other one finds the hashmap empty. Meaning that, despite of being static, the hashmap is instantiated with any HTTP request. This is equivalent to the CDI @RequestScoped annotation. Is there any way to configure the API Gateway endpoints such that to have the same effect like when using CDI @Singleton or @ApplicationScoped annotation ? Many thanks in advance. Nicolas
0
answers
0
votes
6
views
profile picture
Nicolas
asked 18 hours ago
I am using webhook endpoint to push messages to SQS service pipeline looks: ``` gateway -> integration request -> SQS -> integration response ``` everything works fine but now third party integration requires time-to-time validation request, and i need to return calculated hmac sha256 hash in response Not sure if response template support all utils, but I am trying next Integration response template: ``` #set($token = $context.responseOverride.header.RequestBody) #if(!$token || $token == '') {"status": "ok"} #else #set($secretKey = "my-secret-key") #set($hmac = $util.cryptoHmac("HmacSHA256", "$token", $secretKey)) { "token": "$message", "hmac": "$util.base64Encode($hmac)" } #end ``` but looks like `$util.cryptoHmac("HmacSHA256", "$token", $secretKey)` not working, method returns null maybe somebody could help me to resolve this case
0
answers
0
votes
21
views
asked 2 days ago
I'm importing an OpenAPI 3.0 spec into API Gateway and I need to set a couple methods to not require an api-key. The two methods which I want to not require are; 1. The GET method that is the endpoint I'm pointing to for Route53 health checks. 2. A POST which I do not have control over so I cannot have them include the x-api-key header. I was hoping to find an extension in https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-swagger-extensions.html which allowed me to do something like "apikey required=false" on these two methods but I cannot, or I'm just misunderstanding the doc. I can do this from the AWS CLS via the following, but that greatly complicates our deployment process. `aws apigateway update-method --rest-api-id abc --resource-id xyz --http-method GET --patch-operations op="replace",path=/apiKeyRequired,value="false"` Does anyone know if there an extension that can change that setting?
1
answers
0
votes
10
views
DB
asked 2 days ago
Hi, When building private api gateways fronted by a vpc endpoint, the consumer needs to provide a host header with the id of the api. A workaround to fix that is to provide an ALB with Route53 record, which then fronts the vpc endpoint. In this way the consumer does not need to provide an host header. Are there any other workaround so that a consumer does not need to provide host header in order to cal a vpc endpoint fronted private api gateway? Thanks
1
answers
0
votes
17
views
profile picture
EXPERT
alatech
asked 3 days ago
Let us say, I have 2 API gateways in 1 single project, is there any option to deploy multiple API gateways at once ? Or we have to manually deploy each API Gateway ? What is the best CICD option for this use case ?
1
answers
0
votes
20
views
Ashwin
asked 3 days ago
**Error ----------------------------------------------------------------------------------------------: ** <?xml version="1.0" encoding="UTF-8"?> <Error> <Code>SignatureDoesNotMatch</Code> <Message>The request signature we calculated does not match the signature you provided. Check your key and signing method.</Message> <StringToSign>PUT **Code in Python----------------------------------------------------------------------------------------------: ** import botocore import boto3 import datetime from botocore.exceptions import ClientError import json s3_file="test6.jpg" def lambda_handler(event, context): # TODO implement print("Step 1") try: s3 = boto3.client('s3') url = s3.generate_presigned_url( ClientMethod='get_object', Params={ 'Bucket': 's3_Bucket', 'Key': s3_file }, ExpiresIn=36000000 ) result = {'status': 'success', 'data': {'url': url, 'key':s3_file}} response = { 'statusCode': 200, 'body': json.dumps(result), 'headers': { 'Content-Type': 'application/json' } } except ClientError as e: print(f'Error generating presigned URL: {e}') return None return response
1
answers
0
votes
21
views
asked 3 days ago
Our team has a service that will be deployed in all regions, commercial, china and ADC. Our solution depends on API gratway MTLS which we came to find out is not available for some regions like MEL, the [public documentation](https://aws.amazon.com/blogs/compute/introducing-mutual-tls-authentication-for-amazon-api-gateway/) says its available. How can I confirm availability for all regions? And what would be a good alternative that is available in all regions?
0
answers
0
votes
14
views
AWS
asked 3 days ago
Hello, I was trying to build FTPS server using Transfer family, But I couldn't able to successfully build one. Could some one explain in details how to build one in detail. I tried browsing online for guidance all I could find is for building SFTP server. I need help in building "custom identity provider" using rest API and lambda function. I couldn't find the code for the lambda function.
1
answers
0
votes
20
views
asked 4 days ago
Let us say, I want to do versioning of APIs both for internal usage (client app) lambdas as well as for exposing some set of APIs (lambdas) for a third-party system. Before even starting to version, I want to enquire whether there is possibility of having multiple API Gateways for the same ? One for managing and deploying the internal APIs and another for deploying the APIs to expose to third-party system without cloud-front. Or can single API gateway can manage both flows ? What is the best method to manage this ? Any suggestion / approach would be appreciated.
2
answers
0
votes
63
views
Ashwin
asked 5 days ago
When I run CloudFormation deploy using a template with API Gateway resources, the first time I run it, it creates and deploys to stages. The subsequent times I run it, it updates the resources but doesn't deploy to stages. How can i solve this issue.
1
answers
0
votes
19
views
asked 5 days ago