Triển Khai Cognito Và S3 Bucket

Trong phần này, chúng ta sẽ dùng AWS SAM để tạo Cognito User Pool, User Pool Client, Identity Pool và S3 bucket lưu các tệp người dùng tải lên. Đây là các tài nguyên mà Amplify Gen 2 đã tạo cho bạn ở workshop 134.

Bạn cần cài đặt SAM CLI phiên bản 1.146.0 trở lên và cấu hình credentials với câu lệnh aws configure (region ap-southeast-1) trước khi thực hiện phần này.

  1. Chạy câu lệnh sau để khởi tạo một SAM project:
sam init
  • Chọn các thông tin như sau:
Which template source would you like to use?
	1 - AWS Quick Start Templates
	2 - Custom Template Location
Choice: 1

Choose an AWS Quick Start application template
	1 - Hello World Example
	...
Template: 1

Use the most popular runtime and package type? (python3.14 and zip) [y/N]: y

Would you like to enable X-Ray tracing on the function(s) in your application?  [y/N]: N

Would you like to enable monitoring using CloudWatch Application Insights?
For more info, please view https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch-application-insights.html [y/N]: N

Would you like to set Structured Logging in JSON format on your Lambda functions?  [y/N]: N

Project name [sam-app]: fcajdms-sam

Nếu SAM CLI đề xuất một runtime khác python3.14, hãy nhập N, sau đó chọn runtime python3.14 và package type Zip.

SAMInit

  1. Mở thư mục fcajdms-sam bằng trình chỉnh sửa:
cd fcajdms-sam
  • Xoá các thư mục hello_world, events và tests vì chúng ta không dùng hàm mẫu.
  • Mở tệp template.yaml và thay toàn bộ nội dung bằng đoạn code dưới đây:
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
  fcajdms-sam

  FCAJ Serverless Document Management System

Globals:
  Function:
    Runtime: python3.14
    Timeout: 10
    Architectures:
      - x86_64

Resources:
  • Phần Globals khai báo thiết lập chung cho mọi Lambda function của template: runtime Python 3.14 (giống các hàm của workshop 133), timeout 10 giây và kiến trúc x86_64.

SAMInit

  1. Sao chép đoạn code sau vào bên dưới dòng Resources:
  # Cognito User Pool: users sign up and sign in with their email
  FcajDMSUserPool:
    Type: AWS::Cognito::UserPool
    Properties:
      UserPoolName: fcaj-dms-user-pool
      UsernameAttributes:
        - email
      AutoVerifiedAttributes:
        - email
      MfaConfiguration: "OFF"
      EmailConfiguration:
        EmailSendingAccount: COGNITO_DEFAULT
      AccountRecoverySetting:
        RecoveryMechanisms:
          - Name: verified_email
            Priority: 1
      Schema:
        - Name: email
          AttributeDataType: String
          Required: true
          Mutable: true
      Policies:
        PasswordPolicy:
          MinimumLength: 8
          RequireLowercase: true
          RequireNumbers: true
          RequireSymbols: true
          RequireUppercase: true
          TemporaryPasswordValidityDays: 7
      UserAttributeUpdateSettings:
        AttributesRequireVerificationBeforeUpdate:
          - email

  # App client used by the web application (no client secret)
  FcajDMSUserPoolClient:
    Type: AWS::Cognito::UserPoolClient
    Properties:
      ClientName: fcaj-dms-client
      UserPoolId: !Ref FcajDMSUserPool
      GenerateSecret: false
      ExplicitAuthFlows:
        - ALLOW_USER_SRP_AUTH
        - ALLOW_REFRESH_TOKEN_AUTH

  # Identity Pool: temporary AWS credentials to access S3 directly
  FcajDMSIdentityPool:
    Type: AWS::Cognito::IdentityPool
    Properties:
      IdentityPoolName: fcaj_dms_identity_pool
      AllowUnauthenticatedIdentities: true
      CognitoIdentityProviders:
        - ClientId: !Ref FcajDMSUserPoolClient
          ProviderName: !GetAtt FcajDMSUserPool.ProviderName

Đoạn code dùng để khởi tạo các tài nguyên:

  • Một User Pool: người dùng đăng ký và đăng nhập bằng email (UsernameAttributes), email được xác thực bằng mã gửi tự động (AutoVerifiedAttributes). Chính sách mật khẩu yêu cầu ít nhất 8 ký tự, gồm chữ hoa, chữ thường, chữ số và ký tự đặc biệt, giống chính sách mặc định của Amplify Gen 2 và điều kiện kiểm tra mật khẩu của ứng dụng.
  • Một User Pool Client: ứng dụng web dùng client này để đăng nhập với giao thức SRP. Client không có client secret vì ứng dụng chạy trên trình duyệt.
  • Một Identity Pool: cấp thông tin xác thực AWS tạm thời để ứng dụng tải tệp lên và tải tệp từ S3 bucket.

User Pool phải dùng email làm tên đăng nhập để ứng dụng gọi được signUp với email, giống workshop 134. Tên hiển thị (Display name) được lưu vào thuộc tính chuẩn preferred_username. App client không giới hạn write attributes nên ứng dụng có thể ghi và cập nhật thuộc tính này.

CreateUserPool

  1. Tiếp theo chúng ta sẽ tạo role cho người dùng chưa đăng nhập và đã đăng nhập, sau đó gắn hai role này vào Identity Pool. Thêm đoạn code sau vào cuối tệp:
  # Role for guests: no access to AWS resources
  CognitoUnauthenticatedRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: Allow
            Principal:
              Federated: cognito-identity.amazonaws.com
            Action: sts:AssumeRoleWithWebIdentity
            Condition:
              StringEquals:
                "cognito-identity.amazonaws.com:aud": !Ref FcajDMSIdentityPool
              "ForAnyValue:StringLike":
                "cognito-identity.amazonaws.com:amr": unauthenticated

  # Role for signed-in users: same "protected" access level as workshop 134
  CognitoAuthenticatedRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: Allow
            Principal:
              Federated: cognito-identity.amazonaws.com
            Action: sts:AssumeRoleWithWebIdentity
            Condition:
              StringEquals:
                "cognito-identity.amazonaws.com:aud": !Ref FcajDMSIdentityPool
              "ForAnyValue:StringLike":
                "cognito-identity.amazonaws.com:amr": authenticated
      Policies:
        - PolicyName: FcajDMSDocumentStoreAccess
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
              - Effect: Allow
                Action:
                  - s3:GetObject
                Resource: !Sub "${FcajDMSDocumentStore.Arn}/protected/*"
              - Effect: Allow
                Action:
                  - s3:PutObject
                  - s3:DeleteObject
                Resource: !Sub "${FcajDMSDocumentStore.Arn}/protected/${!cognito-identity.amazonaws.com:sub}/*"

  IdentityPoolRoleAttachment:
    Type: AWS::Cognito::IdentityPoolRoleAttachment
    Properties:
      IdentityPoolId: !Ref FcajDMSIdentityPool
      Roles:
        authenticated: !GetAtt CognitoAuthenticatedRole.Arn
        unauthenticated: !GetAtt CognitoUnauthenticatedRole.Arn
  • CognitoUnauthenticatedRole: role cho người dùng chưa đăng nhập, không có quyền truy cập tài nguyên AWS nào.
  • CognitoAuthenticatedRole: role cho người dùng đã đăng nhập, có quyền giống quy tắc protected/{entity_id}/* của workshop 134: mọi người dùng đã đăng nhập được đọc tệp trong thư mục protected/, nhưng chỉ chủ sở hữu mới được ghi và xoá tệp trong thư mục protected/{Identity ID}/ của mình.
  • ${!cognito-identity.amazonaws.com:sub}: dấu ! giúp !Sub giữ nguyên biến này trong policy. Khi người dùng gửi request, IAM thay biến bằng Identity ID của người dùng đó.
  • IdentityPoolRoleAttachment: gắn hai role trên vào Identity Pool.

CreateUserPool

  1. Tiếp theo chúng ta sẽ tạo S3 bucket lưu các tệp mà người dùng tải lên. Thêm đoạn code sau vào cuối tệp:
  # S3 bucket that stores the files uploaded by users
  FcajDMSDocumentStore:
    Type: AWS::S3::Bucket
    Properties:
      BucketName: !Sub "fcajdmsstore-${AWS::AccountId}-${AWS::Region}-an"
      BucketNamespace: account-regional
      CorsConfiguration:
        CorsRules:
          - AllowedHeaders:
              - '*'
            AllowedMethods:
              - GET
              - HEAD
              - PUT
              - POST
              - DELETE
            AllowedOrigins:
              - '*'
            ExposedHeaders:
              - x-amz-server-side-encryption
              - x-amz-request-id
              - x-amz-id-2
              - ETag
            MaxAge: 3000
  • BucketNamespace: account-regional: tạo bucket trong Account Regional namespace, giống lựa chọn Account Regional namespace (recommended) khi bạn tạo bucket ở workshop 135.
  • CorsConfiguration: cho phép ứng dụng web chạy trên trình duyệt tải tệp lên, tải tệp về và xoá tệp trong bucket.

Với Account Regional namespace, tên bucket chỉ cần duy nhất trong phạm vi tài khoản AWS và Region của bạn, và phải kết thúc bằng hậu tố chứa ID tài khoản và Region. Vì vậy template ghép tên bucket với ${AWS::AccountId} và ${AWS::Region}, ví dụ: fcajdmsstore-<ACCOUNT_ID>-ap-southeast-1-an. Bạn không cần đổi tên bucket và sẽ lấy tên đầy đủ ở tab Outputs của stack. Thuộc tính BucketNamespace cần SAM CLI phiên bản mới, nếu sam validate --lint báo BucketNamespace là thuộc tính không hợp lệ, hãy cập nhật SAM CLI.

CreateBucket

  1. Thêm phần Outputs vào cuối tệp để hiển thị các giá trị mà ứng dụng web cần:
Outputs:
  UserPoolId:
    Description: Cognito User Pool ID
    Value: !Ref FcajDMSUserPool
  UserPoolClientId:
    Description: Cognito User Pool app client ID
    Value: !Ref FcajDMSUserPoolClient
  IdentityPoolId:
    Description: Cognito Identity Pool ID
    Value: !Ref FcajDMSIdentityPool
  DocumentStoreBucket:
    Description: S3 bucket that stores the uploaded files
    Value: !Ref FcajDMSDocumentStore
  • Outputs không thụt lề, cùng cấp với Resources. Ở phần 1.2, chúng ta dùng các giá trị này để tạo tệp amplify_outputs.json cho ứng dụng thay cho Amplify CLI.

CreateBucket

  1. Chạy câu lệnh sau tại thư mục fcajdms-sam để build project:
sam build

SAMBuild

  • Chạy câu lệnh sau để kiểm tra SAM template có hợp lệ không:
sam validate --lint

SAMValidate

  1. Chạy câu lệnh dưới đây để triển khai SAM project:
sam deploy --guided
  • Nhập các thông tin như sau:
Stack Name [fcajdms-sam]: fcajdms
AWS Region [ap-southeast-1]: ap-southeast-1
#Shows you resources changes to be deployed and require a 'Y' to initiate deploy
Confirm changes before deploy [y/N]: y
#SAM needs permission to be able to create roles to connect to the resources in your template
Allow SAM CLI IAM role creation [Y/n]: Y
#Preserves the state of previously provisioned resources when an operation fails
Disable rollback [y/N]: N
Save arguments to configuration file [Y/n]: Y
SAM configuration file [samconfig.toml]:
SAM configuration environment [default]:
  • Với hai câu hỏi cuối, ấn Enter để giữ giá trị mặc định.

SAMDeploy

  • Đợi một lúc để SAM tạo CloudFormation changeset
  • Nhập y khi được hỏi Deploy this changeset?

SAMDeploy

  • Kết quả sau khi CloudFormation hoàn thành, terminal hiển thị Successfully created/updated stack - fcajdms in ap-southeast-1 và các giá trị Outputs:

SAMDeploy

SAM lưu các lựa chọn của bạn vào tệp samconfig.toml trong thư mục fcajdms-sam. Từ lần sau, bạn chỉ cần chạy sam build và sam deploy, SAM sẽ dùng lại tên stack fcajdms và Region ap-southeast-1.

  1. Mở bảng điều khiển của CloudFormation
  • Chọn stack fcajdms
  • Chọn tab Resources. Bạn sẽ thấy các tài nguyên mà mình đã mô tả trong template.

CheckStack

  • Chọn tab Outputs để xem các giá trị UserPoolId, UserPoolClientId, IdentityPoolId và DocumentStoreBucket.

CheckStack

  1. Quay lại tab Resources, ấn vào Physical ID của FcajDMSUserPool để mở bảng điều khiển của user pool fcaj-dms-user-pool. Bạn sẽ thấy user pool dùng Email làm tùy chọn đăng nhập.

CheckUserPool

Bạn đã tạo xong các tài nguyên xác thực và lưu trữ với AWS SAM. Sang phần tiếp theo, chúng ta sẽ tạo S3 bucket host ứng dụng web và triển khai front-end.