Java 类com.amazonaws.services.securitytoken.model.AssumeRoleResult 实例源码

项目: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;
}
项目: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    文件:CloudStoreTest.java   
@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.setAssumeAWSRole(true);

    AWSTemporaryCredentials awsCreds = cloudStore.assumeAWSRole("account", "syncer", "athenz.syncer");
    assertNotNull(awsCreds);
    assertEquals(awsCreds.getAccessKeyId(), "accesskeyid");
    assertEquals(awsCreds.getSessionToken(), "sessiontoken");
    assertEquals(awsCreds.getSecretAccessKey(), "secretaccesskey");
}
项目: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();
}
项目:datamung    文件:AssumedSessionCredentialsFactoryBean.java   
private void create()
{
    AssumeRoleResult result =
        sts.assumeRole( new AssumeRoleRequest().withRoleArn( assumedRoleArn ).withExternalId( AgentConfig.ROLE_EXTERNAL_ID ).withRoleSessionName( "rs-"
                                                                                                                                                      + RandomStringUtils.randomAlphabetic( 8 ) ) );

    synchronized ( this )
    {
        expirationDate =
            result.getCredentials().getExpiration().getTime();
        creds =
            new BasicSessionCredentials(
                                         result.getCredentials().getAccessKeyId(),
                                         result.getCredentials().getSecretAccessKey(),
                                         result.getCredentials().getSessionToken() );
    }
}
项目: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;
    }
项目: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());
}
项目:strongbox    文件:ProfileCredentialProvider.java   
/**
 * Resolve AWS credentials based on MFA/Assume role
 *
 * We will assume that if mfa_serial is defined, then role_arn and source_profile also has to be specified.
 *
 * Please note that Strongbox differ from the AWS CLI in the following:
 * AWS CLI: 'Note that configuration variables for using IAM roles can only be in the AWS CLI config file.'
 * Strongbox: '--assume-role' can be specified explicitly
 *
 * https://docs.aws.amazon.com/cli/latest/topic/config-vars.html#using-aws-iam-roles
 */
private AWSCredentials assumeRole(ClientConfiguration clientConfiguration,
                                  ConfigProviderChain configProvider,
                                  ProfileIdentifier profile,
                                  RoleARN roleToAssume) {

    Optional<ProfileIdentifier> sourceProfile = configProvider.getSourceProfile(profile);
    if (!sourceProfile.isPresent()) {
        throw new IllegalStateException(String.format("'%s' must be specified when using '%s' for profile '%s'",
                AWSConfigPropertyKey.SOURCE_PROFILE,
                AWSConfigPropertyKey.ROLE_ARN,
                profile.name));
    }

    SessionCache sessionCache = new SessionCache(profile, roleToAssume);
    Optional<BasicSessionCredentials> cachedCredentials = sessionCache.load();

    if (cachedCredentials.isPresent()) {
        return cachedCredentials.get();
    } else {
        AWSCredentialsProvider staticCredentialsProvider = new AWSStaticCredentialsProvider(getStaticCredentials(configProvider, sourceProfile.get()));

        AWSSecurityTokenService client = AWSSecurityTokenServiceClientBuilder.standard()
                .withCredentials(staticCredentialsProvider)
                .withClientConfiguration(transformAndVerifyOrThrow(clientConfiguration))
                .withRegion(RegionResolver.getRegion())
                .build();

        String sessionId = String.format("strongbox-cli-session-%s", ZonedDateTime.now().toEpochSecond());

        AssumeRoleRequest request = new AssumeRoleRequest();
        request.withRoleArn(roleToAssume.toArn())
                .withRoleSessionName(sessionId);

        Optional<String> mfaSerial = configProvider.getMFASerial(profile);
        if (mfaSerial.isPresent()) {
            MFAToken mfaToken = mfaTokenSupplier.get();

            request.withSerialNumber(mfaSerial.get())
                    .withTokenCode(mfaToken.value);
        }

        AssumeRoleResult result = client.assumeRole(request);
        Credentials credentials = result.getCredentials();

        BasicSessionCredentials basicSessionCredentials = new BasicSessionCredentials(credentials.getAccessKeyId(), credentials.getSecretAccessKey(), credentials.getSessionToken());

        sessionCache.save(result.getAssumedRoleUser(),
                basicSessionCredentials,
                ZonedDateTime.ofInstant(credentials.getExpiration().toInstant(), ZoneId.of("UTC")));

        return basicSessionCredentials;
    }
}
项目:athenz    文件:MockCloudStore.java   
void setAssumeRoleResult(AssumeRoleResult assumeRoleResult) {
    this.assumeRoleResult = assumeRoleResult;
}
项目: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);
}
项目: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);