React 웹사이트 인증
React 웹사이트 인증 생성기는 Amazon Cognito를 사용하여 React 웹사이트에 인증을 추가합니다.
이 생성기는 CDK 또는 Terraform 인프라를 구성하여 Cognito User Pool 및 관련 Identity Pool을 생성하고, 사용자 로그인 플로우를 처리하는 호스팅 UI와 React 웹사이트와의 통합을 설정합니다.
사용법
섹션 제목: “사용법”React 웹사이트에 인증 추가하기
섹션 제목: “React 웹사이트에 인증 추가하기”React 웹사이트에 인증을 추가하는 두 가지 방법이 있습니다:
pnpm nx g @aws/nx-plugin:ts#website#authyarn nx g @aws/nx-plugin:ts#website#authnpx nx g @aws/nx-plugin:ts#website#authbunx nx g @aws/nx-plugin:ts#website#auth어떤 파일이 변경될지 확인하기 위해 드라이 런을 수행할 수도 있습니다
pnpm nx g @aws/nx-plugin:ts#website#auth --dry-runyarn nx g @aws/nx-plugin:ts#website#auth --dry-runnpx nx g @aws/nx-plugin:ts#website#auth --dry-runbunx nx g @aws/nx-plugin:ts#website#auth --dry-run- 설치 Nx Console VSCode Plugin 아직 설치하지 않았다면
- VSCode에서 Nx 콘솔 열기
- 클릭
Generate (UI)"Common Nx Commands" 섹션에서 - 검색
@aws/nx-plugin - ts#website#auth - 필수 매개변수 입력
- 클릭
Generate
| 매개변수 | 타입 | 기본값 | 설명 |
|---|---|---|---|
| project 필수 | string | - | 웹사이트의 루트 디렉토리입니다. |
| cognitoDomain | string | - | 사용할 Cognito 도메인 접두사입니다. 생략하면 npm scope와 웹사이트 프로젝트 이름에서 값이 파생됩니다. |
| allowSignup | boolean | 자가 가입을 허용할지 여부입니다. | |
| iac | inherit | cdk | terraform | inherit | 선호하는 IaC 공급자입니다. 기본적으로 초기 선택에서 상속됩니다. |
| preferInstallDependencies | boolean | true | 생성기 실행 후 의존성 설치를 선호할지 여부입니다. 여러 생성기를 일괄 처리할 때 설치를 연기하려면 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 프로젝트 빌드 타겟 및 구성
디렉터리packages/common/terraform
디렉터리src
디렉터리app/ 프로젝트/생성기에 특정한 인프라를 위한 Terraform 모듈
- …
디렉터리core/
app의 모듈에서 재사용되는 일반 모듈- …
- project.json 프로젝트 빌드 타겟 및 구성
선택한 iac에 따라 다음과 같은 인프라 코드가 생성됩니다:
디렉터리packages/common/constructs/src
디렉터리core
- user-identity.ts Construct which defines the user pool and identity pool
디렉터리packages/common/terraform/src
디렉터리core
디렉터리user-identity
- main.tf Module wrapper for the identity configuration
디렉터리identity
- identity.tf Core identity infrastructure including Cognito User Pool and Identity Pool
디렉터리add-callback-url
- add-callback-url.tf Module for adding callback URLs to existing user pool clients
아키텍처
섹션 제목: “아키텍처”이 생성기는 기존 정적 웹사이트 아키텍처에 Amazon Cognito 사용자 풀(로그인용)과 자격 증명 풀(로그인한 사용자를 범위가 지정된 IAM 자격 증명으로 페더레이션하기 위한)을 추가합니다:
위협 보호
섹션 제목: “위협 보호”User Pool은 표준 인증을 위해 위협 보호가 AUDIT 모드로 설정된 Cognito Plus 기능 플랜에서 생성됩니다. 감사 모드에서 Cognito는 각 로그인에 위험 수준을 할당하고 사용자를 차단하지 않고 평가를 CloudWatch에 기록합니다.
사용자에 대한 위험 평가를 관찰한 후, 위험한 활동에 자동으로 대응하도록(예: MFA 요구 또는 로그인 차단) 전체 기능 적용으로 전환할 수 있습니다:
packages/common/constructs/src/core/user-identity.ts에서 standardThreatProtectionMode를 StandardThreatProtectionMode.FULL_FUNCTION으로 설정하세요.
packages/common/terraform/src/core/user-identity/identity/identity.tf의 user_pool_add_ons 블록에서 advanced_security_mode를 ENFORCED로 설정하세요.
다중 인증(MFA)
섹션 제목: “다중 인증(MFA)”기본적으로 사용자는 로그인하기 전에 MFA(SMS 코드 또는 시간 기반 일회용 비밀번호)를 구성해야 합니다. MFA를 선택 사항으로 만들거나, 완전히 끄거나, 사용 가능한 2단계 인증 방법을 제한할 수 있습니다:
import { Mfa } from 'aws-cdk-lib/aws-cognito';
new UserIdentity(this, 'Identity', { mfa: Mfa.OPTIONAL, mfaSecondFactor: { sms: false, otp: true },});mfa는 Mfa.OFF / Mfa.OPTIONAL / Mfa.REQUIRED를 허용합니다. mfaSecondFactor.sms와 mfaSecondFactor.otp는 각 2단계 인증 방법을 독립적으로 활성화하거나 비활성화합니다. mfa가 Mfa.OFF일 때는 효과가 없습니다. 두 방법을 모두 비활성화한 상태에서 mfa: Mfa.REQUIRED를 설정하면 아무도 로그인을 완료할 수 없으므로 synth 시점에 거부됩니다.
module "user_identity" { source = "../../common/terraform/src/core/user-identity"
mfa = "OPTIONAL" mfa_second_factor_sms = false mfa_second_factor_otp = true}mfa는 "OFF" / "OPTIONAL" / "ON"을 허용합니다. mfa_second_factor_sms와 mfa_second_factor_otp는 각 2단계 인증 방법을 독립적으로 활성화하거나 비활성화합니다. mfa가 "OFF"일 때는 효과가 없습니다.
웹 애플리케이션 방화벽(WAF)
섹션 제목: “웹 애플리케이션 방화벽(WAF)”기본적으로 User Pool은 AWSManagedRulesCommonRuleSet 및 AWSManagedRulesKnownBadInputsRuleSet 관리형 규칙 그룹을 사용하는 AWS WAFv2 Web ACL과 연결됩니다. 자체 Web ACL을 관리하거나 필요하지 않은 경우 이를 비활성화할 수 있습니다:
new UserIdentity(this, 'Identity', { enableWaf: false });module "user_identity" { source = "../../common/terraform/src/core/user-identity"
enable_waf = false}인프라 사용법
섹션 제목: “인프라 사용법”스택에 사용자 자격 증명 인프라를 추가해야 하며, 웹사이트 이전에 선언해야 합니다:
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을 가리킬 수 있도록 필요한 런타임 구성을 자동으로 추가합니다.
사용자 자격 증명 모듈을 추가하고 웹사이트가 이에 의존하도록 해야 합니다:
# Deploy user identity first to add to runtime configmodule "user_identity" { source = "../../common/terraform/src/core/user-identity"}
# Deploy website after identity to include runtime configmodule "my_website" { source = "../../common/terraform/src/app/static-websites/my-website"
providers = { aws.us_east_1 = aws.us_east_1 }
# Ensure identity is deployed first to add to runtime config depends_on = [module.user_identity]}사용자 자격 증명 모듈은 웹사이트가 인증을 위해 올바른 Cognito User Pool을 가리킬 수 있도록 필요한 런타임 구성을 자동으로 추가합니다.
인증된 사용자에게 액세스 권한 부여
섹션 제목: “인증된 사용자에게 액세스 권한 부여”API 호출 권한 부여와 같이 인증된 사용자에게 특정 작업을 수행할 수 있는 액세스 권한을 부여하려면 자격 증명 풀의 인증된 역할에 IAM 정책 문을 추가할 수 있습니다:
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'); }}module "user_identity" { source = "../../common/terraform/src/core/user-identity"}
module "asset_bucket" { source = "../../common/terraform/src/core/asset-bucket"}
module "my_api" { source = "../../common/terraform/src/app/apis/my-api"
asset_bucket_name = module.asset_bucket.bucket_name}
# Add permissions for authenticated users to invoke Fast APIresource "aws_iam_role_policy" "authenticated_fast_api_invoke" { name = "authenticated-user-invoke-my-api" role = module.user_identity.authenticated_role_name
policy = jsonencode({ Version = "2012-10-17" Statement = [ { Effect = "Allow" Action = [ "execute-api:Invoke" ] Resource = "${module.my_api.api_execution_arn}/*" } ] })}