简体   繁体   中英

AWS Cognito Login and Angular 2 routing

I'm not able to navigate to next page on success of AWS Cognito Login authentication from my angular 2 web app. Login is successful and I can see the token in console, but when I navigate on success of authentication I get below mentioned error. What is the mistake?

It throws me this error:

 EXCEPTION: Cannot read property 'navigate' of undefined

The code is as follows:

Component

authenticateUser(loginCredentials:any){

       var authenticationData = {
            Username : loginCredentials.username,
            Password : loginCredentials.password
        };
        //console.log("authenticationData..",authenticationData);
        var authenticationDetails = new AWSCognito.CognitoIdentityServiceProvider.AuthenticationDetails(authenticationData);
        console.log("authenticationDetails..",authenticationDetails);
        var poolData = {
            UserPoolId : "cognito user pool id ", // Your user pool id here
            ClientId : "cognito user pool client id" // Your client id here
        };
        //console.log("poolData..",poolData);
        var userPool = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(poolData);
        console.log("userPool..",userPool);
        var userData = {
            Username : loginCredentials.username,
            Pool : userPool
        };
        //console.log("userData..",userData);
        var cognitoUser = new AWSCognito.CognitoIdentityServiceProvider.CognitoUser(userData);
        console.log("cognitoUser..",cognitoUser);

        cognitoUser.authenticateUser(authenticationDetails, {
            onSuccess: function (result) {
                console.log('access token + ' + result.getAccessToken().getJwtToken());
                console.log('idToken + ' + result.idToken.jwtToken);

                if(result.getAccessToken().getJwtToken() != null){

                    this.router.navigate(['nextPage']);

                }


            },

            onFailure: function(err) {
                console.log('error : ' + err);
                alert(err);
            },


        })

   }

Your best bet is to turn it into a promise instead using callbacks and handle your logic inside "then and catch". This would allow you to better control your code and re-use it else where. I have converted your code to a promise and added one of my code that used be callback before and I converted to a promise for you to compare. A lot of engineers use promises or observables instead callbacks nightmare.

BELOW, YOUR CODE USING PROMISES.

 cognitoUser.authenticateUser(authenticationDetails).promise().then(result => { console.log('access token + ' + result.getAccessToken().getJwtToken()); console.log('idToken + ' + result.idToken.jwtToken); if (result.getAccessToken().getJwtToken() !== null) { this.router.navigate(['nextPage']); } }).catch(err => { console.log('error : ' + err); alert(err); }) 

BELOW, MY CODE USING CALLBACKS AND THEN USING PROMISES.

 confirmSMSLogin(data: string) { AWS.config.region = 'us-east-1'; AWS.config.credentials = new AWS.CognitoIdentityCredentials({ IdentityPoolId: 'us-east-1:xxx-xxxx.etc', }); const cognitoIdentityServiceProvider = new AWS.CognitoIdentityServiceProvider(); const params = { ChallengeName: 'CUSTOM_CHALLENGE', ClientId: 'asdf1234...etc', ChallengeResponses: { USERNAME: this.userModelService.LoginUserModelService[0].username, ANSWER: data }, Session: this.userModelService.LoginUserModelService[0].session }; // DISABLED THIS FUNCTION WITH CALLBACKS WHICH LIMITED THE CONTROL OVER THE FUNCTION. // cognitoIdentityServiceProvider.respondToAuthChallenge(params, function(err, data) { // if (err) { // console.log(err, err.stack); // } else { // successful response // console.log('Successful Authentication'); // AWS.config.credentials = new AWS.CognitoIdentityCredentials({ // IdentityPoolId: 'us-east-1:asdf1234..etc', // Logins: {'cognito-idp.us-east-1.amazonaws.com/us-east-asdf..etc': // data['AuthenticationResult']['IdToken']} // }); // } // }) // Changed aws function callbacks to promise to better control of the flow. return cognitoIdentityServiceProvider.respondToAuthChallenge(params).promise().then((data) => { console.log('Success to Log in') AWS.config.credentials = new AWS.CognitoIdentityCredentials({ IdentityPoolId: 'us-east-1:asdf1234...etc', Logins: { 'cognito-idp.us-east-1.amazonaws.com/us-east-1asdf..etc': data['AuthenticationResult']['IdToken'] } }); this.userModelService.UserSignedInModelService.push(this.jwtHelper1.decodeToken(data.AuthenticationResult.IdToken)) this.router.navigate(['']) }).catch((err) => { if (err) { console.log('has an error', err) } }) } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM