Skip to content

Instantly share code, notes, and snippets.

View mgjam's full-sized avatar

Milan Gatyás mgjam

View GitHub Profile
public class LambdaProxyInput
{
//...other properties
public Dictionary<string, string[]> multiValueQueryStringParameters { get; set; }
}
public object MyHandler(LambdaProxyInput input, ILambdaContext context)
{
var myArrayValues = input.multiValueQueryStringParameters["MyQuerystringArray"];
import { Cors, Resource } from "@aws-cdk/aws-apigateway";
// existing const resource: Resource
resource.addResource('MyCorsResource', {
defaultCorsPreflightOptions: {
allowOrigins: ['https://my-origin-1.com', 'https://my-origin-2.com'],
allowHeaders: Cors.DEFAULT_HEADERS.concat(['x-api-key'])
}
});
#set($origin = $input.params(\"Origin\"))
#if($origin == \"\")
#set($origin = $input.params(\"origin\"))
#end
#if($origin.matches(\"https://my-origin-1.com\") || $origin.matches(\"https://my-origin-2.com\")
#set($context.responseOverride.header.Access-Control-Allow-Origin = $origin)
#end
const getAllowOrigin = (origins: string[]) =>
{
const condition = origins
.map(x => `$origin.matches(\"${x}\")`)
.reduce((l,r) => `${l} || ${r}`);
return `#set($origin = $input.params(\"Origin\"))\n#if($origin == \"\") #set($origin = $input.params(\"origin\")) #end\n#if(${condition})\n #set($context.responseOverride.header.Access-Control-Allow-Origin = $origin)\n#end\n`;
}
// const origins = ['https://my-origin-1.com', 'https://my-origin-2.com'];
const responses: IntegrationResponse[] = [{
statusCode: "200",
responseTemplates: {
'application/json': getAllowOrigin(origins) + '$input.body' // or other template you need
}
}/*, ...rest of your responses */];
// Request
{
...
"headers": {
"header1": "value1",
"header2": "value2"
},
...
}
ISet<string> allowedOrigins; // ["https://my-origin-1.com", "https://my-origin-2.com"] received e.g. from SSM
var originHeader = request.headers.FirstOrDefault(x => "Origin".Equals(x.Key, StringComparison.InvariantCultureIgnoreCase));
// Only single allowed origin is possible in the response. Pick it based on the origin of the request
var allowedOrigin = allowedOrigins.Contains(originHeader.Value?.ToLower()) ? originHeader.Value : string.Empty;
return new // response
{
headers = new Dictionary<string, string>
{
{ "Access-Control-Allow-Origin", allowedOrigin },
const mockIntegration = new MockIntegration({
requestTemplates: {
'application/json': '{"statusCode": 200}'
},
integrationResponses: [{
statusCode: '200',
responseTemplates: {
'text/plain':
`User-agent: *
Disallow: /
const methodOptions: MethodOptions = {
methodResponses: [{
statusCode: '200',
responseModels: {
'text/plain': Model.EMPTY_MODEL
}
}]
};
// Having defined const api: RestApi
const robotsResource = api.root.addResource('robots.txt');
const headMethod = robotsResource.addMethod('HEAD', mockIntegration, methodOptions);
const getMethod = robotsResource.addMethod('GET', mockIntegration, methodOptions);