Разрешить CognitoUser использовать AWS Lambda - PullRequest
2 голосов
/ 24 февраля 2020

Моя проблема:

Использование AWS SDK для вызова AWS Лямбда выдает мне ошибки конфигурации

CredentialsError: Missing credentials in config

Что я нашел:

Вход в систему пользователь впервые инициирует правильные настройки конфигурации, но он теряется при обновлении страницы sh.

Цель:

Использование ... приведенного ниже кода, даже после обновления пользователя страница

 lambda.invoke(params, function(err, data) {
      if (err) {
        // console.log(err, err.stack);
      } else {
        console.log(data);
      } // successful response
    });

Ниже показано, как я в первый раз регистрирую пользователя с помощью cognitoUserPool

Шаг 1: захват имени пользователя и пароля

trySignIn(username, password) {
        console.log("trying to sign in");
        var authenticationData = {
          Username: username,
          Password: password
        };

Шаг 2, использование нового AmazonCognitoIdentity .AuthenticationDetails

        var authenticationDetails = new AmazonCognitoIdentity.AuthenticationDetails(
          authenticationData
        );

Шаг 3 настроить UserPool с UserData

        var poolData = {
          UserPoolId: "myPoolId", // Your user pool id here
          ClientId: "myPoolClient" // Your client id here
        };

        var userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);

        var userData = {
          Username: username,
          Pool: userPool
        };

Шаг 4 Получить объект CognitoUser

        var cognitoUser = new AmazonCognitoIdentity.CognitoUser(userData);
        cognitoUser.authenticateUser(authenticationDetails, {
          onSuccess: function(result) {
            var accessToken = result.getAccessToken().getJwtToken();

            console.log(result);

            //POTENTIAL: Region needs to be set if not already set previously elsewhere.
            //AWS.config.region = "us-east-1";  //moved to component did mount

            AWS.config.credentials = new AWS.CognitoIdentityCredentials({
              IdentityPoolId: "myidentiy-id-pool-id", // your identity pool id here
              Logins: {
                // Change the key below according to the specific region your user pool is in.
                "cognito-idp.us-east-1.amazonaws.com/us-east-1": result
                  .getIdToken()
                  .getJwtToken()
              }
            });

Шаг 5 Здесь мы можем настроить AWS SDK для использования таких вещей, как AWS .Lambda / AWS .S3

            //refreshes credentials using AWS.CognitoIdentity.getCredentialsForIdentity()
            AWS.config.credentials.refresh(error => {
              if (error) {
                console.error(error);
              } else {
                // Instantiate aws sdk service objects now that the credentials have been updated.
                // example: var s3 = new AWS.S3();
                console.log("Successfully logged!");
              }
            });

Проблема - событие после сохранения объекта UserObject в хранилище. Я теряю информацию AWS .config и не могу перенастроить это без запроса пароля пользователя каждый раз

            var user = { username: username };
            localStorage.setItem("cognitoUser", JSON.stringify(user));
            console.log(cognitoUser);
            console.log(user);

Вопрос ?

Как настроить AWS .config, имеющий доступ только к объекту cognitoUser из хранилища, но не к паролю пользователя

Обновление: <- Не работает </h1> Я думаю, что возможно сохранить переменную, созданную на шаге 5, в хранилище. var lambdaTry = new AWS.Lambda localStorage.setItem("lambdaTry", JSON.stringify(lambdaTry));

...