Implementing AWS-Cognito in Angular 2

10,960

Solution 1

Remove the CognitoIdentityServiceProvider. For example:

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);
  }
});

The CognitoIdentityServiceProvider is part of the aws-sdk, not the amazon-cognito-identity-js library.

Solution 2

You should not import the whole package as

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

this is bad idea as you do not need a bunch of bloat in it.

Instead only import what you need. See my example below.

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'])
  }
Share:
10,960
okarlsson
Author by

okarlsson

Updated on June 10, 2022

Comments

  • okarlsson
    okarlsson almost 2 years

    I'm currently trying to get into building webapps with Angular and AWS. My first step is to get working authentication using AWS-Cognito. But i've run in to some problems with imporing and using the AWS-Cognito SDK.

    I have taken the following steps:

    I started by using this Angular 2 quickstart to set up my app: https://github.com/angular/quickstart and then ran npm install

    My next step was to install angular CLI with npm install -g @angular/cli

    Next I installed angular-cognito-identity-sdk by running: npm install --save amazon-cognito-identity-js

    After the SDK was installed I required the sdk into my component:

     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
            };
    

    But when I run the code Iäm given the following error:

    TypeError: Cannot read property 'AuthenticationDetails' of undefined

    Am I missing a step here? What is the best way to implement the Cognito SDK in my Angular app?

    Thank you!