2

Recently I was using the Sign-up and Sign-in template similar this one developed by Vladimir Budilov.

But now, I've been modifying my application to use the hosted UI developed by Amazon. So my application redirects to the hosted UI, all the authentication is made there and they send me the authentication token, more os less as explained in this tutorial.

Summarizing, I call the hosted UI and do login: https://my_domain/login?response_type=token&client_id=my_client_id&redirect_uri=https://www.example.com

I'm redirected to: https://www.example.com/#id_token=123456789tokens123456789&expires_in=3600&token_type=Bearer

So, I have now the token_id but I can't get the current user or user parameters from this. Could anyone help me with informations or some directions?

I've tried the methods in Amazon developer guide .

It works well when I was using Vladimir Budilov's template but trying to use the token_id, I'm not succeeding. Thanks in advance for your time and help.

var data = {
    UserPoolId : '...', // Your user pool id here
    ClientId : '...' // Your client id here
};
var userPool = new AmazonCognitoIdentity.CognitoUserPool(data);
var cognitoUser = userPool.getCurrentUser();

if (cognitoUser != null) {
    cognitoUser.getSession(function(err, session) {
        if (err) {
           alert(err);
            return;
        }
        console.log('session validity: ' + session.isValid());

        AWS.config.credentials = new AWS.CognitoIdentityCredentials({
            IdentityPoolId : '...' // your identity pool id here
            Logins : {
                // Change the key below according to the specific region your user pool is in.
                'cognito-idp.<region>.amazonaws.com/<YOUR_USER_POOL_ID>' : session.getIdToken().getJwtToken()
            }
        });

        // Instantiate aws sdk service objects now that the credentials have been updated.
        // example: var s3 = new AWS.S3();

    });
}
Ashan
  • 18,898
  • 4
  • 47
  • 67
Vítor Resende
  • 230
  • 3
  • 16

2 Answers2

2

The attributes you configure to be added as claims are already available inside the id_token with base64 encoding (Since its a JWT token).

You can decode the token and access these attributes both at Client Side using Javascript and on Server.

For more info refer the StackOverflow question How to decode JWT tokens in JavaScript.

Note: If you need to trust these attributes for a backend operation, make sure you verify the JWT signature before trusting the attributes.

Ashan
  • 18,898
  • 4
  • 47
  • 67
  • That's right. Thanks for your answer. I didn't know abou JWT and now I'm understanding cause your answer. With this solution I really can get the user informations, but for verification like Amazon quote in its site using: https://github.com/awslabs/aws-support-tools/tree/master/Cognito/decode-verify-jwt. For now, I can't understand how it works. Do you get it? – Vítor Resende May 24 '18 at 16:22
  • After you create a CognitoUserPool you can visit the URL https://cognito-idp.{region}.amazonaws.com/{userPoolId}/.well-known/jwks.json (Make sure you fill the region and userPoolId) and download the required keys. These can be used to verify the JWT Token. If you plan to write the custom authorizer using NodeJS, you can use https://github.com/99xt/cognito-jwt-token-validator – Ashan May 24 '18 at 17:21
  • Thank you Ashan, you really helped me. :D – Vítor Resende May 24 '18 at 17:48
0

Here's a specific example of how to parse the callback parameters and set up a user session. This could be initiated in onLoad of your page.

import { CognitoAuth } from 'amazon-cognito-auth-js';

const authData = {
    ClientId : '<TODO: add ClientId>', // Your client id here
    AppWebDomain : '<TODO: add App Web Domain>',
    TokenScopesArray : ['<TODO: add scope array>'], // e.g.['phone', 'email', 'profile','openid', 'aws.cognito.signin.user.admin'],
    RedirectUriSignIn : '<TODO: add redirect url when signed in>',
    RedirectUriSignOut : '<TODO: add redirect url when signed out>',
    IdentityProvider : '<TODO: add identity provider you want to specify>', // e.g. 'Facebook',
    UserPoolId : '<TODO: add UserPoolId>', // Your user pool id here
    AdvancedSecurityDataCollectionFlag : '<TODO: boolean value indicating whether you want to enable advanced security data collection>', // e.g. true
        Storage: '<TODO the storage object>' // OPTIONAL e.g. new CookieStorage(), to use the specified storage provided
};
const auth = new CognitoAuth(authData);
auth.userhandler = {
    onSuccess: function(result) {
        alert("Sign in success");
        showSignedIn(result);
    },
    onFailure: function(err) {
        alert("Error!");
    }
};

const curUrl = window.location.href;
auth.parseCognitoWebResponse(curUrl);

Now you're "signed in" as far as the Cognito JS client is concerned, and you can use getCurrentUser(), getSession(), etc. `See "Use case 2" here for more context/details.

Jake Stoeffler
  • 2,662
  • 24
  • 27