Example usage for com.amazonaws.services.securitytoken AWSSecurityTokenServiceClient AWSSecurityTokenServiceClient

List of usage examples for com.amazonaws.services.securitytoken AWSSecurityTokenServiceClient AWSSecurityTokenServiceClient

Introduction

In this page you can find the example usage for com.amazonaws.services.securitytoken AWSSecurityTokenServiceClient AWSSecurityTokenServiceClient.

Prototype

AWSSecurityTokenServiceClient(AwsSyncClientParams clientParams) 

Source Link

Document

Constructs a new client to invoke service methods on AWS STS using the specified parameters.

Usage

From source file:CodeBuildCredentials.java

License:Open Source License

@Override
public void refresh() {
    if (!iamRoleArn.isEmpty()) {
        if (!haveCredentialsExpired()) {
            return;
        }//  w w w  . ja  v a 2 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.Lab41.java

License:Open Source License

public void appMode_Run(LabVariables labVariables) throws InterruptedException, IOException {
    AWSCredentials credentials = getCredentials("appmode");

    Credentials devCredentials = null, prodCredentials = null;
    AWSSecurityTokenServiceClient stsClient = new AWSSecurityTokenServiceClient(credentials);
    //stsClient.setRegion(Lab41.region);

    System.out.println("\nAssuming developer role to retrieve developer session credentials.");
    Boolean retry;/*from   w  ww.  j a v a2 s . co  m*/
    long start = System.currentTimeMillis();
    do {
        try {
            devCredentials = labCode.appMode_AssumeRole(stsClient, labVariables.getDevelopmentRoleArn(),
                    "dev_session");
            retry = false;
        } catch (AmazonServiceException ase) {
            if (ase.getErrorCode().equals("AccessDenied")) {
                // If we get access denied, the policy that we created hasn't fully propagated through STS
                // so we need to wait and retry. This code will retry for 30 seconds before timing out.
                long now = System.currentTimeMillis();
                if (now >= (start + 30 * 1000)) {
                    System.out.println();
                    throw ase; // Stop waiting.
                }
                retry = true;
                System.out.print(".");
                // Sleep for a second before trying again.
                Thread.sleep(1000);
            } else {
                throw ase;
            }
        }
    } while (retry);

    System.out.println("\nAssuming production role to retrieve production session credentials.");

    start = System.currentTimeMillis();
    do {
        try {
            prodCredentials = labCode.appMode_AssumeRole(stsClient, labVariables.getProductionRoleArn(),
                    "prod_session");
            retry = false;
        } catch (AmazonServiceException ase) {
            if (ase.getErrorCode().equals("AccessDenied")) {
                // If we get access denied, the policy that we created hasn't fully propagated through STS
                // so we need to wait and retry. This code will retry for 30 seconds before timing out.
                long now = System.currentTimeMillis();
                if (now >= (start + 30 * 1000)) {
                    System.out.println();
                    throw ase; // Stop waiting.
                }
                retry = true;
                System.out.print(".");
                // Sleep for a second before trying again.
                Thread.sleep(1000);
            } else {
                throw ase;
            }
        }
    } while (retry);

    System.out.println("\nCreating S3 client objects.");

    AmazonS3Client devS3Client = labCode.appMode_CreateS3Client(devCredentials, Lab41.region);
    AmazonS3Client prodS3Client = labCode.appMode_CreateS3Client(prodCredentials, Lab41.region);

    System.out.println("\nTesting Developer Session...");

    // Create the dev credentials.
    BasicSessionCredentials devSession = new BasicSessionCredentials(devCredentials.getAccessKeyId(),
            devCredentials.getSecretAccessKey(), devCredentials.getSessionToken());

    // Test services access using the dev credentials.
    System.out.println(
            "  IAM: " + (optionalLabCode.appMode_TestIamAccess(Lab41.region, devSession) ? "Accessible."
                    : "Inaccessible."));
    System.out.println(
            "  SQS: " + (optionalLabCode.appMode_TestSqsAccess(Lab41.region, devSession) ? "Accessible."
                    : "Inaccessible."));
    System.out.println(
            "  SNS: " + (optionalLabCode.appMode_TestSnsAccess(Lab41.region, devSession) ? "Accessible."
                    : "Inaccessible."));
    System.out.println("  S3:");
    for (String bucketName : labVariables.getBucketNames()) {
        testS3Client(devS3Client, bucketName);
    }

    System.out.println("\nTesting Production Session...");
    // Create the prod credentials.
    BasicSessionCredentials prodSession = new BasicSessionCredentials(prodCredentials.getAccessKeyId(),
            prodCredentials.getSecretAccessKey(), prodCredentials.getSessionToken());

    // Test services using the prod credentials.
    System.out.println(
            "  IAM: " + (optionalLabCode.appMode_TestIamAccess(Lab41.region, prodSession) ? "Accessible."
                    : "Inaccessible."));
    System.out.println(
            "  SQS: " + (optionalLabCode.appMode_TestSqsAccess(Lab41.region, prodSession) ? "Accessible."
                    : "Inaccessible."));
    System.out.println(
            "  SNS: " + (optionalLabCode.appMode_TestSnsAccess(Lab41.region, prodSession) ? "Accessible."
                    : "Inaccessible."));
    System.out.println("  S3:");
    for (String bucketName : labVariables.getBucketNames()) {
        testS3Client(prodS3Client, bucketName);
    }
}

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 w w w .  j  a v  a2s.  c o m*/

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

From source file:com.ipcglobal.fredimportaws.TsvsToRedshift.java

License:Apache License

/**
 * Instantiates a new tsvs to redshift.// w ww  .  j  a v  a 2  s  .c  om
 *
 * @param pathNameProperties the path name properties
 * @throws Exception the exception
 */
public TsvsToRedshift(String pathNameProperties) throws Exception {
    this.properties = new Properties();
    properties.load(new FileInputStream(pathNameProperties));
    String credentialsProfileName = this.properties.getProperty("credentialsProfileName").trim();
    this.awsBucketName = this.properties.getProperty("awsBucketName").trim();
    this.awsBucketTsvPrefix = this.properties.getProperty("awsBucketTsvPrefix").trim();

    String outputPath = FredUtils.readfixPath("outputPath", properties);
    String outputSubdirTableTsvFiles = FredUtils.readfixPath("outputSubdirTableTsvFiles", properties);
    this.pathTableTsvFiles = outputPath + outputSubdirTableTsvFiles;

    if (credentialsProfileName == null)
        this.credentialsProvider = AwsUtils.initCredentials();
    else
        this.credentialsProvider = AwsUtils.initProfileCredentialsProvider(credentialsProfileName);

    this.s3Client = new AmazonS3Client(credentialsProvider);
    this.transferManager = new TransferManager(credentialsProvider);
    this.stsClient = new AWSSecurityTokenServiceClient(credentialsProvider);
}

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;//from  w ww.j  a v a 2  s.com
    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");
    }// w  w w.  j  a  va 2  s  .c  o m

    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");
    }/* ww  w .  j av  a 2 s  .  co 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.simianarmy.aws.STSAssumeRoleSessionCredentialsProvider.java

License:Apache License

/**
 * Constructs a new STSAssumeRoleSessionCredentialsProvider, which will use
 * the specified credentials provider (which vends long lived AWS
 * credentials) to make a request to the AWS Security Token Service (STS),
 * usess the provided {@link #roleArn} to assume a role and then request
 * short lived session credentials, which will then be returned by this
 * class's {@link #getCredentials()} method.
 * @param longLivedCredentialsProvider/*from  w w  w. j  ava 2s  . c  om*/
 *            Credentials provider for the main AWS credentials for a user's
 *            account.
 * @param roleArn
 *            The AWS ARN of the Role to be assumed.
 */
public STSAssumeRoleSessionCredentialsProvider(AWSCredentialsProvider longLivedCredentialsProvider,
        String roleArn) {
    this.roleArn = roleArn;
    securityTokenService = new AWSSecurityTokenServiceClient(longLivedCredentialsProvider);
}

From source file:com.okta.tools.awscli.java

License:Open Source License

private static AssumeRoleWithSAMLResult assumeAWSRole(String resultSAML) {
    // Decode SAML response
    resultSAML = resultSAML.replace("+", "+").replace("=", "=");
    String resultSAMLDecoded = new String(Base64.decodeBase64(resultSAML));

    ArrayList<String> principalArns = new ArrayList<String>();
    ArrayList<String> roleArns = new ArrayList<String>();

    //When the app is not assigned to you no assertion is returned
    if (!resultSAMLDecoded.contains("arn:aws")) {
        logger.error("\nYou do not have access to AWS through Okta. \nPlease contact your administrator.");
        System.exit(0);//from   w  w w .  jav  a 2s  . co  m
    }

    System.out.println("\nPlease choose the role you would like to assume: ");

    //Gather list of applicable AWS roles
    int i = 0;
    while (resultSAMLDecoded.indexOf("arn:aws") != -1) {
        /*Trying to parse the value of the Role SAML Assertion that typically looks like this:
        <saml2:AttributeValue xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string">
        arn:aws:iam::[AWS-ACCOUNT-ID]:saml-provider/Okta,arn:aws:iam::[AWS-ACCOUNT-ID]:role/[ROLE_NAME]
        </saml2:AttributeValue>
        </saml2:Attribute>
        */
        int start = resultSAMLDecoded.indexOf("arn:aws");
        int end = resultSAMLDecoded.indexOf("</saml2:", start);
        String resultSAMLRole = resultSAMLDecoded.substring(start, end);
        String[] parts = resultSAMLRole.split(",");
        principalArns.add(parts[0]);
        roleArns.add(parts[1]);
        System.out.println("[ " + (i + 1) + " ]: " + roleArns.get(i));
        resultSAMLDecoded = (resultSAMLDecoded
                .substring(resultSAMLDecoded.indexOf("</saml2:AttributeValue") + 1));
        i++;
    }

    //Prompt user for role selection
    int selection = numSelection(roleArns.size());

    String principalArn = principalArns.get(selection);
    String roleArn = roleArns.get(selection);
    crossAccountRoleName = roleArn.substring(roleArn.indexOf("/") + 1);

    //creates empty AWS credentials to prevent the AWSSecurityTokenServiceClient object from unintentionally loading the previous profile we just created
    BasicAWSCredentials awsCreds = new BasicAWSCredentials("", "");

    //use user credentials to assume AWS role
    AWSSecurityTokenServiceClient stsClient = new AWSSecurityTokenServiceClient(awsCreds);

    AssumeRoleWithSAMLRequest assumeRequest = new AssumeRoleWithSAMLRequest().withPrincipalArn(principalArn)
            .withRoleArn(roleArn).withSAMLAssertion(resultSAML).withDurationSeconds(3600); //default token duration to 12 hours

    return stsClient.assumeRoleWithSAML(assumeRequest);
}

From source file:com.yahoo.athenz.instance.provider.impl.InstanceAWSProvider.java

License:Apache License

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;
    }/*ww  w.  ja  v  a 2  s.  c om*/

    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);
}