Java 类com.amazonaws.services.securitytoken.AWSSecurityTokenServiceClient 实例源码

项目:herd    文件:MockStsOperationsImpl.java   
@Override
public AssumeRoleResult assumeRole(AWSSecurityTokenServiceClient awsSecurityTokenServiceClient, AssumeRoleRequest assumeRoleRequest)
{
    assertNotNull(assumeRoleRequest);

    if (assumeRoleRequest.getPolicy() != null && assumeRoleRequest.getPolicy().equals(MockAwsOperationsHelper.AMAZON_THROTTLING_EXCEPTION))
    {
        AmazonServiceException throttlingException = new AmazonServiceException("test throttling exception");
        throttlingException.setErrorCode("ThrottlingException");

        throw throttlingException;
    }

    AssumeRoleResult assumeRoleResult = new AssumeRoleResult();

    assumeRoleResult.setCredentials(new Credentials(MOCK_AWS_ASSUMED_ROLE_ACCESS_KEY, MOCK_AWS_ASSUMED_ROLE_SECRET_KEY, MOCK_AWS_ASSUMED_ROLE_SESSION_TOKEN,
        new Date(System.currentTimeMillis() + 1000 * assumeRoleRequest.getDurationSeconds())));

    return assumeRoleResult;
}
项目:service-block-samples    文件:LambdaCredentialsProvider.java   
/**
 * Creates a new session credential that is valid for 12 hours
 *
 * @return an authenticated {@link Credentials} for the new session token
 */
private Credentials getSessionCredentials() {
    // Create a new session with the user credentials for the service instance
    AWSSecurityTokenServiceClient stsClient =
            new AWSSecurityTokenServiceClient(new BasicAWSCredentials(
                    amazonProperties.getAws().getAccessKeyId(),
                    amazonProperties.getAws().getAccessKeySecret()));

    // Start a new session for managing a service instance's bucket
    GetSessionTokenRequest getSessionTokenRequest =
            new GetSessionTokenRequest().withDurationSeconds(43200);

    // Get the session token for the service instance's bucket
    sessionCredentials = stsClient.getSessionToken(getSessionTokenRequest).getCredentials();

    return sessionCredentials;
}
项目:aws-codebuild-jenkins-plugin    文件:CodeBuildCredentials.java   
@Override
public AWSCredentials getCredentials() {
    AWSCredentialsProvider credentialsProvider = AWSClientFactory.getBasicCredentialsOrDefaultChain(accessKey, secretKey);
    AWSCredentials initialCredentials = credentialsProvider.getCredentials();

    if (iamRoleArn.isEmpty()) {
        return initialCredentials;
    } else {
        AssumeRoleRequest assumeRequest = new AssumeRoleRequest()
                .withRoleArn(iamRoleArn)
                .withExternalId(externalId)
                .withDurationSeconds(3600)
                .withRoleSessionName("CodeBuild-Jenkins-Plugin");

        AssumeRoleResult assumeResult = new AWSSecurityTokenServiceClient(initialCredentials).assumeRole(assumeRequest);

        return new BasicSessionCredentials(
                assumeResult.getCredentials().getAccessKeyId(),
                assumeResult.getCredentials().getSecretAccessKey(),
                assumeResult.getCredentials().getSessionToken());
    }
}
项目:athenz    文件:InstanceAWSProvider.java   
AWSSecurityTokenServiceClient getInstanceClient(AWSAttestationData info) {

    String access = info.getAccess();
    if (access == null || access.isEmpty()) {
        LOGGER.error("getInstanceClient: No access key id available in instance document");
        return null;
    }

    String secret = info.getSecret();
    if (secret == null || secret.isEmpty()) {
        LOGGER.error("getInstanceClient: No secret access key available in instance document");
        return null;
    }

    String token = info.getToken();
    if (token == null || token.isEmpty()) {
        LOGGER.error("getInstanceClient: No token available in instance document");
        return null;
    }

    BasicSessionCredentials creds = new BasicSessionCredentials(access, secret, token);
    return new AWSSecurityTokenServiceClient(creds);
}
项目:fullstop    文件:ExamplePlugin.java   
private AmazonEC2Client getClientForAccount(final String accountId, final Region region) {
    final AWSSecurityTokenServiceClient stsClient = new AWSSecurityTokenServiceClient(new ProfileCredentialsProvider());

    final AssumeRoleRequest assumeRequest = new AssumeRoleRequest().withRoleArn(
            "arn:aws:iam::ACCOUNT_ID:role/fullstop-role")
                                                             .withDurationSeconds(3600).withRoleSessionName(
                    "fullstop-role");

    final AssumeRoleResult assumeResult = stsClient.assumeRole(assumeRequest);

    final BasicSessionCredentials temporaryCredentials = new BasicSessionCredentials(
            assumeResult.getCredentials()
                        .getAccessKeyId(), assumeResult.getCredentials().getSecretAccessKey(),
            assumeResult.getCredentials().getSessionToken());

    final AmazonEC2Client amazonEC2Client = new AmazonEC2Client(temporaryCredentials);
    amazonEC2Client.setRegion(region);

    return amazonEC2Client;
}
项目:aws-credentials-plugin    文件:AWSCredentialsImpl.java   
public AWSCredentials getCredentials() {
    AWSCredentials initialCredentials = new BasicAWSCredentials(accessKey, secretKey.getPlainText());

    if (StringUtils.isBlank(iamRoleArn)) {
        return initialCredentials;
    } else {
        // Handle the case of delegation to instance profile
        if (StringUtils.isBlank(accessKey) && StringUtils.isBlank(secretKey.getPlainText()) ) {
            initialCredentials = (new InstanceProfileCredentialsProvider()).getCredentials();
        }

        AssumeRoleRequest assumeRequest = createAssumeRoleRequest(iamRoleArn);

        AssumeRoleResult assumeResult = new AWSSecurityTokenServiceClient(initialCredentials).assumeRole(assumeRequest);

        return new BasicSessionCredentials(
                assumeResult.getCredentials().getAccessKeyId(),
                assumeResult.getCredentials().getSecretAccessKey(),
                assumeResult.getCredentials().getSessionToken());
    }
}
项目:jets3t-aws-roles    文件:AWSRoleSessionCredentials.java   
private void assumeRoleAndGetCredentials() {
  int defaultRequestedExpiryTimeInMinutes = jets3tProperties.getIntProperty("aws.session-credentials.expiry-time.to-be-requested", 60);
  com.amazonaws.auth.AWSCredentials awsCredentials = new BasicAWSCredentials(iamAccessKey, iamSecretKey);
  AWSSecurityTokenServiceClient stsClient =
          new AWSSecurityTokenServiceClient(awsCredentials);
  AssumeRoleRequest assumeRequest = new AssumeRoleRequest()
          .withRoleArn(roleToBeAssumed)
          .withDurationSeconds(defaultRequestedExpiryTimeInMinutes * 60)
          .withRoleSessionName(DEFAULT_SESSION_NAME);
  if(externalId != null) {
    assumeRequest = assumeRequest.withExternalId(externalId);
  }
  AssumeRoleResult assumeResult =
          stsClient.assumeRole(assumeRequest);
  this.accessKey = assumeResult.getCredentials().getAccessKeyId();
  this.secretKey = assumeResult.getCredentials().getSecretAccessKey();
  this.sessionToken = assumeResult.getCredentials().getSessionToken();
  this.expirationDate = assumeResult.getCredentials().getExpiration();
}
项目:spring-boot-starter-amazon-s3    文件:AmazonS3Template.java   
/**
 * Creates a new session credential that is valid for 12 hours
 *
 * @return an authenticated {@link Credentials} for the new session token
 */
private Credentials getSessionCredentials() {
    // Create a new session with the user credentials for the service instance
    AWSSecurityTokenServiceClient stsClient =
            new AWSSecurityTokenServiceClient(new BasicAWSCredentials(accessKeyId, accessKeySecret));

    // Start a new session for managing a service instance's bucket
    GetSessionTokenRequest getSessionTokenRequest =
            new GetSessionTokenRequest().withDurationSeconds(43200);

    // Get the session token for the service instance's bucket
    sessionCredentials = stsClient.getSessionToken(getSessionTokenRequest).getCredentials();

    return sessionCredentials;
}
项目:aws-codebuild-jenkins-plugin    文件:CodeBuildCredentials.java   
public FormValidation doCheckIamRoleArn(@QueryParameter("proxyHost") final String proxyHost,
                                        @QueryParameter("proxyPort") final String proxyPort,
                                        @QueryParameter("accessKey") final String accessKey,
                                        @QueryParameter("secretKey") final String secretKey,
                                        @QueryParameter("iamRoleArn") final String iamRoleArn,
                                        @QueryParameter("externalId") final String externalId) {

    if (accessKey.isEmpty() || secretKey.isEmpty()) {
        return FormValidation.error("AWS access and secret keys are required to use an IAM role for authorization");
    }

    if(iamRoleArn.isEmpty()) {
        return FormValidation.ok();
    }

    try {

        AWSCredentials initialCredentials = new BasicAWSCredentials(accessKey, secretKey);

        AssumeRoleRequest assumeRequest = new AssumeRoleRequest()
                .withRoleArn(iamRoleArn)
                .withExternalId(externalId)
                .withDurationSeconds(3600)
                .withRoleSessionName("jenkins-codebuild-plugin");

        new AWSSecurityTokenServiceClient(initialCredentials, getClientConfiguration(proxyHost, proxyPort)).assumeRole(assumeRequest);

    } catch (Exception e) {
        String errorMessage = e.getMessage();
        if(errorMessage.length() >= ERROR_MESSAGE_MAX_LENGTH) {
            errorMessage = errorMessage.substring(ERROR_MESSAGE_MAX_LENGTH);
        }
        return FormValidation.error("Authorization failed: " + errorMessage);
    }
    return FormValidation.ok("IAM role authorization successful.");
}
项目:cerberus-lifecycle-cli    文件:CerberusModule.java   
/**
 * Binds all the Amazon services used.
 */
@Override
protected void configure() {
    final Region region = Region.getRegion(Regions.fromName(regionName));
    bind(AmazonEC2.class).toInstance(createAmazonClientInstance(AmazonEC2Client.class, region));
    bind(AmazonCloudFormation.class).toInstance(createAmazonClientInstance(AmazonCloudFormationClient.class, region));
    bind(AmazonIdentityManagement.class).toInstance(createAmazonClientInstance(AmazonIdentityManagementClient.class, region));
    bind(AWSKMS.class).toInstance(createAmazonClientInstance(AWSKMSClient.class, region));
    bind(AmazonS3.class).toInstance(createAmazonClientInstance(AmazonS3Client.class, region));
    bind(AmazonAutoScaling.class).toInstance(createAmazonClientInstance(AmazonAutoScalingClient.class, region));
    bind(AWSSecurityTokenService.class).toInstance(createAmazonClientInstance(AWSSecurityTokenServiceClient.class, region));
    bind(AWSLambda.class).toInstance(createAmazonClientInstance(AWSLambdaClient.class, region));
    bind(AmazonSNS.class).toInstance(createAmazonClientInstance(AmazonSNSClient.class, region));
}
项目:athenz    文件:InstanceAWSProvider.java   
public boolean verifyInstanceIdentity(AWSAttestationData info, final String awsAccount) {

    GetCallerIdentityRequest req = new GetCallerIdentityRequest();

    try {
        AWSSecurityTokenServiceClient client = getInstanceClient(info);
        if (client == null) {
            LOGGER.error("verifyInstanceIdentity - unable to get AWS STS client object");
            return false;
        }

        GetCallerIdentityResult res = client.getCallerIdentity(req);
        if (res == null) {
            LOGGER.error("verifyInstanceIdentity - unable to get caller identity");
            return false;
        }

        String arn = "arn:aws:sts::" + awsAccount + ":assumed-role/" + info.getRole() + "/";
        if (!res.getArn().startsWith(arn)) {
            LOGGER.error("verifyInstanceIdentity - ARN mismatch - request: {} caller-idenity: {}",
                    arn, res.getArn());
            return false;
        }

        return true;

    } catch (Exception ex) {
        LOGGER.error("CloudStore: verifyInstanceIdentity - unable get caller identity: {}",
                ex.getMessage());
        return false;
    }
}
项目:athenz    文件:InstanceAWSProviderTest.java   
@Test
public void testVerifyInstanceIdentityNullIdentity() {
    MockInstanceAWSProvider provider = new MockInstanceAWSProvider();
    provider.setIdentitySuper(true);
    AWSSecurityTokenServiceClient mockClient = Mockito.mock(AWSSecurityTokenServiceClient.class);
    Mockito.when(mockClient.getCallerIdentity(ArgumentMatchers.any())).thenReturn(null);
    provider.setStsClient(mockClient);

    AWSAttestationData info = new AWSAttestationData();
    assertFalse(provider.verifyInstanceIdentity(info, "1234"));
}
项目:athenz    文件:InstanceAWSProviderTest.java   
@Test
public void testVerifyInstanceIdentityException() {
    MockInstanceAWSProvider provider = new MockInstanceAWSProvider();
    provider.setIdentitySuper(true);
    AWSSecurityTokenServiceClient mockClient = Mockito.mock(AWSSecurityTokenServiceClient.class);
    Mockito.when(mockClient.getCallerIdentity(ArgumentMatchers.any())).thenThrow(new ResourceException(101));
    provider.setStsClient(mockClient);

    AWSAttestationData info = new AWSAttestationData();
    assertFalse(provider.verifyInstanceIdentity(info, "1234"));
}
项目:athenz    文件:InstanceAWSProviderTest.java   
@Test
public void testVerifyInstanceIdentityARNMismatch() {
    MockInstanceAWSProvider provider = new MockInstanceAWSProvider();
    provider.setIdentitySuper(true);
    AWSSecurityTokenServiceClient mockClient = Mockito.mock(AWSSecurityTokenServiceClient.class);
    GetCallerIdentityResult result = Mockito.mock(GetCallerIdentityResult.class);
    Mockito.when(result.getArn()).thenReturn("arn:aws:sts::1235:assumed-role/athenz.service/athenz.service");
    Mockito.when(mockClient.getCallerIdentity(ArgumentMatchers.any())).thenReturn(result);
    provider.setStsClient(mockClient);

    AWSAttestationData info = new AWSAttestationData();
    info.setRole("athenz.service");
    assertFalse(provider.verifyInstanceIdentity(info, "1234"));
}
项目:athenz    文件:InstanceAWSProviderTest.java   
@Test
public void testVerifyInstanceIdentity() {
    MockInstanceAWSProvider provider = new MockInstanceAWSProvider();
    provider.setIdentitySuper(true);
    AWSSecurityTokenServiceClient mockClient = Mockito.mock(AWSSecurityTokenServiceClient.class);
    GetCallerIdentityResult result = Mockito.mock(GetCallerIdentityResult.class);
    Mockito.when(result.getArn()).thenReturn("arn:aws:sts::1234:assumed-role/athenz.service/athenz.service");
    Mockito.when(mockClient.getCallerIdentity(ArgumentMatchers.any())).thenReturn(result);
    provider.setStsClient(mockClient);

    AWSAttestationData info = new AWSAttestationData();
    info.setRole("athenz.service");
    assertTrue(provider.verifyInstanceIdentity(info, "1234"));
}
项目:athenz    文件:CloudStore.java   
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;
    }
项目:athenz    文件:MockCloudStore.java   
@Override
AWSSecurityTokenServiceClient getTokenServiceClient() {
    AWSSecurityTokenServiceClient client = Mockito.mock(AWSSecurityTokenServiceClient.class);
    Mockito.when(client.assumeRole(Mockito.any(AssumeRoleRequest.class))).thenReturn(assumeRoleResult);
    Mockito.when(client.getCallerIdentity(Mockito.any(GetCallerIdentityRequest.class))).thenReturn(callerIdentityResult);
    return client;
}
项目:herd    文件:StsDaoImpl.java   
/**
 * Returns a set of temporary security credentials (consisting of an access key ID, a secret access key, and a security token) that can be used to access
 * the specified AWS resource.
 *
 * @param sessionName the session name that will be associated with the temporary credentials. The session name must be the same for an initial set of
 * credentials and an extended set of credentials if credentials are to be refreshed. The session name also is used to identify the user in AWS logs so it
 * should be something unique and useful to identify the caller/use.
 * @param awsRoleArn the AWS ARN for the role required to provide access to the specified AWS resource
 * @param awsRoleDurationSeconds the duration, in seconds, of the role session. The value can range from 900 seconds (15 minutes) to 3600 seconds (1 hour).
 * @param policy the temporary policy to apply to this request
 *
 * @return the assumed session credentials
 */
@Override
public Credentials getTemporarySecurityCredentials(AwsParamsDto awsParamsDto, String sessionName, String awsRoleArn, int awsRoleDurationSeconds,
    Policy policy)
{
    // Construct a new AWS security token service client using the specified client configuration to access Amazon S3.
    // A credentials provider chain will be used that searches for credentials in this order:
    // - Environment Variables - AWS_ACCESS_KEY_ID and AWS_SECRET_KEY
    // - Java System Properties - aws.accessKeyId and aws.secretKey
    // - Instance Profile Credentials - delivered through the Amazon EC2 metadata service

    ClientConfiguration clientConfiguration = new ClientConfiguration().withRetryPolicy(retryPolicyFactory.getRetryPolicy());

    // Only set the proxy hostname and/or port if they're configured.
    if (StringUtils.isNotBlank(awsParamsDto.getHttpProxyHost()))
    {
        clientConfiguration.setProxyHost(awsParamsDto.getHttpProxyHost());
    }
    if (awsParamsDto.getHttpProxyPort() != null)
    {
        clientConfiguration.setProxyPort(awsParamsDto.getHttpProxyPort());
    }

    AWSSecurityTokenServiceClient awsSecurityTokenServiceClient = new AWSSecurityTokenServiceClient(clientConfiguration);

    // Create the request.
    AssumeRoleRequest assumeRoleRequest = new AssumeRoleRequest();
    assumeRoleRequest.setRoleSessionName(sessionName);
    assumeRoleRequest.setRoleArn(awsRoleArn);
    assumeRoleRequest.setDurationSeconds(awsRoleDurationSeconds);
    if (policy != null)
    {
        assumeRoleRequest.setPolicy(policy.toJson());
    }

    // Get the temporary security credentials.
    AssumeRoleResult assumeRoleResult = stsOperations.assumeRole(awsSecurityTokenServiceClient, assumeRoleRequest);
    return assumeRoleResult.getCredentials();
}
项目:aws-credentials-plugin    文件:AWSCredentialsImpl.java   
public AWSCredentials getCredentials(String mfaToken) {
    AWSCredentials initialCredentials = new BasicAWSCredentials(accessKey, secretKey.getPlainText());

    AssumeRoleRequest assumeRequest = createAssumeRoleRequest(iamRoleArn)
            .withSerialNumber(iamMfaSerialNumber)
            .withTokenCode(mfaToken);

    AssumeRoleResult assumeResult = new AWSSecurityTokenServiceClient(initialCredentials).assumeRole(assumeRequest);

    return new BasicSessionCredentials(
            assumeResult.getCredentials().getAccessKeyId(),
            assumeResult.getCredentials().getSecretAccessKey(),
            assumeResult.getCredentials().getSessionToken());
}
项目:aws-codedeploy-plugin    文件:AWSClients.java   
private static AWSCredentials getCredentials(String iamRole, String externalId) {
    if (isEmpty(iamRole)) return null;

    AWSSecurityTokenServiceClient sts = new AWSSecurityTokenServiceClient();

    int credsDuration = (int) (AWSCodeDeployPublisher.DEFAULT_TIMEOUT_SECONDS
                    * AWSCodeDeployPublisher.DEFAULT_POLLING_FREQUENCY_SECONDS);

    if (credsDuration > 3600) {
        credsDuration = 3600;
    }

    AssumeRoleResult assumeRoleResult = sts.assumeRole(new AssumeRoleRequest()
                    .withRoleArn(iamRole)
                    .withExternalId(externalId)
                    .withDurationSeconds(credsDuration)
                    .withRoleSessionName(AWSCodeDeployPublisher.ROLE_SESSION_NAME)
    );

    Credentials stsCredentials = assumeRoleResult.getCredentials();
    BasicSessionCredentials credentials = new BasicSessionCredentials(
            stsCredentials.getAccessKeyId(),
            stsCredentials.getSecretAccessKey(),
            stsCredentials.getSessionToken()
    );

    return credentials;
}
项目:cloudbreak    文件:AwsSessionCredentialClient.java   
public BasicSessionCredentials retrieveSessionCredentials(AwsCredentialView awsCredential) {
    LOGGER.debug("retrieving session credential");
    AWSSecurityTokenServiceClient client = awsSecurityTokenServiceClient();
    AssumeRoleRequest assumeRoleRequest = new AssumeRoleRequest()
            .withDurationSeconds(DEFAULT_SESSION_CREDENTIALS_DURATION)
            .withExternalId(externalId)
            .withRoleArn(awsCredential.getRoleArn())
            .withRoleSessionName("hadoop-provisioning");
    AssumeRoleResult result = client.assumeRole(assumeRoleRequest);
    return new BasicSessionCredentials(
            result.getCredentials().getAccessKeyId(),
            result.getCredentials().getSecretAccessKey(),
            result.getCredentials().getSessionToken());
}
项目:cloudbreak    文件:AwsSessionCredentialClient.java   
private AWSSecurityTokenServiceClient awsSecurityTokenServiceClient() {
    if (!awsEnvironmentVariableChecker.isAwsAccessKeyAvailable() || !awsEnvironmentVariableChecker.isAwsSecretAccessKeyAvailable()) {
        InstanceProfileCredentialsProvider instanceProfileCredentialsProvider = new InstanceProfileCredentialsProvider();
        LOGGER.info("AWSSecurityTokenServiceClient will use aws metadata because environment variables are undefined");
        return new AWSSecurityTokenServiceClient(instanceProfileCredentialsProvider);
    } else {
        LOGGER.info("AWSSecurityTokenServiceClient will use environment variables");
        return new AWSSecurityTokenServiceClient();
    }
}
项目:athenz    文件:MockInstanceAWSProvider.java   
void setStsClient(AWSSecurityTokenServiceClient client) {
    stsClient = client;
}
项目:athenz    文件:MockInstanceAWSProvider.java   
@Override
public AWSSecurityTokenServiceClient getInstanceClient(AWSAttestationData info) {
    return stsClient != null ? stsClient : super.getInstanceClient(info);
}
项目:athenz    文件:MockInstanceAWSECSProvider.java   
void setStsClient(AWSSecurityTokenServiceClient client) {
    stsClient = client;
}
项目:athenz    文件:MockInstanceAWSECSProvider.java   
@Override
public AWSSecurityTokenServiceClient getInstanceClient(AWSAttestationData info) {
    return stsClient != null ? stsClient : super.getInstanceClient(info);
}
项目:athenz    文件:CloudStore.java   
AWSSecurityTokenServiceClient getTokenServiceClient() {
    return new AWSSecurityTokenServiceClient(credentials);
}
项目:herd    文件:StsOperationsImpl.java   
@Override
public AssumeRoleResult assumeRole(AWSSecurityTokenServiceClient awsSecurityTokenServiceClient, AssumeRoleRequest assumeRoleRequest)
{
    return awsSecurityTokenServiceClient.assumeRole(assumeRoleRequest);
}
项目:herd    文件:StsDaoTest.java   
@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);
}
项目:herd    文件:StsDaoTest.java   
@Test
public void testGetTemporarySecurityCredentialsMissingOptionalParameters()
{
    // Create an AWS parameters DTO without proxy settings.
    AwsParamsDto awsParamsDto = new AwsParamsDto();

    // Specify the duration, in seconds, of the role session.
    int awsRoleDurationSeconds = INTEGER_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).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. Please note that we do not specify an IAM policy.
    Credentials result = stsDaoImpl.getTemporarySecurityCredentials(awsParamsDto, SESSION_NAME, AWS_ROLE_ARN, awsRoleDurationSeconds, null);

    // Verify the external calls.
    verify(retryPolicyFactory).getRetryPolicy();
    verify(stsOperations).assumeRole(any(AWSSecurityTokenServiceClient.class), eq(assumeRoleRequest));
    verifyNoMoreInteractionsHelper();

    // Validate the returned object.
    assertEquals(credentials, result);
}
项目:reinvent2013-mobile-photo-share    文件:TemporaryCredentialManagement.java   
public TemporaryCredentialManagement() {
    BasicAWSCredentials creds = new BasicAWSCredentials(Configuration.AWS_ACCESS_KEY_ID,
            Configuration.AWS_SECRET_KEY);
    sts = new AWSSecurityTokenServiceClient(creds);
}
项目:reinvent2013-mobile-photo-share    文件:TemporaryCredentialManagement.java   
public TemporaryCredentialManagement() {
    BasicAWSCredentials creds = new BasicAWSCredentials(Configuration.AWS_ACCESS_KEY_ID,
            Configuration.AWS_SECRET_KEY);
    sts = new AWSSecurityTokenServiceClient(creds);
}
项目:herd    文件:StsOperations.java   
/**
 * Returns a set of temporary security credentials (consisting of an access key ID, a secret access key, and a security token) that can be used to access
 * the specified AWS resource.
 *
 * @param awsSecurityTokenServiceClient the client for accessing the AWS Security Token Service
 * @param assumeRoleRequest the assume role request
 *
 * @return the response from the AssumeRole service method, as returned by AWS Security Token Service
 */
public AssumeRoleResult assumeRole(AWSSecurityTokenServiceClient awsSecurityTokenServiceClient, AssumeRoleRequest assumeRoleRequest);