При входе пользователя появляется ошибка «Неверное имя пользователя или пароль». - PullRequest
0 голосов
/ 14 января 2019

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

Самое странное, что он работает нормально локально (localhost:5000). Я могу создать учетные записи и войти без всякой драмы, но когда я пытаюсь войти на моем сайте https://example.com (размещенный на S3), это выдает вышеуказанную ошибку. Похоже, что пользователи, на самом деле, тоже создаются в Cognito, если я зарегистрируюсь - это работает, но входы в систему не работают нигде, кроме как локально.

Я проверил дважды, трижды каждый параметр, переменную env, пересоздал пул пользователей и т. Д.

Error

Это неоднозначная ошибка, возникающая при попытке войти в систему:

{
  __type: "NotAuthorizedException", 
  message: "Incorrect username or password."
}

Лямбда, запускаемая до регистрации

Я подтверждаю пользователей, прежде чем они зарегистрируются через лямбду:

import {INTERNAL_SERVER_ERROR} from 'http-status-codes';

export async function validateHumanViaSns(
    event: CognitoUserPoolTriggerEvent,
    context: Context,
    callback: Callback
): Promise<CognitoUserPoolTriggerHandler> {
    try {
        event.response.autoConfirmUser = true;

        callback(null, event);

        return;
    } catch (error) {
        console.error(error);
        callback(null, new Response(INTERNAL_SERVER_ERROR, {message: 'Something went wrong'}));

        return;
    }
}

package.json

Мой клиент использует новейшую библиотеку ampify-js .

dependencies: {
  "amplify": "1.1.19" // broken since 1.1.18
}

Шаблон CloudFormation Cognito

UserPool:
  Type: 'AWS::Cognito::UserPool'
  Properties:
    UserPoolName: myapp-${self:provider.stage}-user-pool
    SmsVerificationMessage: 'Your verification code is {####}.'
    AutoVerifiedAttributes:
      - email
    MfaConfiguration: 'OFF'
    EmailVerificationSubject: 'Your MyApp verification code'
    EmailVerificationMessage: 'Your MyApp verification code is {####}.'
    SmsAuthenticationMessage: 'Your MyApp authentication code is {####}.'
    Schema:
      - Name: name
        AttributeDataType: String
        Mutable: true
        Required: false
      - Name: email
        AttributeDataType: String
        Mutable: false
        Required: false
      - Name: phone_number
        AttributeDataType: String
        Mutable: true
        Required: false
    Policies:
      PasswordPolicy:
        RequireLowercase: true
        RequireSymbols: false
        RequireNumbers: true
        MinimumLength: 8
        RequireUppercase: true
    AdminCreateUserConfig:
      InviteMessageTemplate:
        EmailMessage: 'Your MyApp username is {username} and temporary password is {####}.'
        EmailSubject: 'Your temporary MyApp password'
        SMSMessage: 'Your MyApp username is {username} and temporary password is {####}.'
      UnusedAccountValidityDays: 7
      AllowAdminCreateUserOnly: false

# Creates a User Pool Client to be used by the identity pool
UserPoolClient:
  Type: 'AWS::Cognito::UserPoolClient'
  Properties:
    ClientName: myapp-${self:provider.stage}-web-client
    GenerateSecret: false
    UserPoolId:
      Ref: UserPool

# Creates a federeated Identity pool
IdentityPool:
  Type: 'AWS::Cognito::IdentityPool'
  Properties:
    IdentityPoolName: MyApp{self:provider.stage}Identity
    AllowUnauthenticatedIdentities: true
    CognitoIdentityProviders:
      - ClientId:
          Ref: UserPoolClient
        ProviderName:
          'Fn::GetAtt': [ UserPool, ProviderName ]

# Create a role for unauthorized access to AWS resources. Very limited access. Only allows users in the previously created Identity Pool
CognitoUnAuthorizedRole:
  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: IdentityPool
            'ForAnyValue:StringLike':
              'cognito-identity.amazonaws.com :amr': unauthenticated
    Policies:
      - PolicyName: 'CognitoUnauthorizedPolicy'
        PolicyDocument:
          Version: '2012-10-17'
          Statement:
            - Effect: 'Allow'
              Action:
                - 'mobileanalytics:PutEvents'
                - 'cognito-sync:*'
              Resource: '*'

# Create a role for authorized access to AWS resources. Control what your user can access. This example only allows Lambda invokation
# Only allows users in the previously created Identity Pool
CognitoAuthorizedRole:
  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: IdentityPool
            '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:
                - 'lambda:InvokeFunction'
              Resource: '*'

# Assigns the roles to the Identity Pool
IdentityPoolRoleMapping:
  Type: 'AWS::Cognito::IdentityPoolRoleAttachment'
  Properties:
    IdentityPoolId:
      Ref: IdentityPool
    Roles:
      authenticated:
        'Fn::GetAtt': [ CognitoAuthorizedRole, Arn ]
      unauthenticated:
        'Fn::GetAtt': [ CognitoUnAuthorizedRole, Arn ]

У кого-нибудь есть идеи относительно того, почему эта конкретная ошибка выдается (я думаю, что она вводит в заблуждение) или, что еще лучше, как это исправить?

1 Ответ

0 голосов
/ 17 февраля 2019

Это было исправлено в журнале ошибок AWS Amplify Github, больше контекста здесь .

Везде, где вы импортируете функцию амплификации, вам необходимо предварительно импортировать crypto-js зависимость из-за проблемы компиляции Typescript в библиотеке ampify-js:

import 'crypto-js/lib-typedarrays'; // add this line
import Amplify, {Auth} from 'aws-amplify';

Похоже, что это будет постоянное исправление в будущем запросе на получение, поэтому в зависимости от того, когда вы окажетесь здесь, попробуйте сначала обновить пакет aws-amplify до чего-то> 1.1.19, чтобы увидеть, если сначала это было исправлено в основном пакете.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...