Reputation: 1325
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 (e.g. 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)?
Upvotes: 78
Views: 142635
Reputation: 1
To retrieve the user attributes like email or username, first authenticate the user, and then simply call Auth.fetchUserAttributes(). This will give you the user's all attributes.
Step 1: Authenticate the user – Ensure the user is authenticated using AWS Amplify's authentication methods, such as Auth.signIn().
Step 2: Fetch the Cognito Identity ID using Auth.fetchUserAttributes().
const getUserData = async () => {
try {
const session = await Auth.fetchUserAttributes();
conosle.log(session);
} catch (error) {
console.error('Error fetching attributes:', error);
}
};
Note: call the getUserData() after user is Authicated, else through the error cannot call this API.
Upvotes: 0
Reputation: 1
If you want to get the user attributes client-side in a web environment, just use aws-amplify/auth which also exports the getCurrentUser (you might know that one).
import { fetchUserAttributes } from "aws-amplify/auth";
Upvotes: 0
Reputation: 10720
Below aws cli command will return user email from username (aka user sub, user id)
aws cognito-idp admin-get-user --user-pool-id [user_pool_id] --username [user_id] --region [region] --query "UserAttributes[?Name=='email'].Value" --output text --debug
Upvotes: 0
Reputation: 1304
When you get the AccessToken and RefreshToken, you also get a IdToken (if not, maybe try adding scope in Cognito)
The Id Token has some of the information decoded and can be very helpful without adding and extra call to AWS!
Check you Id Token with an online tool as jwt.io and see if the Attribute you need is there...
Upvotes: 0
Reputation: 3644
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": "[email protected]"
}
],
"Username": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxx"
}
Upvotes: 46
Reputation: 1303
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")
Upvotes: 0
Reputation: 7383
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);
}
});
Upvotes: 1
Reputation: 5661
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.
Upvotes: 70
Reputation: 1840
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();
Upvotes: 1
Reputation: 41
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.
e.g. 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.
Upvotes: 4
Reputation: 21
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.
Upvotes: 1
Reputation: 1
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);
}
Upvotes: -12