Deploy Cognito And S3 Bucket

In this section, we will use AWS SAM to create the Cognito User Pool, User Pool Client, Identity Pool and the S3 bucket that stores the files users upload. These are the resources that Amplify Gen 2 created for you in workshop 134.

You need to install SAM CLI version 1.146.0 or later and configure credentials with the aws configure command (region ap-southeast-1) before doing this part.

  1. Run the following command to initialize a SAM project:
sam init
  • Select the following information:
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

If SAM CLI suggests a runtime other than python3.14, enter N, then select the python3.14 runtime and the Zip package type.

SAMInit

  1. Open the fcajdms-sam folder in your editor:
cd fcajdms-sam
  • Delete the hello_world, events and tests folders because we do not use the sample function.
  • Open the template.yaml file and replace its whole content with the code below:
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:
  • The Globals section declares the common settings of every Lambda function in the template: the Python 3.14 runtime (same as the functions of workshop 133), a 10-second timeout and the x86_64 architecture.

SAMInit

  1. Copy the following code below the Resources: line:
  # 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

This code block initializes the following resources:

  • A User Pool: users sign up and sign in with their email (UsernameAttributes), and the email is verified with a code sent automatically (AutoVerifiedAttributes). The password policy requires at least 8 characters with uppercase, lowercase, number and special characters, the same as the Amplify Gen 2 default policy and the password check of the application.
  • A User Pool Client: the web application uses this client to sign in with the SRP protocol. The client has no client secret because the application runs in the browser.
  • An Identity Pool: provides temporary AWS credentials so that the application can upload files to and download files from the S3 bucket.

The User Pool must use email as the username so that the application can call signUp with an email, as in workshop 134. The Display name is saved in the standard preferred_username attribute. The app client does not restrict write attributes, so the application can write and update this attribute.

CreateUserPool

  1. Next, we will create the roles for guests and signed-in users, then attach these two roles to the Identity Pool. Add the following code to the bottom of the file:
  # 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: the role for guests, without access to any AWS resource.
  • CognitoAuthenticatedRole: the role for signed-in users, with the same access as the protected/{entity_id}/* rule of workshop 134: every signed-in user can read the files in the protected/ folder, but only the owner can write and delete files in their own protected/{Identity ID}/ folder.
  • ${!cognito-identity.amazonaws.com:sub}: the ! tells !Sub to keep this variable as is in the policy. When a user sends a request, IAM replaces the variable with the Identity ID of that user.
  • IdentityPoolRoleAttachment: attaches the two roles above to the Identity Pool.

CreateUserPool

  1. Next, we will create the S3 bucket that stores the files users upload. Add the following code to the bottom of the file:
  # 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: creates the bucket in the Account Regional namespace, the same as the Account Regional namespace (recommended) option you chose when creating the bucket in workshop 135.
  • CorsConfiguration: allows the web application running in the browser to upload, download and delete files in the bucket.

With the Account Regional namespace, the bucket name only needs to be unique within your AWS account and Region, and it must end with a suffix that contains the account ID and Region. That is why the template builds the bucket name with ${AWS::AccountId} and ${AWS::Region}, for example: fcajdmsstore-<ACCOUNT_ID>-ap-southeast-1-an. You do not need to change the bucket name, and you will read the full name in the Outputs tab of the stack. The BucketNamespace property needs a recent SAM CLI version; if sam validate --lint reports BucketNamespace as an invalid property, update SAM CLI.

CreateBucket

  1. Add the Outputs section to the bottom of the file to show the values that the web application needs:
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 has no indentation, at the same level as Resources. In part 1.2, we use these values to create the amplify_outputs.json file for the application instead of the Amplify CLI.

CreateBucket

  1. Run the following command in the fcajdms-sam folder to build the project:
sam build

SAMBuild

  • Run the following command to check if the SAM template is valid:
sam validate --lint

SAMValidate

  1. Run the command below to deploy the SAM project:
sam deploy --guided
  • Enter the following information:
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]:
  • For the last two questions, press Enter to keep the default values.

SAMDeploy

  • Wait a while for SAM to create the CloudFormation changeset
  • Enter y when asked Deploy this changeset?

SAMDeploy

  • When CloudFormation completes, the terminal shows Successfully created/updated stack - fcajdms in ap-southeast-1 and the Outputs values:

SAMDeploy

SAM saves your choices in the samconfig.toml file in the fcajdms-sam folder. From now on, you only need to run sam build and sam deploy; SAM reuses the fcajdms stack name and the ap-southeast-1 Region.

  1. Open the CloudFormation console
  • Select the fcajdms stack
  • Select the Resources tab. You will see the resources described in the template.

CheckStack

  • Select the Outputs tab to see the UserPoolId, UserPoolClientId, IdentityPoolId and DocumentStoreBucket values.

CheckStack

  1. Go back to the Resources tab and click the Physical ID of FcajDMSUserPool to open the console of the fcaj-dms-user-pool user pool. You will see that the user pool uses Email as the sign-in option.

CheckUserPool

You have created the authentication and storage resources with AWS SAM. In the next part, we will create the S3 bucket that hosts the web application and deploy the front-end.