Example usage for com.amazonaws.auth BasicSessionCredentials BasicSessionCredentials

List of usage examples for com.amazonaws.auth BasicSessionCredentials BasicSessionCredentials

Introduction

In this page you can find the example usage for com.amazonaws.auth BasicSessionCredentials BasicSessionCredentials.

Prototype

public BasicSessionCredentials(String awsAccessKey, String awsSecretKey, String sessionToken) 

Source Link

Usage

From source file:com.eucalyptus.blockstorage.S3SnapshotTransfer.java

License:Open Source License

private void initializeEucaS3Client() throws SnapshotTransferException {
    if (role == null) {
        try {/*from   w  ww. j a  v a 2s  .  c  om*/
            role = BlockStorageUtil.checkAndConfigureBlockStorageAccount();
        } catch (Exception e) {
            LOG.error("Failed to initialize account for snapshot transfers due to " + e);
            throw new SnapshotTransferException("Failed to initialize eucalyptus account for snapshot transfes",
                    e);
        }
    }

    try {
        SecurityToken token = SecurityTokenManager.issueSecurityToken(role, (int) TimeUnit.HOURS.toSeconds(1));
        eucaS3Client = EucaS3ClientFactory.getEucaS3Client(
                new BasicSessionCredentials(token.getAccessKeyId(), token.getSecretKey(), token.getToken()));
    } catch (Exception e) {
        LOG.error("Failed to initialize S3 client for snapshot transfers due to " + e);
        throw new SnapshotTransferException("Failed to initialize S3 client for snapshot transfers", e);
    }
}

From source file:com.experiment.trax.services.tvmclient.AWSSharedPreferencesWrapper.java

License:Open Source License

/**
 * Gets the AWS Access Key, AWS Secret Key and Security Token currently stored in Shared Preferences.  Then creates a Credentials object
 * and returns that object./*ww w.  j av  a 2  s  .  co  m*/
 */
public static AWSCredentials getCredentialsFromSharedPreferences(SharedPreferences sharedPreferences) {
    String accessKey = AWSSharedPreferencesWrapper.getValueFromSharedPreferences(sharedPreferences,
            AWS_ACCESS_KEY);
    String secretKey = AWSSharedPreferencesWrapper.getValueFromSharedPreferences(sharedPreferences,
            AWS_SECRET_KEY);
    String securityToken = AWSSharedPreferencesWrapper.getValueFromSharedPreferences(sharedPreferences,
            AWS_SECURITY_TOKEN);

    return new BasicSessionCredentials(accessKey, secretKey, securityToken);
}

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  www . j  a  v  a2s.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 AutoScalingGroup retrieveAutoScalingGroupCrossAccount(String asgAccount, String asgName) {
    logger.debug("Getting cross account ASG for asgName: " + asgName + ", asgAccount: " + asgAccount);

    Credentials credentials = stsCredentials.get(asgAccount);

    if (credentials == null || credentials.getExpiration().getTime() < System.currentTimeMillis() + 1000) {
        stsCredentials.put(asgAccount, initializeStsSession(asgAccount));
        credentials = stsCredentials.get(asgAccount);
    }/* w  w  w  .ja  v a 2s .c o  m*/

    ClientConfiguration clientConfiguration = new ClientConfiguration()
            .withConnectionTimeout(serverConfig.getASGQueryTimeoutMs());

    AmazonAutoScaling autoScalingClient = new AmazonAutoScalingClient(
            new BasicSessionCredentials(credentials.getAccessKeyId(), credentials.getSecretAccessKey(),
                    credentials.getSessionToken()),
            clientConfiguration);

    String region = clientConfig.getRegion();
    if (!region.equals("us-east-1")) {
        autoScalingClient.setEndpoint("autoscaling." + region + ".amazonaws.com");
    }

    DescribeAutoScalingGroupsRequest request = new DescribeAutoScalingGroupsRequest()
            .withAutoScalingGroupNames(asgName);
    DescribeAutoScalingGroupsResult result = autoScalingClient.describeAutoScalingGroups(request);
    List<AutoScalingGroup> asgs = result.getAutoScalingGroups();
    if (asgs.isEmpty()) {
        return null;
    } else {
        return asgs.get(0);
    }
}

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

License:Apache License

private AutoScalingGroup retrieveAutoScalingGroupCrossAccount(String asgAccount, String asgName) {
    logger.debug("Getting cross account ASG for asgName: " + asgName + ", asgAccount: " + asgAccount);

    Credentials credentials = stsCredentials.get(asgAccount);

    if (credentials == null || credentials.getExpiration().getTime() < System.currentTimeMillis() + 1000) {
        stsCredentials.put(asgAccount, initializeStsSession(asgAccount));
        credentials = stsCredentials.get(asgAccount);
    }/*from ww w  .  j  av a2s. co m*/

    ClientConfiguration clientConfiguration = new ClientConfiguration()
            .withConnectionTimeout(eurekaConfig.getASGQueryTimeoutMs());

    AmazonAutoScaling autoScalingClient = new AmazonAutoScalingClient(
            new BasicSessionCredentials(credentials.getAccessKeyId(), credentials.getSecretAccessKey(),
                    credentials.getSessionToken()),
            clientConfiguration);

    String region = DiscoveryManager.getInstance().getEurekaClientConfig().getRegion();
    if (!region.equals("us-east-1")) {
        autoScalingClient.setEndpoint("autoscaling." + region + ".amazonaws.com");
    }

    DescribeAutoScalingGroupsRequest request = new DescribeAutoScalingGroupsRequest()
            .withAutoScalingGroupNames(asgName);
    DescribeAutoScalingGroupsResult result = autoScalingClient.describeAutoScalingGroups(request);
    List<AutoScalingGroup> asgs = result.getAutoScalingGroups();
    if (asgs.isEmpty()) {
        return null;
    } else {
        return asgs.get(0);
    }
}

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/*  ww w  .j  a va  2  s.  c om*/
 */
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

/**
 * List all object summary with given prefix in the s3 bucket.
 * @param bucket//  w w w.j  a  va2  s.c o  m
 * @param prefix
 * @return
 */
public static List<S3ObjectSummary> listAllObjects(String bucket, String prefix, String accountId,
        String assumeRole, String externalId) {
    AmazonS3Client s3Client = AwsUtils.s3Client;

    try {
        ListObjectsRequest request = new ListObjectsRequest().withBucketName(bucket).withPrefix(prefix);
        List<S3ObjectSummary> result = Lists.newLinkedList();

        if (!StringUtils.isEmpty(accountId) && !StringUtils.isEmpty(assumeRole)) {
            Credentials assumedCredentials = getAssumedCredentials(accountId, assumeRole, externalId);
            s3Client = new AmazonS3Client(
                    new BasicSessionCredentials(assumedCredentials.getAccessKeyId(),
                            assumedCredentials.getSecretAccessKey(), assumedCredentials.getSessionToken()),
                    clientConfig);
        }

        ObjectListing page = null;
        do {
            if (page != null)
                request.setMarker(page.getNextMarker());
            page = s3Client.listObjects(request);
            result.addAll(page.getObjectSummaries());

        } while (page.isTruncated());

        return result;
    } finally {
        if (s3Client != AwsUtils.s3Client)
            s3Client.shutdown();
    }
}

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

License:Apache License

public static boolean downloadFileIfChangedSince(String bucketName, String bucketFilePrefix, File file,
        long milles, String accountId, String assumeRole, String externalId) {
    AmazonS3Client s3Client = AwsUtils.s3Client;

    try {/*from  www .j  a  va2  s.co  m*/
        if (!StringUtils.isEmpty(accountId) && !StringUtils.isEmpty(assumeRole)) {
            Credentials assumedCredentials = getAssumedCredentials(accountId, assumeRole, externalId);
            s3Client = new AmazonS3Client(
                    new BasicSessionCredentials(assumedCredentials.getAccessKeyId(),
                            assumedCredentials.getSecretAccessKey(), assumedCredentials.getSessionToken()),
                    clientConfig);
        }

        ObjectMetadata metadata = s3Client.getObjectMetadata(bucketName, bucketFilePrefix + file.getName());
        boolean download = !file.exists() || metadata.getLastModified().getTime() > milles;

        if (download) {
            return download(s3Client, bucketName, bucketFilePrefix + file.getName(), file);
        } else
            return download;
    } finally {
        if (s3Client != AwsUtils.s3Client)
            s3Client.shutdown();
    }
}

From source file:com.netflix.simianarmy.aws.STSAssumeRoleSessionCredentialsProvider.java

License:Apache License

/**
 * Starts a new session by sending a request to the AWS Security Token
 * Service (STS) to assume a Role using the long lived AWS credentials. This
 * class then vends the short lived session credentials for the assumed Role
 * sent back from STS./*  www .j  a  v a  2  s . co m*/
 */
private void startSession() {
    AssumeRoleResult assumeRoleResult = securityTokenService
            .assumeRole(new AssumeRoleRequest().withRoleArn(roleArn)
                    .withDurationSeconds(DEFAULT_DURATION_SECONDS).withRoleSessionName("SimianArmy"));
    Credentials stsCredentials = assumeRoleResult.getCredentials();
    sessionCredentials = new BasicSessionCredentials(stsCredentials.getAccessKeyId(),
            stsCredentials.getSecretAccessKey(), stsCredentials.getSessionToken());
    sessionCredentialsExpiration = stsCredentials.getExpiration();
}

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

License:Open Source License

private static String setAWSCredentials(AssumeRoleWithSAMLResult assumeResult, String credentialsProfileName)
        throws FileNotFoundException, UnsupportedEncodingException, IOException {
    BasicSessionCredentials temporaryCredentials = new BasicSessionCredentials(
            assumeResult.getCredentials().getAccessKeyId(), assumeResult.getCredentials().getSecretAccessKey(),
            assumeResult.getCredentials().getSessionToken());

    String awsAccessKey = temporaryCredentials.getAWSAccessKeyId();
    String awsSecretKey = temporaryCredentials.getAWSSecretKey();
    String awsSessionToken = temporaryCredentials.getSessionToken();

    //File file = new File(System.getProperty("user.home") + "/.aws/credentials");
    //file.getParentFile().mkdirs();
    //try {/*from   w  ww . j av a  2  s  . com*/

    if (credentialsProfileName.startsWith("arn:aws:sts::")) {
        credentialsProfileName = credentialsProfileName.substring(13);
    }
    if (credentialsProfileName.contains(":assumed-role")) {
        credentialsProfileName = credentialsProfileName.replaceAll(":assumed-role", "");
    }

    Object[] args = { new String(credentialsProfileName) };
    //writer.println("[aws-okta]");
    MessageFormat fmt = new MessageFormat("[{0}]");
    String profileNameLine = fmt.format(args);

    ProfilesConfigFile profilesConfigFile = null;
    try {
        profilesConfigFile = new ProfilesConfigFile();
    } catch (AmazonClientException ace) {
        PopulateCredentialsFile(profileNameLine, awsAccessKey, awsSecretKey, awsSessionToken);
    }

    try {
        if (profilesConfigFile != null && profilesConfigFile.getCredentials(credentialsProfileName) != null) {

            //if we end up here, it means we were  able to find a matching profile
            PopulateCredentialsFile(profileNameLine, awsAccessKey, awsSecretKey, awsSessionToken);
        }
    } catch (IllegalArgumentException iae) {

        //if we end up here, it means we were not able to find a matching profile so we need to append one
        FileWriter fileWriter = new FileWriter(System.getProperty("user.home") + "/.aws/credentials", true); //TODO: need to be updated to work with Windows
        PrintWriter writer = new PrintWriter(fileWriter); // new PrintWriter(file, "UTF-8");
        WriteNewProfile(writer, profileNameLine, awsAccessKey, awsSecretKey, awsSessionToken);
        fileWriter.close();
    }

    return credentialsProfileName;
}