콘텐츠로 이동

React 웹사이트 인증

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

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

React 웹사이트에 인증을 추가하는 두 가지 방법이 있습니다:

Terminal window
pnpm nx g @aws/nx-plugin:ts#website#auth
어떤 파일이 변경될지 확인하기 위해 드라이 런을 수행할 수도 있습니다
Terminal window
pnpm nx g @aws/nx-plugin:ts#website#auth --dry-run
매개변수타입기본값설명
project 필수string-웹사이트의 루트 디렉토리입니다.
cognitoDomain string-사용할 Cognito 도메인 접두사입니다. 생략하면 npm scope와 웹사이트 프로젝트 이름에서 값이 파생됩니다.
allowSignup boolean자가 가입을 허용할지 여부입니다.
iac inherit | cdk | terraforminherit선호하는 IaC 공급자입니다. 기본적으로 초기 선택에서 상속됩니다.
preferInstallDependencies booleantrue생성기 실행 후 의존성 설치를 선호할지 여부입니다. 여러 생성기를 일괄 처리할 때 설치를 연기하려면 false로 설정하세요 (후속 생성기가 Nx 프로젝트 그래프를 계산할 수 있도록 필요한 경우 설치는 여전히 실행됩니다); 마지막에 한 번만 설치합니다.

React 웹사이트에서 다음과 같은 변경 사항을 확인할 수 있습니다:

  • 디렉터리src
    • 디렉터리components
      • 디렉터리CognitoAuth
        • index.tsx Main authentication component
    • main.tsx Updated to instrument the CognitoAuth component

이 생성기는 선택한 iac를 기반으로 코드형 인프라를 제공하므로, 관련 CDK constructs 또는 Terraform 모듈을 포함하는 packages/common에 프로젝트를 생성합니다.

공통 코드형 인프라 프로젝트는 다음과 같이 구성됩니다:

  • 디렉터리packages/common/constructs
    • 디렉터리src
      • 디렉터리app/ 프로젝트/생성기에 특정한 인프라를 위한 Constructs
      • 디렉터리core/ app의 constructs에서 재사용되는 일반 constructs
      • index.ts app에서 constructs를 내보내는 진입점
    • project.json 프로젝트 빌드 타겟 및 구성

선택한 iac에 따라 다음과 같은 인프라 코드가 생성됩니다:

  • 디렉터리packages/common/constructs/src
    • 디렉터리core
      • user-identity.ts Construct which defines the user pool and identity pool

이 생성기는 기존 정적 웹사이트 아키텍처에 Amazon Cognito 사용자 풀(로그인용)과 자격 증명 풀(로그인한 사용자를 범위가 지정된 IAM 자격 증명으로 페더레이션하기 위한)을 추가합니다:

Web BrowserWAFCognito(User + Identity Pool)Scoped IAMCredentialsAuthenticatedAWS Resources Sign in IAM/Cognito

User Pool은 표준 인증을 위해 위협 보호AUDIT 모드로 설정된 Cognito Plus 기능 플랜에서 생성됩니다. 감사 모드에서 Cognito는 각 로그인에 위험 수준을 할당하고 사용자를 차단하지 않고 평가를 CloudWatch에 기록합니다.

사용자에 대한 위험 평가를 관찰한 후, 위험한 활동에 자동으로 대응하도록(예: MFA 요구 또는 로그인 차단) 전체 기능 적용으로 전환할 수 있습니다:

packages/common/constructs/src/core/user-identity.ts에서 standardThreatProtectionModeStandardThreatProtectionMode.FULL_FUNCTION으로 설정하세요.

기본적으로 사용자는 로그인하기 전에 MFA(SMS 코드 또는 시간 기반 일회용 비밀번호)를 구성해야 합니다. MFA를 선택 사항으로 만들거나, 완전히 끄거나, 사용 가능한 2단계 인증 방법을 제한할 수 있습니다:

import { Mfa } from 'aws-cdk-lib/aws-cognito';
new UserIdentity(this, 'Identity', {
mfa: Mfa.OPTIONAL,
mfaSecondFactor: { sms: false, otp: true },
});

mfaMfa.OFF / Mfa.OPTIONAL / Mfa.REQUIRED를 허용합니다. mfaSecondFactor.smsmfaSecondFactor.otp는 각 2단계 인증 방법을 독립적으로 활성화하거나 비활성화합니다. mfaMfa.OFF일 때는 효과가 없습니다. 두 방법을 모두 비활성화한 상태에서 mfa: Mfa.REQUIRED를 설정하면 아무도 로그인을 완료할 수 없으므로 synth 시점에 거부됩니다.

기본적으로 User Pool은 AWSManagedRulesCommonRuleSetAWSManagedRulesKnownBadInputsRuleSet 관리형 규칙 그룹을 사용하는 AWS WAFv2 Web ACL과 연결됩니다. 자체 Web ACL을 관리하거나 필요하지 않은 경우 이를 비활성화할 수 있습니다:

new UserIdentity(this, 'Identity', { enableWaf: false });

스택에 사용자 자격 증명 인프라를 추가해야 하며, 웹사이트 이전에 선언해야 합니다:

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 User Pool을 가리킬 수 있도록 필요한 런타임 구성을 자동으로 추가합니다.

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

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

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', {
integrations: MyApi.defaultIntegrations(this).build(),
});
api.grantInvokeAccess(identity.identityPool.authenticatedRole);
new MyWebsite(this, 'MyWebsite');
}
}