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?
2
Answers
so I figure it out by separating getting attributes from login.
I have added following function:
And then I call it in this order:
It seems you either need to specify the username you’re trying to obtain custom attributes from:
or, alternatively you’ll need to loop over the users in the pool to find out their user and dynamically assign and
getUserAttributes
: