在 Angular 2 中实施 AWS-Cognito

Implementing AWS-Cognito in Angular 2

我目前正在尝试使用 Angular 和 AWS 构建网络应用程序。我的第一步是使用 AWS-Cognito 获得工作身份验证。但是我 运行 在导入和使用 AWS-Cognito SDK 时遇到了一些问题。

我已采取以下步骤:

我首先使用此 Angular 2 快速入门来设置我的应用程序:https://github.com/angular/quickstart 然后 运行 npm install

我的下一步是使用 npm install -g @angular/cli

安装 angular CLI

接下来我通过 运行ning 安装了 angular-cognito-identity-sdk:npm install --save amazon-cognito-identity-js

安装 SDK 后,我需要将 SDK 添加到我的组件中:

 console.log(AmazonCognitoIdentity);

         var authenticationData = {
            Username : 'username',
            Password : 'password',
        };
        var authenticationDetails = new AmazonCognitoIdentity.CognitoIdentityServiceProvider.AuthenticationDetails(authenticationData);
        var poolData = {
            UserPoolId : 'pool_id', // Your user pool id here
            ClientId : 'client_id' // Your client id here
        };
        var userPool = new AmazonCognitoIdentity.CognitoIdentityServiceProvider.CognitoUserPool(poolData);
        var userData = {
            Username : 'username',
            Pool : userPool
        };

但是当我 运行 代码时,我给出了以下错误:

TypeError: Cannot read property 'AuthenticationDetails' of undefined

我是不是漏掉了一步?在我的 Angular 应用程序中实施 Cognito SDK 的最佳方式是什么?

谢谢!

删除 CognitoIdentityServiceProvider。例如:

import * as AWSCognito from 'amazon-cognito-identity-js';

// Later on
const userPool = new AWSCognito.CognitoUserPool(awsCognitoSettings);
const authDetails = new AWSCognito.AuthenticationDetails({
  Username: this.state.username,
  Password: this.state.password
});
const cognitoUser = new AWSCognito.CognitoUser({
  Username: this.state.username,
  Pool: userPool
});
cognitoUser.authenticateUser(authDetails, {
  onSuccess: (result) => {
    console.log(`access token = ${result.getAccessToken().getJwtToken()}`);
  },
  onFailure: (err) => {
    alert(err);
  }
});

CognitoIdentityServiceProvideraws-sdk 的一部分,而不是 amazon-cognito-identity-js 库。

您不应将整个包导入为

import * as AWSCognito from 'amazon-cognito-identity-js';

这是个坏主意,因为你不需要在里面装一堆臃肿的东西。

而是仅导入您需要的内容。请参阅下面的示例。

import {AuthenticationDetails, CognitoUser, CognitoUserAttribute, CognitoUserPool} from 'amazon-cognito-identity-js';

const PoolData = {
  UserPoolId: 'us-east-1-xxxxx',
  ClientId: 'xxxxxxxxxxx'
};

const userPool = new CognitoUserPool(PoolData);

/////in export class....

/// Sign Up User
  signupUser(user: string, password: string, email: string) {
    const dataEmail = {
      Name: 'email',
      Value: email
    };
    const  emailAtt = [new CognitoUserAttribute(dataEmail)];

    userPool.signUp(user,  password, emailAtt, null, ((err, result) => {
      if (err) {
        console.log('There was an error ', err);
      } else {
        console.log('You have successfully signed up, please confirm your email ')
      }
    }))
  }

  /// Confirm User

    confirmUser(username: string, code: string) {
      const userData = {
        Username: username,
        Pool: userPool
      };

      const cognitoUser = new CognitoUser(userData);

      cognitoUser.confirmRegistration(code, true, (err, result) => {
        if (err) {
          console.log('There was an error -> ', err)
        } else {
          console.log('You have been confirmed ')
        }
      })
  }

  //// Sign in User

    signinUser(username: string, password: string) {
    const authData = {
      Username: username,
      Password: password
    };
    const authDetails = new AuthenticationDetails(authData);
    const userData = {
      Username: username,
      Pool: userPool
    };
    const cognitoUser = new CognitoUser(userData);

    cognitoUser.authenticateUser(authDetails, {
      onSuccess: (result) => {
        // console.log('You are now Logged in');
        this.isUser.next(true);
        this.router.navigate(['/'])
      },
      onFailure: (err) => {
        console.log('There was an error during login, please try again -> ', err)
      }
    })
  }

  /// Log User Out
    logoutUser() {
      userPool.getCurrentUser().signOut();
      this.router.navigate(['home'])
  }