Using an stsclient assumed role with cognito in java

0

I am using Java.

I have an aws user (sts client) on which I do an "assume role" before trying to call cognito "list users".

The assume role seem to be working fine. However, the "list users" is throwing an error ("The security token included in the request is invalid") and I don't know why. Here is the full error trace:

software.amazon.awssdk.services.cognitoidentityprovider.model.CognitoIdentityProviderException: The security token included in the request is invalid. (Service: CognitoIdentityProvider, Status Code: 400, Request ID: XXX-XXX-XXX)
at software.amazon.awssdk.core.internal.http.CombinedResponseHandler.handleErrorResponse(CombinedResponseHandler.java:125)
at software.amazon.awssdk.core.internal.http.CombinedResponseHandler.handleResponse(CombinedResponseHandler.java:82)
at software.amazon.awssdk.core.internal.http.CombinedResponseHandler.handle(CombinedResponseHandler.java:60)
at software.amazon.awssdk.core.internal.http.CombinedResponseHandler.handle(CombinedResponseHandler.java:41)
at software.amazon.awssdk.core.internal.http.pipeline.stages.HandleResponseStage.execute(HandleResponseStage.java:40)
at software.amazon.awssdk.core.internal.http.pipeline.stages.HandleResponseStage.execute(HandleResponseStage.java:30)
at software.amazon.awssdk.core.internal.http.pipeline.RequestPipelineBuilder$ComposingRequestPipelineStage.execute(RequestPipelineBuilder.java:206)
at software.amazon.awssdk.core.internal.http.pipeline.stages.ApiCallAttemptTimeoutTrackingStage.execute(ApiCallAttemptTimeoutTrackingStage.java:73)
at software.amazon.awssdk.core.internal.http.pipeline.stages.ApiCallAttemptTimeoutTrackingStage.execute(ApiCallAttemptTimeoutTrackingStage.java:42)
at software.amazon.awssdk.core.internal.http.pipeline.stages.TimeoutExceptionHandlingStage.execute(TimeoutExceptionHandlingStage.java:78)
at software.amazon.awssdk.core.internal.http.pipeline.stages.TimeoutExceptionHandlingStage.execute(TimeoutExceptionHandlingStage.java:40)
at software.amazon.awssdk.core.internal.http.pipeline.stages.ApiCallAttemptMetricCollectionStage.execute(ApiCallAttemptMetricCollectionStage.java:50)
at software.amazon.awssdk.core.internal.http.pipeline.stages.ApiCallAttemptMetricCollectionStage.execute(ApiCallAttemptMetricCollectionStage.java:36)
at software.amazon.awssdk.core.internal.http.pipeline.stages.RetryableStage.execute(RetryableStage.java:81)
at software.amazon.awssdk.core.internal.http.pipeline.stages.RetryableStage.execute(RetryableStage.java:36)
at software.amazon.awssdk.core.internal.http.pipeline.RequestPipelineBuilder$ComposingRequestPipelineStage.execute(RequestPipelineBuilder.java:206)
at software.amazon.awssdk.core.internal.http.StreamManagingStage.execute(StreamManagingStage.java:56)
at software.amazon.awssdk.core.internal.http.StreamManagingStage.execute(StreamManagingStage.java:36)
at software.amazon.awssdk.core.internal.http.pipeline.stages.ApiCallTimeoutTrackingStage.executeWithTimer(ApiCallTimeoutTrackingStage.java:80)
at software.amazon.awssdk.core.internal.http.pipeline.stages.ApiCallTimeoutTrackingStage.execute(ApiCallTimeoutTrackingStage.java:60)
at software.amazon.awssdk.core.internal.http.pipeline.stages.ApiCallTimeoutTrackingStage.execute(ApiCallTimeoutTrackingStage.java:42)
at software.amazon.awssdk.core.internal.http.pipeline.stages.ApiCallMetricCollectionStage.execute(ApiCallMetricCollectionStage.java:48)
at software.amazon.awssdk.core.internal.http.pipeline.stages.ApiCallMetricCollectionStage.execute(ApiCallMetricCollectionStage.java:31)
at software.amazon.awssdk.core.internal.http.pipeline.RequestPipelineBuilder$ComposingRequestPipelineStage.execute(RequestPipelineBuilder.java:206)
at software.amazon.awssdk.core.internal.http.pipeline.RequestPipelineBuilder$ComposingRequestPipelineStage.execute(RequestPipelineBuilder.java:206)
at software.amazon.awssdk.core.internal.http.pipeline.stages.ExecutionFailureExceptionReportingStage.execute(ExecutionFailureExceptionReportingStage.java:37)
at software.amazon.awssdk.core.internal.http.pipeline.stages.ExecutionFailureExceptionReportingStage.execute(ExecutionFailureExceptionReportingStage.java:26)
at software.amazon.awssdk.core.internal.http.AmazonSyncHttpClient$RequestExecutionBuilderImpl.execute(AmazonSyncHttpClient.java:193)
at software.amazon.awssdk.core.internal.handler.BaseSyncClientHandler.invoke(BaseSyncClientHandler.java:103)
at software.amazon.awssdk.core.internal.handler.BaseSyncClientHandler.doExecute(BaseSyncClientHandler.java:167)
at software.amazon.awssdk.core.internal.handler.BaseSyncClientHandler.lambda$execute$1(BaseSyncClientHandler.java:82)
at software.amazon.awssdk.core.internal.handler.BaseSyncClientHandler.measureApiCallSuccess(BaseSyncClientHandler.java:175)
at software.amazon.awssdk.core.internal.handler.BaseSyncClientHandler.execute(BaseSyncClientHandler.java:76)
at software.amazon.awssdk.core.client.handler.SdkSyncClientHandler.execute(SdkSyncClientHandler.java:45)
at software.amazon.awssdk.awscore.client.handler.AwsSyncClientHandler.execute(AwsSyncClientHandler.java:56)
at software.amazon.awssdk.services.cognitoidentityprovider.DefaultCognitoIdentityProviderClient.listUsers(DefaultCognitoIdentityProviderClient.java:6504)
at EC.myClass.listUsersFilter(myClass.java:107)
at EC.myClass.myMainFunction(myClass.java:62)

Here is my code in Java:

import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.cognitoidentityprovider.model.*;
import software.amazon.awssdk.services.sts.StsClient;
import software.amazon.awssdk.services.sts.model.AssumeRoleRequest;
import software.amazon.awssdk.services.sts.model.StsException;
import software.amazon.awssdk.services.sts.model.AssumeRoleResponse;
import software.amazon.awssdk.services.sts.model.Credentials;

import software.amazon.awssdk.services.cognitoidentityprovider.CognitoIdentityProviderClient;


public class myClass{

	public static void myMainFunction(String role, String envRole, String userPoolId, String clientEmail){

		String roleArn = "arn:aws:iam::"+envRole+":role/"+role;
		String roleSessionName = "AssumeRoleSession1";
		Region region = Region.EU_WEST_1;

		StsClient stsClient = StsClient.builder()
				.region(region)
				.credentialsProvider(ProfileCredentialsProvider.create())
				.build();

		Credentials myCreds = assumeGivenRole(stsClient, roleArn, roleSessionName);

		AwsBasicCredentials awsCreds = AwsBasicCredentials.create(myCreds.accessKeyId(), myCreds.secretAccessKey());

		CognitoIdentityProviderClient cognitoClient = CognitoIdentityProviderClient.builder()
				.region(region)
				.credentialsProvider(StaticCredentialsProvider.create(awsCreds))
				.build();


		String username = listUsersFilter(cognitoClient, userPoolId, clientEmail);

	}

	public static Credentials assumeGivenRole(StsClient stsClient, String roleArn, String roleSessionName) {
		AssumeRoleRequest roleRequest = AssumeRoleRequest.builder()
				.roleArn(roleArn)
				.roleSessionName(roleSessionName)
				.build();

		AssumeRoleResponse roleResponse = stsClient.assumeRole(roleRequest);
		Credentials myCreds = roleResponse.credentials();

		return myCreds;
	}

	// Shows how to list users by using a filter.
	public static String listUsersFilter(CognitoIdentityProviderClient cognitoClient, String userPoolId, String email) {		
		String filter = "email = \""+email+"\"";
		ListUsersRequest usersRequest = ListUsersRequest.builder()
				.userPoolId(userPoolId)
				.filter(filter)
				.build();

		ListUsersResponse response = cognitoClient.listUsers(usersRequest);
		response.users().forEach(user -> {
			System.out.println("User with filter applied " + user.username() + " Status " + user.userStatus() + " Created " + user.userCreateDate() );
		});

		return response.users().get(0).username();
	}

I don't know why my code isn't working. Especially since I have the exact same code in Python where it's working just fine (though in Python, I explicitly give the sessionToken to cognito, but it doesn't seem to be possible in Java?).

Any idea on what I'm doing wrong?


For comparison, here is the same code in Python which is working:

	sts = boto3.client('sts')

	assumed_role_object=sts.assume_role(
		RoleArn="arn:aws:iam::"+env_role+":role/"+role,
		RoleSessionName="AssumeRoleSession1"
	)

	credentials=assumed_role_object['Credentials']
	cognito=boto3.client(
	    'cognito-idp',
	    region_name="eu-west-1",
	    aws_access_key_id=credentials['AccessKeyId'],
	    aws_secret_access_key=credentials['SecretAccessKey'],
	    aws_session_token=credentials['SessionToken'],
	)

	getUser = cognito.list_users(
		UserPoolId=userPoolId,
		AttributesToGet=[],
		Limit=10,
		Filter='email="'+email+'"'
	)
1 Answer
0

Your Python version is providing the session token to the Cognito client but your Java version is not. Use AwsSessionCredentials instead of AwsBasicCredentials.

profile pictureAWS
answered 2 years ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions