简体   繁体   中英

Getting Cognito User custom attributes with amazon-cognito-identity.min.js

I have a Cognito user authentication using amazon-cognito-identity.min.js. Login, getting jwt token works just fine. Now I would like to get user custom attributes, but can't get it working - I am getting error "User is not authorized". I found that I should use cognitoUser.getUserAttributes(), but this seems it is not working.

var userPoolId = 'eu-west-1_xxxxxxxx'
var clientId = 'yyyyyyyyyyyyyyyyyyyyyyyyyy'

var poolData = { UserPoolId : userPoolId,
ClientId : clientId
};

var userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);

function login(){
    var username = $('#username').val();
    var authenticationData = {
        Username: username,
        Password: $('#password').val()
    };

    console.log("Username:",username, "Password:",$('#password').val())

    var authenticationDetails = new AmazonCognitoIdentity.AuthenticationDetails(authenticationData);

    var userData = {
        Username : username,
        Pool : userPool
    };
    var cognitoUser = new AmazonCognitoIdentity.CognitoUser(userData);
    console.log(cognitoUser);

    cognitoUser.authenticateUser(authenticationDetails, {
        onSuccess: function (result) {
            console.log(result)
            var accessToken = result.getAccessToken().getJwtToken();
           

            cognitoUser.getUserAttributes(function(err, result) {
                if (err) {
                    alert(err.message || JSON.stringify(err));
                    return;
                }
                custom_attribute = result[4].getValue();
                console.log(custom_attribute);
                return custom_attribute;
               
        });

            localStorage;
            localStorage.setItem("accessToken", accessToken);
            localStorage.setItem("custom_attribute", custom_attribute);            
            window.location = './index.html';
        },

        onFailure: function(err) {
            console.log("failed to authenticate");
            console.log(JSON.stringify(err))
            alert("Failed to Log in.\nPlease check your credentials.")
        },
    });
}

function checkLogin(redirectOnRec, redirectOnUnrec){

    var cognitoUser = userPool.getCurrentUser();
    if (cognitoUser != null) {
        if (redirectOnRec) {
            window.location = './index.html';
        } else {
            $("#body").css({'visibility':'visible'});           
        }
    } else {
        if (redirectOnUnrec) {
            window.location = './signin.html'
        } 
    }
}

function logOut() {
    
    var cognitoUser = userPool.getCurrentUser();
    console.log(cognitoUser, "signing out...")
    cognitoUser.signOut();
    window.location = './signin.html';
}

var idKey = 'cognito-idp.ap-southeast-2.amazonaws.com/' + userPoolId
var cognitoUser = userPool.getCurrentUser();

Here is my index.html part where we trigger it:

    <script type="text/javascript">
      $(function () {        
        checkLogin(false, true)
      })
      window.onload = function () {
        checkLogin(false, true)
        localStorage;
        var token = localStorage.getItem("accessToken");
      }
    </script>
   

Can you suggest how I should do it?

It seems you either need to specify the username you're trying to obtain custom attributes from:

cognitoUser.username = '<username>';

or, alternatively you'll need to loop over the users in the pool to find out their user and dynamically assign and getUserAttributes :

// List the users in the user pool
userPool.listUsers((err, users) => {
  if (err) {
    // Handle error
  } else {
    // Loop through the list of users
    users.forEach(user => {
      // Get the user's custom attributes
      user.getUserAttributes((err, attributes) => {
        if (err) {
          // Handle error
        } else {
          // Print the user's custom attributes
          console.log(attributes);
        }
      });
    });
  }
});

so I figure it out by separating getting attributes from login.

I have added following function:

function login(){
var username = $('#username').val();
var authenticationData = {
    Username: username,
    Password: $('#password').val()
};

console.log("Username:",username, "Password:",$('#password').val())

var authenticationDetails = new AmazonCognitoIdentity.AuthenticationDetails(authenticationData);

var userData = {
    Username : username,
    Pool : userPool
};
var cognitoUser = new AmazonCognitoIdentity.CognitoUser(userData);
console.log(cognitoUser);

cognitoUser.authenticateUser(authenticationDetails, {
    onSuccess: function (result) {
        console.log(result)
        var accessToken = result.getAccessToken().getJwtToken();
        localStorage;
        localStorage.setItem("accessToken", accessToken);                 
        window.location = './index.html';
    },

    onFailure: function(err) {
        console.log("failed to authenticate");
        console.log(JSON.stringify(err))
        alert("Failed to Log in.\nPlease check your credentials.")
    },
});}


function getUserAttributes(){
var cognitoUser = userPool.getCurrentUser();
let machine_id = '';
if (cognitoUser != null) {
    cognitoUser.getSession(function (err, session) {

        cognitoUser.getUserAttributes(function(err, result) {
            if (err) {
                console.log(err);
                return;
            }
            for (let i = 0; i < result.length; i++) {
                if (result[i].getName() === 'custom:attr_id') {                    
                    attr_id = result[i].getValue();
                    console.log(attr_id);
                    localStorage;
                    localStorage.setItem("attr_id", attr_id);                                                
                }
                }                    
                else {
                  console.log(result[i].getValue());
                }
            }

        });

    });
}}

And then I call it in this order:

    <script type="text/javascript">
    window.onload = function () {
      checkLogin(false, true);
      getUserAttributes();
      localStorage;
      var attr = localStorage.getItem("attr_id");

  }
</script>

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