AWS CDK user pool authorizer

前端 未结 7 1405
滥情空心
滥情空心 2021-02-12 23:31

I\'m trying to create an API gateway using the AWS-CDK and protect the REST endpoints with a Cognito user pool authorizer.

I cannot find any examples how one would do th

7条回答
  •  感动是毒
    2021-02-13 00:12

    You have to:

    • create the api gateway
    • set Cognito as authorizer in the api gateway
    • set the authorization in your method
    • set your integration with the lambda to 'Use Lambda Proxy integration'. The LambdaIntegration properties has on true this value by default, so don't worry for it

    Finally, make a request adding the token in the Header. The API gateway will validate it with Cognito. If this pass then, your lambda will be triggered and in the event you can find the claims event.requestContext.authorizer.claims.

    
    const lambda = require("@aws-cdk/aws-lambda");
    const apiGateway = require('@aws-cdk/aws-apigateway'); 
    
     const api = new apiGateway.RestApi(
          this,
          '',
          {
            restApiName: '',
          },
        );
    
        const auth = new apiGateway.CfnAuthorizer(this, '', {
          name: "",
          type: apiGateway.AuthorizationType.COGNITO,
          authorizerResultTtlInSeconds: 300,
          identitySource: "method.request.header.Authorization",
          restApiId: api.restApiId,
          providerArns: [''],
        });
    
        const myLambda= new lambda.Function(this, "", {
          functionName: '',
          runtime: lambda.Runtime.NODEJS_10_X,
          handler: "",
          code: lambda.Code.fromAsset(""), // TODO: modify the way to get the path
        });
    
          const lambdaIntegration = new apiGateway.LambdaIntegration(myLambda);
    
          const resource = api.root.resourceForPath('');
          // When the API will be deployed, the URL will look like this
          // https://xxxxxx.execute-api.us-east-2.amazonaws.com/dev/
    
          const authorizationOptions = {
            apiKeyRequired: false,
            authorizer: {authorizerId: auth.ref},
            authorizationType: 'COGNITO_USER_POOLS'
          };
    
          resource.addMethod(
            GET, // your method
            lambdaIntegration,
            authorizationOptions
          );
    
    

提交回复
热议问题