Example usage for com.amazonaws.services.securitytoken.model AssumeRoleResult getCredentials

List of usage examples for com.amazonaws.services.securitytoken.model AssumeRoleResult getCredentials

Introduction

In this page you can find the example usage for com.amazonaws.services.securitytoken.model AssumeRoleResult getCredentials.

Prototype


public Credentials getCredentials() 

Source Link

Document

The temporary security credentials, which include an access key ID, a secret access key, and a security (or session) token.

Usage

From source file:CodeBuildCredentials.java

License:Open Source License

@Override
public void refresh() {
    if (!iamRoleArn.isEmpty()) {
        if (!haveCredentialsExpired()) {
            return;
        }/*from   w  w w. j  ava2 s .  c  o  m*/

        AWSCredentialsProvider credentialsProvider = AWSClientFactory
                .getBasicCredentialsOrDefaultChain(accessKey, secretKey);
        AWSCredentials credentials = credentialsProvider.getCredentials();

        AssumeRoleRequest assumeRequest = new AssumeRoleRequest().withRoleArn(iamRoleArn)
                .withExternalId(externalId).withDurationSeconds(3600)
                .withRoleSessionName("CodeBuild-Jenkins-Plugin");

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

        roleCredentials = assumeResult.getCredentials();
    }
}

From source file:awslabs.lab41.SolutionCode.java

License:Open Source License

@Override
public Credentials appMode_AssumeRole(AWSSecurityTokenServiceClient stsClient, String roleArn,
        String roleSessionName) {
    Credentials credentials;//from w  w w  . j ava2s  .  c om

    //  Construct an AssumeRoleRequest object using the provided role ARN and role session name.
    AssumeRoleRequest assumeRoleRequest = new AssumeRoleRequest().withRoleSessionName(roleSessionName)
            .withRoleArn(roleArn);

    //  Submit the requestusing the assumeRole method of the stsClient object. 
    AssumeRoleResult assumeRoleResult = stsClient.assumeRole(assumeRoleRequest);
    //  Return the credentials from the request result.
    credentials = assumeRoleResult.getCredentials();
    return credentials;
}

From source file:com.cloudbees.jenkins.plugins.awscredentials.AWSCredentialsImpl.java

License:Open Source License

public AWSCredentials getCredentials() {
    AWSCredentials initialCredentials = new BasicAWSCredentials(accessKey, secretKey.getPlainText());

    if (StringUtils.isBlank(iamRoleArn)) {
        return initialCredentials;
    } else {/*from  ww w. jav a 2s .  co m*/
        // Check for available region from the SDK, otherwise specify default
        String clientRegion = null;
        DefaultAwsRegionProviderChain sdkRegionLookup = new DefaultAwsRegionProviderChain();
        try {
            clientRegion = sdkRegionLookup.getRegion();
        } catch (com.amazonaws.SdkClientException e) {
            LOGGER.log(Level.WARNING, "Could not find default region using SDK lookup.", e);
        }
        if (clientRegion == null) {
            clientRegion = Regions.DEFAULT_REGION.getName();
        }

        AWSSecurityTokenService client;
        // Handle the case of delegation to instance profile
        if (StringUtils.isBlank(accessKey) && StringUtils.isBlank(secretKey.getPlainText())) {
            client = AWSSecurityTokenServiceClientBuilder.standard().withRegion(clientRegion).build();
        } else {
            client = AWSSecurityTokenServiceClientBuilder.standard()
                    .withCredentials(new AWSStaticCredentialsProvider(initialCredentials))
                    .withRegion(clientRegion).build();
        }

        AssumeRoleRequest assumeRequest = createAssumeRoleRequest(iamRoleArn)
                .withDurationSeconds(this.getStsTokenDuration());

        AssumeRoleResult assumeResult = client.assumeRole(assumeRequest);

        return new BasicSessionCredentials(assumeResult.getCredentials().getAccessKeyId(),
                assumeResult.getCredentials().getSecretAccessKey(),
                assumeResult.getCredentials().getSessionToken());
    }
}

From source file:com.cloudbees.jenkins.plugins.awscredentials.AWSCredentialsImpl.java

License:Open Source License

public AWSCredentials getCredentials(String mfaToken) {
    AWSCredentials initialCredentials = new BasicAWSCredentials(accessKey, secretKey.getPlainText());

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

    AssumeRoleResult assumeResult = new AWSSecurityTokenServiceClient(initialCredentials)
            .assumeRole(assumeRequest);/*from ww w.j a v  a  2 s.c  o m*/

    return new BasicSessionCredentials(assumeResult.getCredentials().getAccessKeyId(),
            assumeResult.getCredentials().getSecretAccessKey(),
            assumeResult.getCredentials().getSessionToken());
}

From source file:com.dtolabs.rundeck.plugin.resources.ec2.EC2ResourceModelSource.java

License:Apache License

private void initialize() {
    final ArrayList<String> params = new ArrayList<String>();
    if (null != filterParams) {
        Collections.addAll(params, filterParams.split(";"));
    }//from w  w w  .j  ava 2  s.c o  m
    loadMapping();
    if (this.credentials == null && assumeRoleArn != null) {
        AWSSecurityTokenServiceClient sts_client = new AWSSecurityTokenServiceClient();
        //        sts_client.setEndpoint("sts-endpoint.amazonaws.com");
        AssumeRoleRequest assumeRoleRequest = new AssumeRoleRequest();
        assumeRoleRequest.setRoleArn(assumeRoleArn);
        assumeRoleRequest.setRoleSessionName("RundeckEC2ResourceModelSourceSession");
        AssumeRoleResult assumeRoleResult = sts_client.assumeRole(assumeRoleRequest);
        Credentials assumeCredentials = assumeRoleResult.getCredentials();
        credentials = new BasicSessionCredentials(assumeCredentials.getAccessKeyId(),
                assumeCredentials.getSecretAccessKey(), assumeCredentials.getSessionToken());
    }

    mapper = new InstanceToNodeMapper(this.credentials, mapping, clientConfiguration);
    mapper.setFilterParams(params);
    mapper.setEndpoint(endpoint);
    mapper.setRunningStateOnly(runningOnly);
}

From source file:com.jaspersoft.jasperserver.api.engine.jasperreports.util.AwsCredentialUtil.java

License:Open Source License

public static AWSCredentials getAWSCredentials(String awsAccessKey, String awsSecretKey, String roleARN) {
    AWSCredentials awsCredentials;// ww w .j a  va2 s.co  m
    if (isNotEmpty(awsAccessKey) && isNotEmpty(awsSecretKey)) {
        awsCredentials = new BasicAWSCredentials(awsAccessKey.trim(), awsSecretKey.trim());

        // Use user long-term credentials to call the
        // AWS Security Token Service (STS) AssumeRole API, specifying
        // the ARN for the role -RO-role in amazon account.
        if (isNotEmpty(roleARN)) {
            AWSSecurityTokenServiceClient stsClient = new AWSSecurityTokenServiceClient(awsCredentials);

            AssumeRoleRequest assumeRequest = new AssumeRoleRequest().withRoleArn(roleARN.trim())
                    .withRoleSessionName("JRSRequest");

            AssumeRoleResult assumeResult = null;
            try {
                assumeResult = stsClient.assumeRole(assumeRequest);
            } catch (Exception ex) {
                logger.error(ex);
                throw new JSShowOnlyErrorMessage(ex.getMessage());
            }

            // AssumeRole returns temporary security credentials for
            // the IAM role.
            awsCredentials = new BasicSessionCredentials(assumeResult.getCredentials().getAccessKeyId(),
                    assumeResult.getCredentials().getSecretAccessKey(),
                    assumeResult.getCredentials().getSessionToken());
        }
    } else {
        //Try getting Ec2 instance credentials.
        AWSCredentialsProvider instanceCredentialsProvider = new DefaultAWSCredentialsProviderChain();
        try {
            awsCredentials = instanceCredentialsProvider.getCredentials();
        } catch (Exception ex) {
            ApplicationContext ctx = StaticApplicationContext.getApplicationContext();
            MessageSource message = ctx.getBean("messageSource", MessageSource.class);

            logger.error("Exception loading default JRS instance credentials", ex);
            throw new JSShowOnlyErrorMessage(
                    message.getMessage("aws.exception.datasource.load.default.credentials", null,
                            LocaleContextHolder.getLocale()));
        }
    }
    return awsCredentials;
}

From source file:com.netflix.eureka.aws.AwsAsgUtil.java

License:Apache License

private Credentials initializeStsSession(String asgAccount) {
    AWSSecurityTokenService sts = new AWSSecurityTokenServiceClient(new InstanceProfileCredentialsProvider());
    String region = clientConfig.getRegion();
    if (!region.equals("us-east-1")) {
        sts.setEndpoint("sts." + region + ".amazonaws.com");
    }/*from   ww  w  . j a va2s. c om*/

    String roleName = serverConfig.getListAutoScalingGroupsRoleName();
    String roleArn = "arn:aws:iam::" + asgAccount + ":role/" + roleName;

    AssumeRoleResult assumeRoleResult = sts.assumeRole(
            new AssumeRoleRequest().withRoleArn(roleArn).withRoleSessionName("sts-session-" + asgAccount));

    return assumeRoleResult.getCredentials();
}

From source file:com.netflix.eureka.util.AwsAsgUtil.java

License:Apache License

private Credentials initializeStsSession(String asgAccount) {
    AWSSecurityTokenService sts = new AWSSecurityTokenServiceClient(new InstanceProfileCredentialsProvider());
    String region = DiscoveryManager.getInstance().getEurekaClientConfig().getRegion();
    if (!region.equals("us-east-1")) {
        sts.setEndpoint("sts." + region + ".amazonaws.com");
    }//from   w  ww. j av a  2 s.c o m

    String roleName = EurekaServerConfigurationManager.getInstance().getConfiguration()
            .getListAutoScalingGroupsRoleName();

    String roleArn = "arn:aws:iam::" + asgAccount + ":role/" + roleName;

    AssumeRoleResult assumeRoleResult = sts.assumeRole(
            new AssumeRoleRequest().withRoleArn(roleArn).withRoleSessionName("sts-session-" + asgAccount));

    return assumeRoleResult.getCredentials();
}

From source file:com.netflix.genie.web.util.S3ClientFactory.java

License:Apache License

/**
 * Get an S3 client given the configuration of the system.
 *
 * @return an S3 client// w  w w .j  a  v  a2 s .  co  m
 */
public AmazonS3 getS3Client() {
    if (this.assumeRole) {
        // TODO: It's possible this could be optimized to reuse a client that a role has already been assumed for
        //       it would take more logic in this class and likely isn't worth it right now before we decide how
        //       4.x may work best. As it is now create a new client every time one is requested to assume a role

        // See: https://docs.aws.amazon.com/AmazonS3/latest/dev/AuthUsingTempSessionTokenJava.html
        final AWSSecurityTokenService stsClient = AWSSecurityTokenServiceClientBuilder.standard()
                .withCredentials(this.awsCredentialsProvider)
                .withClientConfiguration(this.awsClientConfiguration).withRegion(this.awsRegion).build();

        final AssumeRoleRequest roleRequest = new AssumeRoleRequest().withRoleArn(this.roleArn)
                .withRoleSessionName("Genie-" + UUID.randomUUID().toString());

        final AssumeRoleResult roleResult = stsClient.assumeRole(roleRequest);
        final Credentials sessionCredentials = roleResult.getCredentials();

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

        return AmazonS3ClientBuilder.standard()
                .withCredentials(new AWSStaticCredentialsProvider(basicSessionCredentials))
                .withClientConfiguration(this.awsClientConfiguration).withRegion(this.awsRegion).build();
    } else {
        return this.defaultS3Client;
    }
}

From source file:com.netflix.ice.common.AwsUtils.java

License:Apache License

/**
 * Get assumes IAM credentials.//from w  w w  . j  ava 2  s  .c  o m
 * @param accountId
 * @param assumeRole
 * @return assumes IAM credentials
 */
public static Credentials getAssumedCredentials(String accountId, String assumeRole, String externalId) {
    AssumeRoleRequest assumeRoleRequest = new AssumeRoleRequest()
            .withRoleArn("arn:aws:iam::" + accountId + ":role/" + assumeRole)
            .withRoleSessionName(assumeRole.substring(0, Math.min(assumeRole.length(), 32)));
    if (!StringUtils.isEmpty(externalId))
        assumeRoleRequest.setExternalId(externalId);
    AssumeRoleResult roleResult = securityClient.assumeRole(assumeRoleRequest);
    return roleResult.getCredentials();
}