use of com.amazonaws.services.securitytoken.model.AssumeRoleResult in project athenz by yahoo.
the class CloudStore method assumeAWSRole.
public AWSTemporaryCredentials assumeAWSRole(String account, String roleName, String principal, Integer durationSeconds, String externalId, StringBuilder errorMessage) {
if (!awsEnabled) {
throw new ResourceException(ResourceException.INTERNAL_SERVER_ERROR, "AWS Support not enabled");
}
// first check to see if we already have the temp creds cached
final String cacheKey = getCacheKey(account, roleName, principal, durationSeconds, externalId);
AWSTemporaryCredentials tempCreds = getCachedCreds(cacheKey, durationSeconds);
if (tempCreds != null) {
return tempCreds;
}
if (isFailedTempCredsRequest(cacheKey)) {
errorMessage.append("Cached invalid request. Retry operation after ").append(invalidCacheTimeout).append(" seconds.");
return null;
}
AssumeRoleRequest req = getAssumeRoleRequest(account, roleName, durationSeconds, externalId);
try {
AWSSecurityTokenService client = getTokenServiceClient();
AssumeRoleResult res = client.assumeRole(req);
Credentials awsCreds = res.getCredentials();
tempCreds = new AWSTemporaryCredentials().setAccessKeyId(awsCreds.getAccessKeyId()).setSecretAccessKey(awsCreds.getSecretAccessKey()).setSessionToken(awsCreds.getSessionToken()).setExpiration(Timestamp.fromMillis(awsCreds.getExpiration().getTime()));
} catch (AmazonServiceException ex) {
LOGGER.error("CloudStore: assumeAWSRole - unable to assume role: {}, error: {}, status code: {}", req.getRoleArn(), ex.getMessage(), ex.getStatusCode());
if (ex.getStatusCode() == ResourceException.FORBIDDEN) {
putInvalidCacheCreds(cacheKey);
}
errorMessage.append(ex.getErrorMessage());
return null;
} catch (Exception ex) {
LOGGER.error("CloudStore: assumeAWSRole - unable to assume role: {}, error: {}", req.getRoleArn(), ex.getMessage());
errorMessage.append(ex.getMessage());
return null;
}
putCacheCreds(cacheKey, tempCreds);
return tempCreds;
}
use of com.amazonaws.services.securitytoken.model.AssumeRoleResult in project athenz by yahoo.
the class CloudStore method assumeAWSRole.
public AWSTemporaryCredentials assumeAWSRole(String account, String roleName, String principal) {
if (!awsEnabled) {
throw new ResourceException(ResourceException.INTERNAL_SERVER_ERROR, "AWS Support not enabled");
}
AssumeRoleRequest req = getAssumeRoleRequest(account, roleName, principal);
AWSTemporaryCredentials tempCreds = null;
try {
AWSSecurityTokenServiceClient client = getTokenServiceClient();
AssumeRoleResult res = client.assumeRole(req);
Credentials awsCreds = res.getCredentials();
tempCreds = new AWSTemporaryCredentials().setAccessKeyId(awsCreds.getAccessKeyId()).setSecretAccessKey(awsCreds.getSecretAccessKey()).setSessionToken(awsCreds.getSessionToken()).setExpiration(Timestamp.fromMillis(awsCreds.getExpiration().getTime()));
} catch (Exception ex) {
LOGGER.error("CloudStore: assumeAWSRole - unable to assume role: " + ex.getMessage());
return null;
}
return tempCreds;
}
use of com.amazonaws.services.securitytoken.model.AssumeRoleResult in project herd by FINRAOS.
the class StsDaoTest method testGetTemporarySecurityCredentials.
@Test
public void testGetTemporarySecurityCredentials() {
// Create an AWS parameters DTO with proxy settings.
AwsParamsDto awsParamsDto = new AwsParamsDto();
awsParamsDto.setHttpProxyHost(HTTP_PROXY_HOST);
awsParamsDto.setHttpProxyPort(HTTP_PROXY_PORT);
// Specify the duration, in seconds, of the role session.
int awsRoleDurationSeconds = INTEGER_VALUE;
// Create an IAM policy.
Policy policy = new Policy(STRING_VALUE);
// Create a retry policy.
RetryPolicy retryPolicy = new RetryPolicy(PredefinedRetryPolicies.DEFAULT_RETRY_CONDITION, PredefinedRetryPolicies.DEFAULT_BACKOFF_STRATEGY, INTEGER_VALUE, true);
// Create the expected assume role request.
AssumeRoleRequest assumeRoleRequest = new AssumeRoleRequest().withRoleArn(AWS_ROLE_ARN).withRoleSessionName(SESSION_NAME).withPolicy(policy.toJson()).withDurationSeconds(awsRoleDurationSeconds);
// Create AWS credentials for API authentication.
Credentials credentials = new Credentials();
credentials.setAccessKeyId(AWS_ASSUMED_ROLE_ACCESS_KEY);
credentials.setSecretAccessKey(AWS_ASSUMED_ROLE_SECRET_KEY);
credentials.setSessionToken(AWS_ASSUMED_ROLE_SESSION_TOKEN);
// Create an assume role result.
AssumeRoleResult assumeRoleResult = new AssumeRoleResult();
assumeRoleResult.setCredentials(credentials);
// Mock the external calls.
when(retryPolicyFactory.getRetryPolicy()).thenReturn(retryPolicy);
when(stsOperations.assumeRole(any(AWSSecurityTokenServiceClient.class), eq(assumeRoleRequest))).thenReturn(assumeRoleResult);
// Call the method under test.
Credentials result = stsDaoImpl.getTemporarySecurityCredentials(awsParamsDto, SESSION_NAME, AWS_ROLE_ARN, awsRoleDurationSeconds, policy);
// Verify the external calls.
verify(retryPolicyFactory).getRetryPolicy();
verify(stsOperations).assumeRole(any(AWSSecurityTokenServiceClient.class), eq(assumeRoleRequest));
verifyNoMoreInteractionsHelper();
// Validate the returned object.
assertEquals(credentials, result);
}
use of com.amazonaws.services.securitytoken.model.AssumeRoleResult in project aws-doc-sdk-examples by awsdocs.
the class MakingRequestsWithIAMTempCredentials method main.
public static void main(String[] args) {
String clientRegion = "*** Client region ***";
String roleARN = "*** ARN for role to be assumed ***";
String roleSessionName = "*** Role session name ***";
String bucketName = "*** Bucket name ***";
try {
// Creating the STS client is part of your trusted code. It has
// the security credentials you use to obtain temporary security credentials.
AWSSecurityTokenService stsClient = AWSSecurityTokenServiceClientBuilder.standard().withCredentials(new ProfileCredentialsProvider()).withRegion(clientRegion).build();
// Obtain credentials for the IAM role. Note that you cannot assume the role of an AWS root account;
// Amazon S3 will deny access. You must use credentials for an IAM user or an IAM role.
AssumeRoleRequest roleRequest = new AssumeRoleRequest().withRoleArn(roleARN).withRoleSessionName(roleSessionName);
AssumeRoleResult roleResponse = stsClient.assumeRole(roleRequest);
Credentials sessionCredentials = roleResponse.getCredentials();
// Create a BasicSessionCredentials object that contains the credentials you just retrieved.
BasicSessionCredentials awsCredentials = new BasicSessionCredentials(sessionCredentials.getAccessKeyId(), sessionCredentials.getSecretAccessKey(), sessionCredentials.getSessionToken());
// Provide temporary security credentials so that the Amazon S3 client
// can send authenticated requests to Amazon S3. You create the client
// using the sessionCredentials object.
AmazonS3 s3Client = AmazonS3ClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(awsCredentials)).withRegion(clientRegion).build();
// Verify that assuming the role worked and the permissions are set correctly
// by getting a set of object keys from the bucket.
ObjectListing objects = s3Client.listObjects(bucketName);
System.out.println("No. of Objects: " + objects.getObjectSummaries().size());
} catch (AmazonServiceException e) {
// The call was transmitted successfully, but Amazon S3 couldn't process
// it, so it returned an error response.
e.printStackTrace();
} catch (SdkClientException e) {
// Amazon S3 couldn't be contacted for a response, or the client
// couldn't parse the response from Amazon S3.
e.printStackTrace();
}
}
use of com.amazonaws.services.securitytoken.model.AssumeRoleResult in project athenz by yahoo.
the class CloudStoreTest method testAssumeAWSRole.
@Test
public void testAssumeAWSRole() {
MockCloudStore cloudStore = new MockCloudStore();
cloudStore.awsEnabled = true;
AssumeRoleResult mockResult = Mockito.mock(AssumeRoleResult.class);
Credentials creds = Mockito.mock(Credentials.class);
Mockito.when(creds.getAccessKeyId()).thenReturn("accesskeyid");
Mockito.when(creds.getSecretAccessKey()).thenReturn("secretaccesskey");
Mockito.when(creds.getSessionToken()).thenReturn("sessiontoken");
Mockito.when(creds.getExpiration()).thenReturn(new Date());
Mockito.when(mockResult.getCredentials()).thenReturn(creds);
cloudStore.setAssumeRoleResult(mockResult);
cloudStore.setReturnSuperAWSRole(true);
StringBuilder errorMessage = new StringBuilder();
AWSTemporaryCredentials awsCreds = cloudStore.assumeAWSRole("account", "syncer", "athenz.syncer", null, null, errorMessage);
assertNotNull(awsCreds);
assertEquals(awsCreds.getAccessKeyId(), "accesskeyid");
assertEquals(awsCreds.getSessionToken(), "sessiontoken");
assertEquals(awsCreds.getSecretAccessKey(), "secretaccesskey");
cloudStore.close();
}
Aggregations