'AWS CDK - Cognito UserPool authorizer on API Gateway not working
My goal is to set up some lambda functions which are public (i.e. no authorization required to send requests) and other ones which require a User to be logged in within a Cognito UserPool.
In my CDK file below, I'm adding an Authorizer only on one of the two endpoints, but then when I launch a request both of them are unprotected, and in the function logs you can see there is no Cognito UserPool nor AuthenticationType.
Any ideas on what's missing?
Thanks!
{
"httpMethod":"GET",
"body":null,
"resource":"/private",
"requestContext":{
...,
"identity":{
"apiKey":null,
"userArn":null,
"cognitoAuthenticationType":null,
"caller":null,
"userAgent":"Custom User Agent String",
"user":null,
"cognitoIdentityPoolId":null,
"cognitoAuthenticationProvider":null,
"sourceIp":"127.0.0.1",
"accountId":null
},
...
},
...
}
CDK file:
import * as apigateway from '@aws-cdk/aws-apigateway';
import * as lambda from '@aws-cdk/aws-lambda';
import * as s3 from '@aws-cdk/aws-s3';
import { UserPool, VerificationEmailStyle, UserPoolClient } from '@aws-cdk/aws-cognito'
import { App, CfnParameter, Duration, Stack, StackProps } from '@aws-cdk/core';
export class CdkStack extends Stack {
constructor(scope: App, id: string, props: StackProps) {
super(scope, id, props);
new CfnParameter(this, 'AppId');
const userPool = new UserPool(this, 'dev-users', {
userPoolName: 'dev-users',
selfSignUpEnabled: true,
userVerification: {
emailSubject: 'Verify your email for our awesome app!',
emailBody: 'Hello {username}, Thanks for signing up to our awesome app! Your verification code is {####}',
emailStyle: VerificationEmailStyle.CODE,
smsMessage: 'Hello {username}, Thanks for signing up to our awesome app! Your verification code is {####}',
},
signInAliases: {
email: true
},
signInCaseSensitive: false,
standardAttributes: {
email: { required: true, mutable: false }
},
passwordPolicy: {
minLength: 6,
requireLowercase: true,
requireUppercase: true,
requireDigits: true,
requireSymbols: false,
tempPasswordValidity: Duration.days(7),
}
})
const environment = { };
// The code will be uploaded to this location during the pipeline's build step
const artifactBucket = s3.Bucket.fromBucketName(this, 'ArtifactBucket', process.env.S3_BUCKET!);
const artifactKey = `${process.env.CODEBUILD_BUILD_ID}/function-code.zip`;
const code = lambda.Code.fromBucket(artifactBucket, artifactKey);
// This is a Lambda function config associated with the source code: get-all-items.js
const publicFunction = new lambda.Function(this, 'publicFunction', {
description: 'A simple example includes a HTTP get method accessible to everyone',
handler: 'src/handlers/public.publicHandler',
runtime: lambda.Runtime.NODEJS_10_X,
code,
environment,
timeout: Duration.seconds(60),
});
// Give Read permissions to the SampleTable
// This is a Lambda function config associated with the source code: put-item.js
const privateFunction = new lambda.Function(this, 'privateFunction', {
description: 'This functions should only be accessible to authorized users from a Cognito UserPool',
handler: 'src/handlers/private.privateHandler',
runtime: lambda.Runtime.NODEJS_10_X,
code,
timeout: Duration.seconds(60),
environment,
});
const api = new apigateway.RestApi(this, 'ServerlessRestApi', { cloudWatchRole: false });
const authorizer = new apigateway.CfnAuthorizer(this, 'cfnAuth', {
restApiId: api.restApiId,
name: 'HelloWorldAPIAuthorizer',
type: 'COGNITO_USER_POOLS',
identitySource: 'method.request.header.Authorization',
providerArns: [userPool.userPoolArn],
})
api.root.addResource('public').addMethod(
'GET',
new apigateway.LambdaIntegration(publicFunction)
);
api.root.addResource('private').addMethod(
'GET',
new apigateway.LambdaIntegration(privateFunction),
{
authorizationType: apigateway.AuthorizationType.COGNITO,
authorizer: {
authorizerId: authorizer.ref
}
}
);
}
}
const app = new App();
new CdkStack(app, 'CognitoProtectedApi', {});
app.synth();
Solution 1:[1]
Try doing the following in your addMethod
.
{
authorizationType: apigateway.AuthorizationType.COGNITO,
authorizer // pass the authorizer object instead of authorizerId stuff.
}
Refer https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_apigateway.CognitoUserPoolsAuthorizer.html for more details.
Following is for AWS CDK 2.20.0
You can create a CognitoUserPoolsAuthorizer
and then either attach it as default authorizer for an API GW, or attach it specific route.
For adding to a specific method,
const userPool = new cognito.UserPool(this, 'UserPool');
const auth = new apigateway.CognitoUserPoolsAuthorizer(this, 'booksAuthorizer', {
cognitoUserPools: [userPool]
});
declare const books: apigateway.Resource;
books.addMethod('GET', new apigateway.HttpIntegration('http://amazon.com'), {
authorizer: auth,
authorizationType: apigateway.AuthorizationType.COGNITO,
})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Akshay Kumar |