简体   繁体   English

使用 amazon-cognito-identity.min.js 获取 Cognito 用户自定义属性

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

I have a Cognito user authentication using amazon-cognito-identity.min.js.我有一个使用 amazon-cognito-identity.min.js 的 Cognito 用户身份验证。 Login, getting jwt token works just fine.登录,获取 jwt 令牌就可以了。 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.我发现我应该使用 cognitoUser.getUserAttributes(),但这似乎不起作用。

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:这是我触发它的 index.html 部分:

    <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 :或者,您需要遍历池中的用户以找出他们的用户并动态分配和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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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