AWS Cognito SMS 2FA: неверный код или состояние авторизации для пользователя - PullRequest
0 голосов
/ 09 февраля 2019

Для воспроизведения я

  1. ввожу адрес электронной почты подтвержденного пользователя и
  2. пароль подтвержденного пользователя
  3. , принимая ошибку: Missing required parameter SMS_MFA_CODE, потому что this.state.code - это пустая строка, когда она передается в cognitoUser.sendMFACode(context.state.code, this), context - это значение, переданное как this через signIn()
  4. , введя код, отправленный с помощью SMS
  5. вызывает ту же самую функцию cognitoUser.authenticateUser(), на этот раз с this.state.code, заполненной как более чем пустая строка.

У меня та же ошибка при очень разных обстоятельствах, что и у этого парня: Многофакторная аутентификация SMS AWS Cognito возвращает неверный код или состояние авторизации

Я подписанформат из случая 23 в следующем руководстве по использованию npm: https://www.npmjs.com/package/amazon-cognito-identity-js (из) https://docs.aws.amazon.com/cognito/latest/developerguide/using-amazon-cognito-identity-user-pools-javascript-example-authenticating-admin-created-user.html?shortFooter=true

import React, { Component } from 'react'
import { BrowserRouter as Router, Route, Link, Redirect } from "react-router-dom";
import * as AWS from 'aws-sdk/global';
import { AuthenticationDetails, CognitoUserPool, CognitoUserAttribute, CognitoUser } from 'amazon-cognito-identity-js'; 
import PropTypes from 'prop-types'

import '../../stylesheets/Authentication.css'

export default class CognitoIdentitySignIn extends Component {

    constructor(props) {
        super(props);
        this.state = {
            password: "",
            email: "",
            code: "",
            submissionAnnouncement: "",
            readyForCode: false
        };
        this.handleChangeEmail = this.handleChangeEmail.bind(this);
        this.handleChangePassword = this.handleChangePassword.bind(this);
        this.handleChangeCode = this.handleChangeCode.bind(this);
        this.submitCredentials = this.submitCredentials.bind(this);
    }

    handleChangeEmail(event) {
        this.setState({email: event.target.value});
    }
    handleChangePassword(event) {
        this.setState({password: event.target.value});
    }
    handleChangeCode(event) {
        this.setState({code: event.target.value});
    }

    submitCredentials(event) {
        this.signIn(this, this.state.email, this.state.password);
    }

    signIn(context, email, password) {
        var authenticationData = {
            Username : email,
            Password : password
        };
        var authenticationDetails = new AuthenticationDetails(authenticationData);

        var poolData = {
            UserPoolId: 'us-west-2_xxxxxxxx',
            ClientId: 'XXXXXXXXXXXXXXXXXXXXXX',
        };

        var userPool = new CognitoUserPool(poolData);
        var userData = {
            Username : email,
            Pool : userPool
        };
        var cognitoUser = new CognitoUser(userData);
        console.log(authenticationDetails);
        console.log(cognitoUser);
        cognitoUser.authenticateUser(authenticationDetails, {
            onSuccess: function (session) {
                var accessToken = session.getAccessToken().getJwtToken();

                AWS.config.region = 'us-west-2';
                // Change the key below according to the specific region your user pool is in.
                var Logins = {}
                Logins[`cognito-idp.${AWS.config.region}.amazonaws.com/${poolData.UserPoolId}`] = accessToken;
                AWS.config.credentials = new AWS.CognitoIdentityCredentials({
                    IdentityPoolId : 'us-west-2:XXXXXXX-XXXX-XXXXXXXX', 
                    Logins : Logins
                });

                //refreshes credentials using AWS.CognitoIdentity.getCredentialsForIdentity()
                AWS.config.credentials.refresh((error) => {
                    if (error) {
                        alert('onSuccess:\n' + JSON.stringify(error));
                        context.setState({
                            submissionAnnouncement: error.message,
                            readyForCode: false
                        })
                        console.error(error);
                    } else {
                        // Instantiate aws sdk service objects now that the credentials have been updated.
                        // example: var s3 = new AWS.S3();
                        context.setState({
                            submissionAnnouncement: "SUCCESS",
                            readyForCode: true
                        });
                        console.log(session);
                        var cognitoUser = session.user;
                    }
                });
            },

            onFailure: function(err) {
                alert('onFailure:\n' + JSON.stringify(err));
                if (err.message === "Missing required parameter SMS_MFA_CODE") {
                    context.setState({
                        submissionAnnouncement: err.message,
                        readyForCode: true
                    })
                } else {
                    context.setState({
                        submissionAnnouncement: err.message
                    })
                }

            },

            mfaRequired: function(codeDeliveryDetails) {
                // MFA is required to complete user authentication.
                // Get the code from user and call
                console.log(codeDeliveryDetails)
                cognitoUser.sendMFACode(context.state.code, this)
            }
            // ,

            // newPasswordRequired: function(userAttributes, requiredAttributes) {
            // not actually doing anything with this
            // }

        });
    }

    render() {
        return (
            <div className='SignIn'>
                <div className='sign-in-input-box'>
                    <label> 
                        <p>Email</p>
                        <input className='sign-in-email-input' value={this.state.email} onChange={this.handleChangeEmail} type='text' />
                    </label>
                </div>
                <div className='sign-in-input-box'>
                    <label>
                        <p>Password</p>
                        <input className='sign-in-password-input' value={this.state.password} onChange={this.handleChangePassword} type='text' />
                    </label>
                </div>
                <div className="click-text" onClick={this.submitCredentials}> SIGN IN </div>
                {(this.state.submissionAnnouncement === "" ? null : <div><span>{this.state.submissionAnnouncement}</span></div>)}
                {(this.state.readyForCode) ?  
                    <div className='sign-in-input-box'>
                        <label>
                            <p>Password</p>
                            <input className='sign-in-code-input' value={this.state.code} onChange={this.handleChangeCode} type='text' />
                        </label>
                    </div>:
                 null}
            </div>
        )
    }
}

CognitoIdentitySignIn.propTypes = {

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