Search code examples
javaamazon-web-servicesamazon-cognito

Set attributesToGet() in ListUsersRequest : Java


I want to fetch only username attribute from cognito.

When I do not set anything in my attributesToGet(), I am able to successfully fetch the record. But when I try to set any attributes, I get an error : AwsErrorDetails(errorMessage=One or more requested attributes do not exist., errorCode=InvalidParameterException, serviceName=CognitoIdentityProvider)

below is the code with the attribute set to username

 String emailId = "[email protected]";
 ListUsersRequest listUsersRequest = ListUsersRequest.builder()
            .userPoolId(userPoolId)
            .filter(String.format("%s = \"%s\"", "email", emailId))
            .attributesToGet(new String[]{"username"})
            .build();

        ListUsersResponse userInfo = cognitoIdentityProviderClient
            .listUsers(listUsersRequest);

below is a screenshot of my cognito pool headers enter image description here

Please help me get this working!


Solution

  • The attribute username you are trying to get is not part of the list of attributes for which this is applicable, it is a "top-level" user attribute and is always present.

    When you get a response (as you are able to when not passing anything in attributesToGet) you will notice the attributes list does not contain the username, which is outside, as seen in this example:

    {
      "Users": [
        {
          "Username": "johndoe",
          "Attributes": [
            { "Name": "sub", "Value": "41f3c652-6d3b-4ae5-8bad-271785f9adb5" },
            { "Name": "email_verified", "Value": "true" },
            { "Name": "name", "Value": "John Doe" },
            { "Name": "email", "Value": "[email protected]" },
            { "Name": "custom:role", "Value": "administrator" }
          ],
          "UserCreateDate": "2022-06-22T11:11:40.180000+01:00",
          "UserLastModifiedDate": "2022-07-23T11:55:35.352000+01:00",
          "Enabled": true,
          "UserStatus": "RESET_REQUIRED"
        }
      ]
    }
    

    Also check the ListUsers Response syntax in API Reference where the Username is shown as a top-level field.