Skip to content

Instantly share code, notes, and snippets.

@bpaquet
Created January 22, 2025 11:30
Show Gist options
  • Save bpaquet/10c2098d75c8e56608414844ea990b5a to your computer and use it in GitHub Desktop.
Save bpaquet/10c2098d75c8e56608414844ea990b5a to your computer and use it in GitHub Desktop.
Simple class to generate AWS STS GetcallerIdentity presigned url
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import software.amazon.awssdk.auth.signer.Aws4Signer;
import software.amazon.awssdk.auth.signer.params.Aws4PresignerParams;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.http.SdkHttpMethod;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sts.StsClient;
import software.amazon.awssdk.services.sts.endpoints.StsEndpointParams;
import software.amazon.awssdk.services.sts.endpoints.StsEndpointProvider;
import java.net.URI;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
public class StsPreSigner {
public static final String GET_CALLER_IDENTITY_ACTION = "GetCallerIdentity";
public static final String GET_CALLER_IDENTITY_VERSION = "2011-06-15";
private static final Aws4Signer signer = Aws4Signer.create();
private final SdkHttpFullRequest getCallerIdentityRequest;
private final AwsCredentialsProvider clientCredentialsProvider;
private final Region region;
public StsPreSigner(StsClient stsClient) {
this.clientCredentialsProvider = (AwsCredentialsProvider) stsClient.serviceClientConfiguration()
.credentialsProvider();
StsEndpointProvider endPointProvider = (StsEndpointProvider) stsClient.serviceClientConfiguration()
.endpointProvider().get();
StsEndpointParams stsEndpointParams = StsEndpointParams.builder()
.region(stsClient.serviceClientConfiguration().region()).build();
URI endpoint = endPointProvider.resolveEndpoint(stsEndpointParams).getNow(null).url();
region = stsClient.serviceClientConfiguration().region();
getCallerIdentityRequest = SdkHttpFullRequest.builder().method(SdkHttpMethod.GET).protocol(endpoint.getScheme())
.host(endpoint.getHost()).encodedPath("/").appendRawQueryParameter("Action", GET_CALLER_IDENTITY_ACTION)
.appendRawQueryParameter("Version", GET_CALLER_IDENTITY_VERSION).build();
}
public String getCallerIdentity() {
Aws4PresignerParams params = Aws4PresignerParams.builder()
.awsCredentials(this.clientCredentialsProvider.resolveCredentials())
.expirationTime(Instant.now().plus(10, ChronoUnit.MINUTES)).signingRegion(this.region)
.signingName(StsClient.SERVICE_NAME).build();
return signer.presign(getCallerIdentityRequest, params).getUri().toString();
}
}
@bpaquet
Copy link
Author

bpaquet commented Jan 22, 2025

This is not supported by the SDK, and it's not so easy :(

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment