При перезагрузке моей страницы AWS.config.credentials устанавливается равным нулю.Как сохранить их на разных страницах без необходимости каждый раз устанавливать новые учетные данные? - PullRequest
0 голосов
/ 29 мая 2019

Я использую AWS Cognito с аутентификацией Google для аутентификации пользователей на моем сайте.Учетные данные Cognito используются в нескольких местах на сайте для доступа к таблицам DynamoDB.Каждый раз, когда я перезагружаю страницу или открываю ее на новой вкладке - даже после полной аутентификации непосредственно перед этим - AWS.config.credentials отображается как ноль, когда я пытаюсь получить к ней доступ.Я теоретически мог бы каждый раз создавать новые учетные данные, но это создавало бы серьезную задержку для пользователя и не было бы идеальным для всех.

Проблема (и, надеюсь, решение), кажется, проистекает из директивы, показанной ниже.Я перепробовал кучу разных вещей, но что во всех случаях является непротиворечивым, так это когда я пытаюсь вызвать любой экземпляр AWS.config.credentials после перезагрузки, он показывает как ноль, и мое веб-приложение не работает.Вот код, который я использую:

Начальный тип аутентификации:

googleInit() {
    // google's function to prep user
    gapi.load('auth2', () => {
      this.auth2 = gapi.auth2.init({
        client_id: 'xxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com',
        cookiepolicy: 'single_host_origin',
        scope: 'profile email'
      });

      // calls this when sign-in button clicked
      this.attachSignin(document.getElementById('googleBtn'));
    });
  }

  // once a user is in the pop up login window
  attachSignin(element) {
    this.auth2.attachClickHandler(element, {},
      // this part is called if they successfully sign in
      (googleUser) => {

        // stores the user's profile
        let profile = googleUser.getBasicProfile();

        // stores user's authorization and changes the corresponding variable in dataService
        this.authResult = googleUser.getAuthResponse();
        Cookie.set('authResultAccessToken', this.authResult.access_token, 7);
        Cookie.set('authResultIdToken', this.authResult.id_token, 7);

        Cookie.set('googleAuthenticated', 'true', 7);

        this.queryAWS();

        // this is called if the sign in does not work or if they close the window or anything of that sort
      }, (error) => {
        alert(JSON.stringify(error, undefined, 2));
      });
  }

  queryAWS() {
    AWS.config.region = environment.AWS_REGION;
    AWS.config.credentials = new AWS.CognitoIdentityCredentials({
      IdentityPoolId: environment.AWS_IDENTITY_POOL_ID,
      Logins: { "accounts.google.com": this.authResult.id_token }
    });
    AWS.config.credentials.get(err => {
      if (!err) {
        Cookie.set('awsAuthenticated', 'true', 7);
        this.ngZone.run(() => { this._router.navigate(['/actions']) });
      }

      else {
        //alert("Your session has timed out.\nReauthenticate by refreshing and logging in again.");
        console.log("ERROR: " + err);
      }
    });
  }

Директива, вызываемая с каждым компонентом для проверки учетных данных:

ngOnInit() {
    this.refreshAWS()
  }

  refreshAWS() {

    if(AWS.config.credentials.expired){
      AWS.config.credentials.params.Logins['accounts.google.com'] = Cookie.get('authResultIdToken');
      AWS.config.credentials.refresh((err) => {
        if (err) {
          console.log(err);
        }
        else {
          console.log("TOKEN SUCCESSFULLY UPDATED");
        }
      });
    }
  }

Iпоследовательно получаю несколько ошибок:

При попытке доступа к DynamoDB:

CredentialsError: Missing credentials in config

При попытке доступа к AWS.config.credentials в директиве:

ERROR TypeError: Cannot set property 'fill in blank' of null

Ивот этот:

ERROR Error: Uncaught (in promise): CredentialsError: Missing credentials in config
CredentialsError: Missing credentials in config

У кого-нибудь есть идеи?Я видел кучу разных вещей, выполняющих поиск в Google, но ничего, что решило мои проблемы.

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