Как настроить Cognito Auth, чтобы просто иметь электронную почту + пароль, используя Serverless? - PullRequest
0 голосов
/ 09 июня 2019

Я использую Serverless для создания пула пользователей Cognito, но в настоящее время имя пользователя и номер телефона являются обязательными полями, которые мне не нужны для моего приложения. Я использую Cognito с приложением реагирования, которое реализует аутентификацию с

import { withAuthenticator } from 'aws-amplify-react';

...

export default withAuthenticator(App);

Без сервера выглядит так:

    CognitoUserPool:
      Type: AWS::Cognito::UserPool
      Properties:
        UserPoolName: ${self:service}_user_pool
        MfaConfiguration: OFF
        UsernameAttributes:
          - email
        Policies:
          PasswordPolicy:
            MinimumLength: 8
            RequireLowercase: False
            RequireNumbers: False
            RequireSymbols: False
            RequireUppercase: False

    CognitoUserPoolClient:
      Type: AWS::Cognito::UserPoolClient
      Properties:
        ClientName: ${self:service}_client
        UserPoolId:
          Ref: CognitoUserPool   

    ApiGatewayAuthorizer: 
      Type: AWS::ApiGateway::Authorizer
      Properties: 
        Name: CognitoUserPool
        Type: COGNITO_USER_POOLS
        IdentitySource: method.request.header.Authorization
        RestApiId: 
          Ref: ApiGatewayRestApi
        ProviderARNs: 
          - Fn::GetAtt:
              - CognitoUserPool
              - Arn

    CognitoIdentityPool:
      Type: AWS::Cognito::IdentityPool
      Properties:
        IdentityPoolName: ${self:service}_identity_pool
        AllowUnauthenticatedIdentities: false
        CognitoIdentityProviders:
          - ClientId:
              Ref: CognitoUserPoolClient
            ProviderName:
              Fn::GetAtt: [CognitoUserPool, ProviderName]

    CognitoIdentityPoolRoles:
      Type: AWS::Cognito::IdentityPoolRoleAttachment
      Properties:
        IdentityPoolId:
          Ref: CognitoIdentityPool
        Roles:
          authenticated:
            Fn::GetAtt: [CognitoAuthRole, Arn]
          unauthenticated:
            Fn::GetAtt: [CognitoUnauthRole, Arn]

    CognitoAuthRole:
      Type: AWS::IAM::Role
      Properties:
        RoleName: appAuthRole
        Path: /
        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: CognitoIdentityPool
                "ForAnyValue:StringLike":
                  "cognito-identity.amazonaws.com:amr": authenticated
        Policies:
          - PolicyName: "CognitoAuthorizedPolicy"
            PolicyDocument:
              Version: "2012-10-17"
              Statement:
                - Effect: "Allow"
                  Action:
                    - "mobileanalytics:PutEvents"
                    - "cognito-sync:*"
                    - "cognito-identity:*"
                  Resource: "*"
                - Effect: "Allow"
                  Action:
                    - "execute-api:Invoke"
                  Resource: "*"
    CognitoUnauthRole:
      Type: AWS::IAM::Role
      Properties:
        RoleName: appUnauthRole
        Path: /
        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: CognitoIdentityPool
                "ForAnyValue:StringLike":
                  "cognito-identity.amazonaws.com:amr": unauthenticated
        Policies:
          - PolicyName: "CognitoUnauthorizedPolicy"
            PolicyDocument:
              Version: "2012-10-17"
              Statement:
                - Effect: "Allow"
                  Action:
                    - "mobileanalytics:PutEvents"
                    - "cognito-sync:*"
                    - "cognito-identity:*"
                  Resource: "*"

Я сейчас искал здесь какую-то опцию установки, но не нашел что-то, чтобы отключить телефон и имя пользователя:

https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cognito-userpool.html

Возможно ли решить эту проблему с помощью еще одной конфигурации без сервера или мне, возможно, нужно изменить реализацию реакции?

Можно настроить поле для входа в систему, как это, но без правильной конфигурации он запрашивает пропущенное имя пользователя, если вы просто «скрываете» поля в форме входа в систему

const signUpConfig = {
  hideAllDefaults: true,
  signUpFields: [
    {
      label: 'Email',
      key: 'email',
      required: true,
      placeholder: 'Email',
      type: 'email',
      displayOrder: 1
    },
    {
      label: 'Password',
      key: 'password',
      required: true,
      placeholder: 'Password',
      type: 'password',
      displayOrder: 2
    }
  ]
};

export default withAuthenticator(App, { signUpConfig });
...