跳转到内容

CloudScape网站身份验证

CloudScape 网站认证生成器通过Amazon Cognito为您的 CloudScape 网站添加身份验证功能。

该生成器会配置 CDK 基础设施,用于创建 Cognito 用户池及关联的身份池、处理用户登录流程的托管 UI,并将其与您的 CloudScape 网站集成。

使用方法

为 CloudScape 网站添加认证

您可以通过两种方式为 CloudScape 网站添加认证:

  1. 安装 Nx Console VSCode Plugin 如果您尚未安装
  2. 在VSCode中打开Nx控制台
  3. 点击 Generate (UI) 在"Common Nx Commands"部分
  4. 搜索 @aws/nx-plugin - ts#cloudscape-website#auth
  5. 填写必需参数
    • 点击 Generate

    配置选项

    参数 类型 默认值 描述
    project 必需 string - The root directory of the Cloudscape application.
    cognitoDomain 必需 string - The cognito domain prefix to use
    allowSignup boolean Whether to allow self-signup

    生成器输出

    您的 React 网站将产生以下变更:

    • 文件夹src
      • 文件夹components
        • 文件夹CognitoAuth
          • index.tsx 主认证组件
      • main.tsx 更新以集成 CognitoAuth 组件

    packages/common/constructs 目录下将生成以下基础设施代码:

    • 文件夹src
      • 文件夹core
        • user-identity.ts 定义用户池和身份池的构造

    基础设施使用

    您需要在堆栈中添加 UserIdentity 构造,并确保其声明在网站构造之前:

    packages/infra/src/stacks/application-stack.ts
    import { Stack } from 'aws-cdk-lib';
    import { Construct } from 'constructs';
    import { MyWebsite, UserIdentity } from ':my-scope/common-constructs';
    export class ApplicationStack extends Stack {
    constructor(scope: Construct, id: string) {
    super(scope, id);
    new UserIdentity(this, 'Identity');
    new MyWebsite(this, 'MyWebsite');
    }
    }

    UserIdentity 构造会自动添加必要的运行时配置,确保您的网站能正确指向 Cognito 用户池进行认证。

    授予认证用户访问权限

    要为认证用户授予特定操作权限(例如允许调用 API),可向身份池的认证角色添加 IAM 策略声明:

    packages/infra/src/stacks/application-stack.ts
    import { Stack } from 'aws-cdk-lib';
    import { Construct } from 'constructs';
    import { MyWebsite, UserIdentity, MyApi } from ':my-scope/common-constructs';
    export class ApplicationStack extends Stack {
    constructor(scope: Construct, id: string) {
    super(scope, id);
    const identity = new UserIdentity(this, 'Identity');
    const api = new MyApi(this, 'MyApi');
    api.grantInvokeAccess(identity.identityPool.authenticatedRole);
    new MyWebsite(this, 'MyWebsite');
    }
    }