Aws Cdk RestApi Cognito 和 IAM 授权

问题描述 投票:0回答:1

我正在尝试重建我的 Amplify 项目,该项目当前使用具有 Cognito 和 IAM 授权模式的 AppSync。由于我想使用 CDK 构建所有资源并希望用 API Gateway 替换 AppSync,所以我想知道如何支持 Cognito 以及 IAM 访问。

那么如何为使用 AWS CDK 构建的 RestApi 实现 Cognito 和 IAM(访客访问)授权?

AppSync 已支持指定两种授权模式:

const api = new GraphqlApi(this, 'TodoTestAPI', {
  name: 'TodoTestAPI',
  schema: Schema.fromAsset(path.join(__dirname, 'schema.graphql')),
  authorizationConfig: {
    defaultAuthorization: {
      authorizationType: AuthorizationType.USER_POOL,
      userPoolConfig: {
        userPool,
      },
    },
    additionalAuthorizationModes: [
      {
        authorizationType: AuthorizationType.IAM,
      },
    ],
  },

如何使用 RestApi 做到这一点?

我当前的代码如下所示:

        const api = new RestApi(this, `RestApi`, {
            defaultMethodOptions: {
                authorizationType: AuthorizationType.IAM,
            },
            defaultCorsPreflightOptions: {
                allowOrigins: Cors.ALL_ORIGINS,
                allowMethods: Cors.ALL_METHODS,
            },
            cloudWatchRole: true,
        });
aws-api-gateway amazon-cognito amazon-iam aws-cdk aws-appsync
1个回答
0
投票

我将其放在一起,以便与 API 网关进行 lambda 集成。成功登录到

Cognito
后的 idToken 需要通过每个 API 请求传递到
Authorization
标头。

我认为您需要创建一个

authorizer
并将其附加到您的 API 网关:

  let api = new apigateway.RestApi(this, "knowledgeBaseApi", {
    description: "Used by the LLM Knowledge Base to integrate services",
    deployOptions: { stageName: "dev" },
    defaultCorsPreflightOptions: {
      allowOrigins: ["*"],
      allowHeaders: ["*"],
      allowMethods: ["*"],
    },
    
  });
  let apiAuth = new apigateway.CognitoUserPoolsAuthorizer(
    this,
    "cognitoAuth",
    {
      cognitoUserPools: [userPool],
    },
  );
  apiAuth._attachToApi(api);

然后,当您创建路径时,您可以指定此

authorizer

let home = api.root.addResource("home");

  home.addMethod(
    "GET",
    new apigateway.LambdaIntegration(lambdaProxyFunc, { proxy: true }),
    {
      authorizer: apiAuth,
// Also require passing "Authorization" as a header
      requestParameters: {
        "method.request.header.Authorization": true,
      },
      requestValidatorOptions: {
        validateRequestParameters: true,
      },
    },
  );
© www.soinside.com 2019 - 2024. All rights reserved.