amazon-archives / amazon-cognito-identity-js

Amazon Cognito Identity SDK for JavaScript
Other
985 stars 451 forks source link

Missing credentials in config with use case 4 #68

Closed ToddHoff closed 8 years ago

ToddHoff commented 8 years ago

I'm able to register a user and a confirm the code. Yay. Now I want to list some buckets in S3. The error I get in the console is: Error: Missing credentials in config

The token prints out and everything looks good until the s3.listBuckets call. Here's the code:

function authenticateUser(username, password, identityPoolId, userPoolId, clientId) {

AWS.config.region = 'us-east-1'; AWS.config.credentials = new AWS.CognitoIdentityCredentials({ IdentityPoolId: identityPoolId, });

AWSCognito.config.region = 'us-east-1'; AWSCognito.config.credentials = new AWS.CognitoIdentityCredentials({ IdentityPoolId: identityPoolId, });

var authenticationData = { Username : username, Password : password };

console.log(authenticationData);

var authenticationDetails = new AWSCognito.CognitoIdentityServiceProvider.AuthenticationDetails(authenticationData); var poolData = { UserPoolId : userPoolId, ClientId : clientId }; var userPool = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(poolData); var userData = { Username : username, Pool : userPool }; var cognitoUser = new AWSCognito.CognitoIdentityServiceProvider.CognitoUser(userData); cognitoUser.authenticateUser(authenticationDetails, { onSuccess: function (result) { console.log('access token + ' + result.getAccessToken().getJwtToken());

  var login = "cognito-idp.us-east-1.amazonaws.com/" + userPoolId;

  AWS.config.credentials = new AWS.CognitoIdentityCredentials({
    IdentityPoolId: identityPoolId,
    Logins : {
      login : result.getIdToken().getJwtToken()
      }
    });

  var s3 = new AWS.S3();
  s3.listBuckets(function(err, data) {
    if (err) { console.log("Error:", err); }
    else {
      for (var index in data.Buckets) {
        var bucket = data.Buckets[index];
        console.log("Bucket: ", bucket.Name, ' : ', bucket.CreationDate);
      }
    }
  });

},
onFailure: function(err) {
  alert("Error:" + err);
},

});

}// authenticateUser

Is there something I'm doing wrong here?

chetanme commented 8 years ago

I believe you asked the same question on AWS forums. Will close this in favor of forum post.

ToddHoff commented 8 years ago

I asked there because I really need an answer to make progress with this service. So it's not closed.

On Wed, Jun 22, 2016 at 12:28 AM, Chetan Mehta notifications@github.com wrote:

I believe you asked the same question on AWS forums. Will close this in favor of forum post.

— You are receiving this because you authored the thread. Reply to this email directly, view it on GitHub, or mute the thread.

chetanme commented 8 years ago

I have answered your question on the forum post and was hoping that we can continue the discussion there if needed. Basically, after configuring your credentials object with the token, you will need to make a call to obtain those credentials by calling refresh(). You can then put your call to S3 inside the callback.

AWS.config.credentials = new AWS.CognitoIdentityCredentials({...}); AWS.config.credentials.refresh(function(){ // Your S3 code here... });

ToddHoff commented 8 years ago

Thanks! I never seem to get emails from amazon threads even though I'm watching them.

One thing, if this is necessary, shouldn't it be in the example code?

So I made the code change:

console.log("BEFORE AWSCognito.CognitoIdentityServiceProvider.CognitoUser"); var cognitoUser = new AWSCognito.CognitoIdentityServiceProvider.CognitoUser(userData); cognitoUser.authenticateUser(authenticationDetails, { onSuccess: function (result) { console.log('access token + ' + result.getAccessToken().getJwtToken());

  var login_fldname = "cognito-idp.us-east-1.amazonaws.com/" +

login.userPoolId;

console.log("BEFORE new AWS.CognitoIdentityCredentials"); AWS.config.credentials = new AWS.CognitoIdentityCredentials({ IdentityPoolId: login.identityPoolId, Logins : { login_fldname : result.getIdToken().getJwtToken() } }); console.log("BEFORE refresh"); AWS.config.credentials.refresh(function(err){ console.log(err); console.log("BEFORE new AWS.S3"); var s3 = new AWS.S3();

And I get this error from AWS.config.credentials.refresh(function(err):

pro.html:90 Error: Logins don't match. Please include at least one valid login for this identity or identity pool.(…)

It doesn't matter if I hard code the login to:

AWS.config.credentials = new AWS.CognitoIdentityCredentials({ IdentityPoolId: login.identityPoolId, Logins : { "cognito-idp.us-east-1.amazonaws.com/us-east-1_P0RM3dXyy" : result.getIdToken().getJwtToken() } });

I'm not sure why the login is invalid, it's the same data that was used when registering the user and confirming the code. the AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool and AWSCognito.CognitoIdentityServiceProvider.CognitoUser calls.

One thing I've noticed that every time I run the authentication code I see the identity count in my federated identity pool increase. Is that correct?

thanks

On Wed, Jun 22, 2016 at 7:46 AM, Chetan Mehta notifications@github.com wrote:

I have answered your question on the forum post. Basically, after configuring your credentials object with the token, you will need to make a call to obtain those credentials by calling refresh(). You can then put your call to S3 inside the callback.

`AWS.config.credentials = new AWS.CognitoIdentityCredentials({...});

AWS.config.credentials.refresh(function(){ // Your S3 code here... });`

— You are receiving this because you authored the thread. Reply to this email directly, view it on GitHub https://github.com/aws/amazon-cognito-identity-js/issues/68#issuecomment-227767456, or mute the thread https://github.com/notifications/unsubscribe/ABOgrtZukXWVffRXolWEchTBAiv1IfViks5qOUrWgaJpZM4I6QKJ .

chetanme commented 8 years ago

Logins don't match. Please include at least one valid login for this identity or identity pool error is thrown if your identity pool is not configured to support authentication providers and just supports unauthenticated access.

You can follow this guide to see the steps which can help you configure your federated identity pool with a user pool. Once this is done, you should not get this error.

chetanme commented 8 years ago

Logins don't match. Please include at least one valid login for this identity or identity pool error is thrown if your identity pool is not configured to support authentication providers and just supports unauthenticated access.

You can follow this guide to see the steps which can help you configure your federated identity pool with a user pool. Once this is done, you should not get this error.

ToddHoff commented 8 years ago

Thanks, I selected cognito but didn't match it to a pool. I did so and in the federated identity dashboard I see a us-east-1_P0RM3dXyy

_2.6%_1

Now I get an error from the refresh call:

NotAuthorizedException: Invalid login token. Issuer doesn't match providerName

I rechecked all my ids and I looked up the error and didn't see anything obviously relevant.

It does give me a token:

access token + eyJraWQiOiJ5TnVsR3YrVHh6Nk9cL0xFcldNOWFNTjNyNzA5UzAzRlFYMTd6dUJIOXFHZz0iLCJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJkNTkyMTFhOS0yNjMzLTQzMDAtODliMy1jYjQwNDMwZjBmZjAiLCJ0b2tlbl91c2UiOiJhY2Nlc3MiLCJzY29wZSI6ImF3cy5jb2duaXRvLnNpZ25pbi51c2VyLmFkbWluIiwiaXNzIjoiaHR0cHM6XC9cL2NvZ25pdG8taWRwLnVzLWVhc3QtMS5hbWF6b25hd3MuY29tXC91cy1lYXN0LTFfUDBSTTNkWHl5IiwiZXhwIjoxNDY2NzAzODA0LCJjbGllbnRfaWQiOiI2NzhvYnN0ZmR1dmlqbXVxOWdhOGh1Zzg4biIsInVzZXJuYW1lIjoiYW5uaWUifQ.Yd6ra8wR2Qkt07xrEs4RjiwKI7Wn1bj4XSurH4MtUYhhJptHOBoe2qioJWGoyz8PAtpeIJCAgqq_y8SSqxTnGnfNdfLylx9XEcqvbuETGCnMnjoDNOhXzp7jWpg0KmJyKnVhU5-LViON0T_2hrDGJ3VsqgLDb78pNmSiH6vHg7FatAlLMvfUYWMgTgVEezk66yLT7yM_ur0uZin0t1vxSqGs_EGyFZUE27eA2wbcQtI7EGON7yifnzAckpSQB3Vfk5ucq4_dLH9cMOmkcM1HeJYDu5pjI6y3yEGNKlOLwu7tWTspnNST2s0aMBfP4ssu04EckoirpxOUjZ9VXbZ4dg

The code:

var login = { region: "us-east-1", username: "xxx", password: "yyy", email: "user@gmail.com", identityPoolId: "us-east-1:d7dfdd6f-5a5e-43dd-abd6-7674606a8712", userPoolId: "us-east-1_P0RM3dXyy", clientId: "678obstfduvijmuq9ga8hug88n", }

function authenticateUser(login) { console.log("authenticateUser:" + JSON.stringify(login));

AWS.config.region = login.region, AWS.config.credentials = new AWS.CognitoIdentityCredentials({ IdentityPoolId: login.identityPoolId, });

AWSCognito.config.region = login.region; AWSCognito.config.credentials = new AWS.CognitoIdentityCredentials({ IdentityPoolId: login.identityPoolId, });

var authenticationData = { Username : login.username, Password : login.password };

var authenticationDetails = new AWSCognito.CognitoIdentityServiceProvider.AuthenticationDetails(authenticationData); var poolData = { UserPoolId : login.userPoolId, ClientId : login.clientId };

var userPool = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(poolData); var userData = { Username : login.username, Pool : userPool };

var cognitoUser = new AWSCognito.CognitoIdentityServiceProvider.CognitoUser(userData); cognitoUser.authenticateUser(authenticationDetails, {

onSuccess: function (result) {
  console.log('access token + ' +

result.getAccessToken().getJwtToken());

  var login_fldname = "cognito-idp.us-east-1.amazonaws.com/" +

login.userPoolId;

  AWS.config.credentials = new AWS.CognitoIdentityCredentials({
    IdentityPoolId: login.identityPoolId,
    Logins : {
        login_fldname : result.getIdToken().getJwtToken()
      }
    });

  console.log("BEFORE refresh");
  AWS.config.credentials.refresh(function(err){
    if (err) {
      console.log("Refresh Error:" + err);
    } else {
      console.log("BEFORE new AWS.S3");
      var s3 = new AWS.S3();
      s3.listBuckets(function(err, data) {
        if (err) { console.log("Error:", err); }
        else {
          for (var index in data.Buckets) {
            var bucket = data.Buckets[index];
            console.log("Bucket: ", bucket.Name, ' : ',

bucket.CreationDate); } } }) } }) }, onFailure: function(err) { alert("Error:" + err); }, });

}// authenticateUser

On Wed, Jun 22, 2016 at 2:43 PM, Chetan Mehta notifications@github.com wrote:

Reopened #68 https://github.com/aws/amazon-cognito-identity-js/issues/68 .

— You are receiving this because you authored the thread. Reply to this email directly, view it on GitHub https://github.com/aws/amazon-cognito-identity-js/issues/68#event-701135591, or mute the thread https://github.com/notifications/unsubscribe/ABOgrkBz27aY7FUuglrBQVN6j-1xZNtUks5qOayNgaJpZM4I6QKJ .

chetanme commented 8 years ago

This all looks fine and should work as expected. If this keeps failing for you, can you post a request id with the time stamp which got this error? It will help us debug this on the service side.

itrestian commented 8 years ago

Credentials are no longer required since we are now making unauthenticated calls. Closing.

paulsson commented 8 years ago

Wow... @ToddHoff did you ever get this resolved? I don't see a resolution posted and explained here or on your AWS forum thread. I am having the same exact issue. When I call "authenticateUser" I successfully get back all 3 tokens which are written to LocalStorage automatically. However when I try to call "get" or "refresh" on my credentials object I get: Invalid login token. Issuer doesn't match providerName

Here's some of the http headers from the response: Date:Wed, 14 Sep 2016 15:24:58 GMT x-amzn-ErrorMessage:Invalid login token. Issuer doesn't match providerName x-amzn-ErrorType:NotAuthorizedException: x-amzn-RequestId:65853701-7a8f-11e6-9dd6-635c717d3ebc

My client id, user pool id, and identity pool id are all set properly and verified.

@chetanme can I take you up on your offer to look into the service logs for my RequestId above?

paulsson commented 8 years ago

I figured it out. Most people will want a central "config" location where they define values for their user pool id, identity pool id, client id, etc so they don't have to proliferate these hardcoded values throughout their code. However you can't use a variable value as a key when constructing your cognito credentials idp Logins map / dict.

In case anybody else is trying something similar.

Don't:

let loginsCognitoKey = 'cognito-idp.us-east-1.amazonaws.com/' + AppConfig.USER_POOL_ID;
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
    IdentityPoolId: AppConfig.IDENTITY_POOL_ID,
    Logins: {
        loginsCognitoKey: result.getIdToken().getJwtToken()
    }
});

Do:

let loginsCognitoKey = 'cognito-idp.us-east-1.amazonaws.com/' + AppConfig.USER_POOL_ID;
let loginsIdpData = {};
loginsIdpData[loginsCognitoKey] = result.getIdToken().getJwtToken();
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
    IdentityPoolId: AppConfig.IDENTITY_POOL_ID,
    Logins: loginsIdpData
});

I didn't notice this until I was inspecting the http request body that was being sent when trying to retrieve AWS creds. Would be nice if the cognito examples were updated with a little more real world examples using best practices of not proliferating hardcoded values throughout the code.

itrestian commented 8 years ago

Thanks for the feedback. You can send a pull request to make it clear in the documentation how you need to construct your logins map.

jonmanzo commented 8 years ago

Know this is closed but this should not be in the docs as it is simple JavaScript.

{ Logins: { loginsCognitoKey: result.getIdToken().getJwtToken() } }

Will always equate to a prop name of loginsCognitoKey.

Just do this:

` { Logins: {

} } `