Skip to content

Commit

Permalink
fix(apigateway): allow overriding apiKeyRequired on methods
Browse files Browse the repository at this point in the history
RestApi has the ability to set the apiKeyRequired option for all methods via defaultMethodOptions.

Setting this option on a method should override the value set in defaultMethodOptions, but it doesn't work.

This commit fixes the behaviour and adds a test.

Mentioned in aws#8827
  • Loading branch information
iRoachie committed May 23, 2023
1 parent dc4bbec commit 5673b75
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 2 deletions.
2 changes: 1 addition & 1 deletion packages/aws-cdk-lib/aws-apigateway/lib/method.ts
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,7 @@ export class Method extends Resource {
restApiId: this.api.restApiId,
httpMethod: this.httpMethod,
operationName: options.operationName || defaultMethodOptions.operationName,
apiKeyRequired: options.apiKeyRequired || defaultMethodOptions.apiKeyRequired,
apiKeyRequired: options.apiKeyRequired ?? defaultMethodOptions.apiKeyRequired,
authorizationType,
authorizerId,
requestParameters: options.requestParameters || defaultMethodOptions.requestParameters,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -299,7 +299,7 @@ describe('lambda api', () => {
ResourceId: { Ref: 'lambdarestapiproxyE3AE07E3' },
AuthorizationType: 'NONE',
AuthorizerId: Match.absent(),
ApiKeyRequired: Match.absent(),
ApiKeyRequired: false,
Integration: {
IntegrationResponses: [
{
Expand Down
28 changes: 28 additions & 0 deletions packages/aws-cdk-lib/aws-apigateway/test/restapi.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1330,4 +1330,32 @@ describe('SpecRestApi', () => {
'AWS::ApiGateway::RestApi', {});
});
});

test('can override "apiKeyRequired" set in "defaultMethodOptions" at the resource level', () => {
// GIVEN
const stack = new Stack();

// WHEN
const api = new apigw.RestApi(stack, 'myapi', {
defaultMethodOptions: {
apiKeyRequired: true,
},
});

api.root.addMethod('GET', undefined, {});
api.root.addMethod('POST', undefined, {
apiKeyRequired: false,
});

// THEN
Template.fromStack(stack).hasResourceProperties('AWS::ApiGateway::Method', {
HttpMethod: 'GET',
ApiKeyRequired: true,
});

Template.fromStack(stack).hasResourceProperties('AWS::ApiGateway::Method', {
HttpMethod: 'POST',
ApiKeyRequired: false,
});
});
});

0 comments on commit 5673b75

Please sign in to comment.