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.
sam init
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.

cd fcajdms-sam
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:

# 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:
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.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.

# 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
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 đó.
# 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.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.

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

sam build

sam validate --lint

sam deploy --guided
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]:

y khi được hỏi Deploy this changeset?

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.



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.