【AWS】CloudformationでCognito作成

1. 使用するサービス

(AWS)

  • Cloudformation
  • Cognito

2.概要

Cloudformationを使用してログイン後にトークンを渡し、以降のLambdaとのやり取りをトークンの認証を用いて実装するようなCognitoを作成します。
大体デフォルト設定ですが、注意点コメント入れておきます。

  UserPool:
    Type: "AWS::Cognito::UserPool"
    Properties:
      UserPoolName: !Sub "${Project}-${Stage}-UserPool"
      AdminCreateUserConfig:
          AllowAdminCreateUserOnly: false
          UnusedAccountValidityDays: 7
      AliasAttributes:
        - email
      AutoVerifiedAttributes:
        - email
      UsernameConfiguration:
        CaseSensitive: True
      EmailVerificationMessage: "Your verification code is {####}."
      EmailVerificationSubject: "Your verification code"
      #ログイン後に処理をしたい場合はここにLambda追加
      LambdaConfig:
        PostConfirmation: !GetAtt PostConfirmationFunction.Arn
      MfaConfiguration: 'OFF'
      Policies:
        PasswordPolicy:
          MinimumLength: 8
          RequireLowercase: true
          RequireNumbers: true
          RequireSymbols: true
          RequireUppercase: true
      Schema:
        - AttributeDataType: "String"
          DeveloperOnlyAttribute: false
          Mutable: true
          Name: "email"
          StringAttributeConstraints:
            MaxLength: "2048"
            MinLength: "0"
          Required: true
      SmsAuthenticationMessage:  "Your authentication code is {####}."
      SmsVerificationMessage: "Your verification code is {####}."
  
  
  UserPoolClient:
    Type: AWS::Cognito::UserPoolClient
    Properties:
      ClientName: !Sub "${Project}-${Stage}-UserPollClient"
      
      #トークン承認の場合は、基本的にimplicitとopenidで大丈夫なはず
   AllowedOAuthFlows:
        - implicit
      AllowedOAuthScopes:
        - openid
      AllowedOAuthFlowsUserPoolClient: true
      GenerateSecret: false
   #ここをCOGNITOにしないとログイン画面でエラーになる
   #必要に応じてFacebookなどプロバイダー追加
      SupportedIdentityProviders:
        - COGNITO
      #ログイン後の画面URLを記載
      CallbackURLs:
       - !Sub "https://${S3DomainName}-${Project}-${Stage}.${HostedZoneName}/index.html"
      #ログアウト後の画面URLを記載
      LogoutURLs:
       - !Sub "https://${S3DomainName}-${Project}-${Stage}.${HostedZoneName}/index.html"
      UserPoolId:
        Ref: UserPool
  
  # Not use custom domain because of this https://github.com/aws-cloudformation/aws-cloudformation-coverage-roadmap/issues/241      
  UserPoolClientDomain:    
    Type: AWS::Cognito::UserPoolDomain
    Properties: 
      Domain: !Sub "${SinginDomain}-${Project}-${Stage}"
      UserPoolId: !Ref UserPool

ログイン画面のドメインはデフォルトの使用します。CLoudformationで一気に独自ドメインまで作成するのは現時点では簡単に実装できません。恐らく、ドメインの紐付けか何かに時間がかかる為?
GUIだと確かに時間はかかるけど簡単にできます。