콘텐츠로 이동

React 웹사이트 인증

React 웹사이트 인증 생성기는 Amazon Cognito를 사용하여 React 웹사이트에 인증 기능을 추가합니다.

이 생성기는 CDK 또는 Terraform 인프라를 구성하여 Cognito 사용자 풀 및 관련 Identity Pool, 사용자 로그인 흐름을 처리하는 호스팅된 UI, 그리고 React 웹사이트와의 통합을 설정합니다.

다음 두 가지 방법으로 React 웹사이트에 인증을 추가할 수 있습니다:

  1. 설치 Nx Console VSCode Plugin 아직 설치하지 않았다면
  2. VSCode에서 Nx 콘솔 열기
  3. 클릭 Generate (UI) "Common Nx Commands" 섹션에서
  4. 검색 @aws/nx-plugin - ts#react-website#auth
  5. 필수 매개변수 입력
    • 클릭 Generate
    매개변수 타입 기본값 설명
    project 필수 string - The root directory of the React website.
    cognitoDomain 필수 string - The cognito domain prefix to use
    allowSignup boolean Whether to allow self-signup
    iacProvider string Inherit The preferred IaC provider. By default this is inherited from your initial selection.

    React 웹사이트에 다음과 같은 변경 사항이 적용됩니다:

    • 디렉터리src
      • 디렉터리components
        • 디렉터리CognitoAuth
          • index.tsx 기본 인증 컴포넌트
      • main.tsx CognitoAuth 컴포넌트를 적용하도록 업데이트

    이 생성기는 선택한 iacProvider 기반으로 인프라를 코드 형태로 제공하므로, packages/common 디렉터리에 관련 CDK 구축 요소 또는 Terraform 모듈을 포함하는 프로젝트를 생성합니다.

    공통 인프라스트럭처 코드 프로젝트의 구조는 다음과 같습니다:

    • 디렉터리packages/common/constructs
      • 디렉터리src
        • 디렉터리app/ 특정 프로젝트/생성기에 종속적인 인프라를 위한 구축 요소
        • 디렉터리core/ app 내 구축 요소에서 재사용되는 일반적 구축 요소
        • index.ts app의 구축 요소를 익스포트하는 진입점
      • project.json 프로젝트 빌드 대상 및 구성

    선택한 iacProvider에 따라 다음 인프라 코드가 생성됩니다:

    • 디렉터리packages/common/constructs/src
      • 디렉터리core
        • user-identity.ts 사용자 풀 및 Identity Pool을 정의하는 Construct

    웹사이트 선언 이전에 사용자 Identity 인프라를 스택에 추가해야 합니다:

    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 Construct는 웹사이트가 올바른 Cognito 사용자 풀을 가리킬 수 있도록 필요한 런타임 구성을 자동으로 추가합니다.

    인증된 사용자에게 액세스 권한 부여

    섹션 제목: “인증된 사용자에게 액세스 권한 부여”

    API 호출 권한 부여와 같이 인증된 사용자에게 특정 작업 수행 권한을 부여하려면 Identity Pool의 인증된 역할에 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');
    }
    }