Java Code Examples for com.amazonaws.services.securitytoken.AWSSecurityTokenService#assumeRole()

The following examples show how to use com.amazonaws.services.securitytoken.AWSSecurityTokenService#assumeRole() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AWSClientManagerImpl.java    From pacbot with Apache License 2.0 7 votes vote down vote up
/**
 * Gets the temp credentials using cred provider.
 *
 * @param roleArnWithAdequateAccess
 *            the role arn with adequate access
 * @param region
 *            the region
 * @param acp
 *            the acp
 * @param validForSeconds
 *            the valid for seconds
 * @return the temp credentials using cred provider
 */
private BasicSessionCredentials getTempCredentialsUsingCredProvider(String roleArnWithAdequateAccess,
        Regions region, AWSCredentialsProvider acp, Integer validForSeconds) {
    if (null == region) { // cloud trail case
        region = Regions.DEFAULT_REGION;
    }
    AWSSecurityTokenServiceClientBuilder stsBuilder = AWSSecurityTokenServiceClientBuilder.standard()
            .withCredentials(acp).withRegion(region);
    AWSSecurityTokenService sts = stsBuilder.build();
    AssumeRoleRequest assumeRequest = new AssumeRoleRequest().withRoleArn(roleArnWithAdequateAccess)
            .withDurationSeconds(validForSeconds).withRoleSessionName(PacmanSdkConstants.DEFAULT_SESSION_NAME);
    logger.debug("assume role request " + assumeRequest.toString());
    AssumeRoleResult assumeResult = sts.assumeRole(assumeRequest);
    logger.debug("assume role response " + assumeResult.toString());
    BasicSessionCredentials temporaryCredentials = new BasicSessionCredentials(assumeResult.getCredentials()
            .getAccessKeyId(), assumeResult.getCredentials().getSecretAccessKey(), assumeResult.getCredentials()
            .getSessionToken());

    return temporaryCredentials;
}
 
Example 2
Source File: CredentialProvider.java    From pacbot with Apache License 2.0 7 votes vote down vote up
/**
 * Gets the credentials.
 *
 * @param account the account
 * @param roleName the role name
 * @return the credentials
 */
public  BasicSessionCredentials getCredentials(String account,String roleName){
	
	BasicSessionCredentials baseAccntCreds = getBaseAccountCredentials(baseAccount,baseRegion,roleName);
	if(baseAccount.equals(account)){
		return baseAccntCreds;
	}
	AWSSecurityTokenServiceClientBuilder stsBuilder = AWSSecurityTokenServiceClientBuilder.standard().withCredentials( new AWSStaticCredentialsProvider(baseAccntCreds)).withRegion(baseRegion);
	AWSSecurityTokenService stsClient = stsBuilder.build();
    AssumeRoleRequest assumeRequest = new AssumeRoleRequest().withRoleArn(getRoleArn(account,roleName)).withRoleSessionName("pic-ro-"+account);
    AssumeRoleResult assumeResult = stsClient.assumeRole(assumeRequest);
    return  new BasicSessionCredentials(
            assumeResult.getCredentials()
                        .getAccessKeyId(), assumeResult.getCredentials().getSecretAccessKey(),
            assumeResult.getCredentials().getSessionToken());
}
 
Example 3
Source File: CredentialProvider.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the credentials.
 *
 * @param account the account
 * @param roleName the role name
 * @return the credentials
 */
public  BasicSessionCredentials getCredentials(String account,String roleName){
	BasicSessionCredentials baseAccntCreds = getBaseAccountCredentials(roleName);
	if(baseAccount.equals(account)){
		return baseAccntCreds;
	}
	AWSSecurityTokenServiceClientBuilder stsBuilder = AWSSecurityTokenServiceClientBuilder.standard().withCredentials( new AWSStaticCredentialsProvider(baseAccntCreds)).withRegion(baseRegion);
	AWSSecurityTokenService stsClient = stsBuilder.build();
    AssumeRoleRequest assumeRequest = new AssumeRoleRequest().withRoleArn(getRoleArn(account,roleName)).withRoleSessionName("pic-ro-"+account);
    AssumeRoleResult assumeResult = stsClient.assumeRole(assumeRequest);
    return  new BasicSessionCredentials(
            assumeResult.getCredentials()
                        .getAccessKeyId(), assumeResult.getCredentials().getSecretAccessKey(),
            assumeResult.getCredentials().getSessionToken());
}
 
Example 4
Source File: AssumedRole.java    From pipeline-aws-plugin with Apache License 2.0 6 votes vote down vote up
private AssumedRole assumeRole(final AWSSecurityTokenService sts) {
	final AssumeRoleRequest assumeRoleRequest = new AssumeRoleRequest().withRoleArn(this.roleArn)
					.withRoleSessionName(this.sessionName)
					.withDurationSeconds(this.durationInSeconds);
	Optional.ofNullable(this.externalId).ifPresent(assumeRoleRequest::setExternalId);
	Optional.ofNullable(this.policy).ifPresent(assumeRoleRequest::withPolicy);
	AssumeRoleResult assumeRoleResult = sts.assumeRole(assumeRoleRequest);
	return new AssumedRole(assumeRoleResult.getCredentials(), assumeRoleResult.getAssumedRoleUser());
}
 
Example 5
Source File: ProfileCredentialProvider.java    From strongbox with Apache License 2.0 5 votes vote down vote up
/**
 * 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;
    }
}