简体   繁体   中英

How to get user attributes (username, email, etc.) using cognito identity id

I have AWS Cognito Identity Pool that is configured with Cognito User Pool as an authentication provider.

Assume I have identity ID of an identity in Cognito Identity Pool (eg us-east-1:XXaXcXXa-XXXX-XXXX-XXX-XXXXXXXXXXXX) where this identity has a linked login to a user in Cognito User Pool.

Using identity ID, how can I get the linked user details (email, phone, username)?

The ID Token that you exchange with Cognito federated identity service to get the identity id and credentials already has all user attributes. You do not need an extra call to any service.

在此处输入图片说明

It is a JWT token and you can use any library on the client to decode the values. You can read this guide for more information about the tokens vended by Cognito user pools.

Alternatively, you can also use the Access Token to call GetUser API which will return all the user information.

Using REST API

AccessToken

Thought that this could be very helpful to someone as I've spent a lot of time trying to figure out how to get UserAttributes with only accessToken and region ( Similar to this but with REST API ( Without using aws-sdk )

You can get UserAttributes with accessToken using this HTTP request. ( GetUser )

Method: POST
Endpoint: https://cognito-idp.{REGION}.amazonaws.com/
Content-Type: application/x-amz-json-1.1
Content-Length: 1162 // Access Token bytes length
X-Amz-Target: AWSCognitoIdentityProviderService.GetUser
Body: {"AccessToken":"ACCESS_TOKEN"}

And if the accessToken is valid, you should receive example response like the following

{
    "UserAttributes": [
        {
            "Name": "sub",
            "Value": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxx"
        },
        {
            "Name": "email_verified",
            "Value": "true"
        },
        {
            "Name": "name",
            "Value": "Jason"
        },
        {
            "Name": "phone_number_verified",
            "Value": "true"
        },
        {
            "Name": "phone_number",
            "Value": "+xxxxxxxxxxx"
        },
        {
            "Name": "email",
            "Value": "xxxx@gmail.com"
        }
    ],
    "Username": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxx"
}

AWS cognito-idp list-users has a filter option that allows you to filter based on attribute. 'sub' is the attribute that matches the identity id you are describing.

eg at the command line:

aws cognito-idp list-users --user-pool-id us-east-1_abcdFghjI --filter "sub=\":XXaXcXXa-XXXX-XXXX-XXX-XXXXXXXXXXXX\""

This also requires the user-pool-id, which I suspect you have. Additionally, I have no idea how this is implemented or how it performances when filtering a large number of users, but I take custom attributes not being usable in filters as a hint that there is some form of indexing behind the curtain.

I faced the similar issue and after too much of scratching i was not able to find the exact way of pulling out the details. My usecase was to get the details in android APP. After looking into their AWSMobile client API code. I found below and it is working from me.

Log.i(TAG, "User Details"+ AWSMobileClient.getInstance().getUserAttributes().toString());

Recommendation - Try use AWSMobileclient incase you are using it for Android Development as this is new library that is recommended for development.

Just struggled with this for a while, and the way I got the user name, using Java API is:

identityManager.login(this, new DefaultSignInResultHandler() {
        @Override
        public void onSuccess(Activity activity, IdentityProvider identityProvider) {
            ...               
            String userName = ((CognitoUserPoolsSignInProvider) identityProvider).getCognitoUserPool().getCurrentUser().getUserId();

There is a listener we can initialize that will listen to changes in our authentication state and allow us to have access to the type of authentication event that happened and update the application state based on that data.

With Amplify, the Hub module allows us to do this pretty easily:

import { Hub } from 'aws-amplify';

Hub.listen('auth', (data) => {
    const {payload} = data;
    if (payload.event === 'signOut') {
       console.log('signOut');
    } else if (payload.event === 'signIn') {
       console.log('A new auth event has happened: ', data.payload.data.username + ' has ' + data.payload.event);
    }
});

在此处输入图片说明

For those who are looking how to get the value of email parameter in Java programmatically

I assume you have already figured out how to get the needed / all users from the pool.

Say I have ListUsersResult with my all users and say I want to check the email value of the first user:

ListUsersResult allUsers = getAllUsers();
UserType userType = allUsers.getUsers().get(0);

First I can get user's all attributes:

List<AttributeType> attributes = userType.getAttributes();

Then loop through the attributes looking for the one we're interested in (our case email ):

for (AttributeType att : attributes) {
      if (att.getName().equals("email")) {
        // do whatever you want


      }
    }

Remember that printing in to the console will most probably not work since it is sensitive data. But you can compare it like this:

att.getValue().equals("mymail@mail")

Use this piece of code

       GetDetailsHandler detailsHandler = new GetDetailsHandler() {
     @Override
     public void onSuccess(CognitoUserDetails cognitoUserDetails) {
        CognitoUserAttributes cognitoUserAttributes=cognitoUserDetails.getAttributes();
        stringStringHashMap=new HashMap<>();
        stringStringHashMap =cognitoUserAttributes.getAttributes();
         userNumber=stringStringHashMap.get("phone_number");
        e1.setText(userNumber);

        Log.d("Response"," Inside DEATILS HANDLER");
        // Store details in the AppHandler
        AppHelper.setUserDetails(cognitoUserDetails);
        // Trusted devices?
        handleTrustedDevice();
       // e1.setText(input.getText().toString());
         }

         @Override
          public void onFailure(Exception exception) {
        closeWaitDialog();
        showDialogMessage("Could not fetch user details!", AppHelper.formatException(exception), true);
        }
       };
     private void getDetails() {
    AppHelper.getPool().getUser(username).getDetailsInBackground(detailsHandler);
      }  
console.log('username is ' + cognitoUser.getUsername());

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