1

Пробовал добавить авторизацию c Facebook через Amazon Cognito в моем реакт приложении, конфиг моего Aws Amplify выглядит так:

Amplify.configure({
  Auth: {
    region: config.cognito.REGION,
    UserPoolId: config.cognito.USER_POOL_ID,
    ClientId: config.cognito.APP_CLIENT_ID
  }
});

Есть кнопка авторизации с Facebook, Facebook возврашает токен потом идет запрос в Cognito, вот код запроса:

async handleResponse(data) {
    const { email, accessToken: token, expiresIn } = data;
    const expires_at = expiresIn * 1000 + new Date().getTime();
    const user = { email };
    const identity_id = data.userID

    console.log(identity_id)
    this.setState({ isLoading: true });

    try {
      const response = await Auth.federatedSignIn(
        "facebook",
        { token, expires_at },
        user
      );
      this.setState({ isLoading: false });
      this.props.onLogin(response);
    } catch (e) {
      this.setState({ isLoading: false });
      this.handleError(e);
    }
  }

Но при авторизации выдается ошибка:

"No Cognito Federated Identity pool provided"

Cможете подсказать как решить эту проблему?

1 ответ 1

0

Первое, что я вижу, так это то, что в объекте user поле name - обязательно, в то время как email и phoneNumber опциональны. Добавьте имя, фейсбук его возвращает в ответе вместе с токеном. Ссылка на документацию: Federated with Auth0 и код из документации:

Auth.federatedSignIn(
    domain, // The Auth0 Domain,
    {
        token: idToken, // The id token from Auth0
        // expires_at means the timestamp when the token provided expires,
        // here we can derive it from the expiresIn parameter provided,
        // then convert its unit from second to millisecond, and add the current timestamp
        expires_at: exp * 1000 // the expiration timestamp
    },
    { 
        // the user object, you can put whatever property you get from the Auth0
        // for exmaple:
        name, // the user name
        email, // Optional, the email address
        phoneNumber, // Optional, the phone number
    } 
)

Далее Auth-конфигурация Amplify.configure. Судя по ошибке, ему не хватает проперти identityPoolId - отсюда и валится ошибка. Судя из документации Manual Setup , в Вашем случае оно обязательно:

// REQUIRED only for Federated Authentication - Amazon Cognito Identity Pool ID
identityPoolId: 'XX-XXXX-X:XXXXXXXX-XXXX-1234-abcd-1234567890ab',

Код из документации с описаниями:

Amplify.configure({
  Auth: {
    // REQUIRED only for Federated Authentication - Amazon Cognito Identity Pool ID
    identityPoolId: 'XX-XXXX-X:XXXXXXXX-XXXX-1234-abcd-1234567890ab',

    // REQUIRED - Amazon Cognito Region
    region: 'XX-XXXX-X',

    // OPTIONAL - Amazon Cognito Federated Identity Pool Region 
    // Required only if it's different from Amazon Cognito Region
    identityPoolRegion: 'XX-XXXX-X',

    // OPTIONAL - Amazon Cognito User Pool ID
    userPoolId: 'XX-XXXX-X_abcd1234',

    // OPTIONAL - Amazon Cognito Web Client ID (26-char alphanumeric string)
    userPoolWebClientId: 'a1b2c3d4e5f6g7h8i9j0k1l2m3',

    // OPTIONAL - Enforce user authentication prior to accessing AWS resources or not
    mandatorySignIn: false,

    // OPTIONAL - Configuration for cookie storage
    // Note: if the secure flag is set to true, then the cookie transmission requires a secure protocol
    cookieStorage: {
      // REQUIRED - Cookie domain (only required if cookieStorage is provided)
      domain: '.yourdomain.com',
      // OPTIONAL - Cookie path
      path: '/',
      // OPTIONAL - Cookie expiration in days
      expires: 365,
      // OPTIONAL - Cookie secure flag
      // Either true or false, indicating if the cookie transmission requires a secure protocol (https).
      secure: true
    },

    // OPTIONAL - customized storage object
    storage: new MyStorage(),

    // OPTIONAL - Manually set the authentication flow type. Default is 'USER_SRP_AUTH'
    authenticationFlowType: 'USER_PASSWORD_AUTH'
  }
});

Также, чтобы удостовериться в ошибке, достаточно найти исходный код из Credentials:

const { region, userPoolId, identityPoolId } = this._config;
if (!identityPoolId) {
    logger.debug('No Cognito Federated Identity pool provided');
    return Promise.reject('No Cognito Federated Identity pool provided');
}

Здесь из конфига как раз таки достается значение identityPoolId и проверяется, что оно было установлено.

1
  • спасибо за ответ) да нужен был параметр,для обычной авторизации через когнито не нужен был identityPoolId и поэтому я провтыкал этот момент),еще раз спасибо 19 сен 2019 в 3:19

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.