Example usage for com.amazonaws.auth AWSCredentialsProvider getCredentials

List of usage examples for com.amazonaws.auth AWSCredentialsProvider getCredentials

Introduction

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

Prototype

public AWSCredentials getCredentials();

Source Link

Document

Returns AWSCredentials which the caller can use to authorize an AWS request.

Usage

From source file:AwsSdkSample.java

License:Open Source License

/**
 * The only information needed to create a client are security credentials -
 * your AWS Access Key ID and Secret Access Key. All other
 * configuration, such as the service endpoints have defaults provided.
 *
 * Additional client parameters, such as proxy configuration, can be specified
 * in an optional ClientConfiguration object when constructing a client.
 *
 * @see com.amazonaws.auth.BasicAWSCredentials
 * @see com.amazonaws.auth.PropertiesCredentials
 * @see com.amazonaws.ClientConfiguration
 *//*from   ww w .ja va  2  s . com*/
private static void init() throws Exception {
    /*
     * ProfileCredentialsProvider loads AWS security credentials from a
     * .aws/config file in your home directory.
     *
     * These same credentials are used when working with other AWS SDKs and the AWS CLI.
     *
     * You can find more information on the AWS profiles config file here:
     * http://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html
     */
    File configFile = new File(System.getProperty("user.home"), ".aws/credentials");
    AWSCredentialsProvider credentialsProvider = new ProfileCredentialsProvider(
            new ProfilesConfigFile(configFile), "default");

    if (credentialsProvider.getCredentials() == null) {
        throw new RuntimeException("No AWS security credentials found:\n"
                + "Make sure you've configured your credentials in: " + configFile.getAbsolutePath() + "\n"
                + "For more information on configuring your credentials, see "
                + "http://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html");
    }

    ec2 = new AmazonEC2Client(credentialsProvider);
    s3 = new AmazonS3Client(credentialsProvider);
}

From source file:CodeBuildCredentials.java

License:Open Source License

@Override
public AWSCredentials getCredentials() {
    AWSCredentialsProvider credentialsProvider = AWSClientFactory.getBasicCredentialsOrDefaultChain(accessKey,
            secretKey);//from  w ww. j a  va2  s .  c  o m
    AWSCredentials credentials = credentialsProvider.getCredentials();

    if (!iamRoleArn.isEmpty()) {
        if (haveCredentialsExpired()) {
            refresh();
        }
        credentials = new BasicSessionCredentials(roleCredentials.getAccessKeyId(),
                roleCredentials.getSecretAccessKey(), roleCredentials.getSessionToken());
    }

    return credentials;
}

From source file:CodeBuildCredentials.java

License:Open Source License

@Override
public void refresh() {
    if (!iamRoleArn.isEmpty()) {
        if (!haveCredentialsExpired()) {
            return;
        }//from w  ww.  j  a 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:SampleKinesisApplication.java

License:Open Source License

private static void configure(String propertiesFile) throws IOException {

    if (propertiesFile != null) {
        loadProperties(propertiesFile);/*  w  ww  .  j  a v  a2s  . c  o  m*/
    }

    // ensure the JVM will refresh the cached IP values of AWS resources (e.g. service endpoints).
    java.security.Security.setProperty("networkaddress.cache.ttl", "60");

    String workerId = InetAddress.getLocalHost().getCanonicalHostName() + ":" + UUID.randomUUID();
    LOG.info("Using workerId: " + workerId);

    // Get credentials from IMDS. If unsuccessful, get them from the credential profiles file.
    AWSCredentialsProvider credentialsProvider = null;
    try {
        credentialsProvider = new InstanceProfileCredentialsProvider();
        // Verify we can fetch credentials from the provider
        credentialsProvider.getCredentials();
        LOG.info("Obtained credentials from the IMDS.");
    } catch (AmazonClientException e) {
        LOG.info("Unable to obtain credentials from the IMDS, trying classpath properties", e);
        credentialsProvider = new ProfileCredentialsProvider();
        // Verify we can fetch credentials from the provider
        credentialsProvider.getCredentials();
        LOG.info("Obtained credentials from the properties file.");
    }

    LOG.info("Using credentials with access key id: "
            + credentialsProvider.getCredentials().getAWSAccessKeyId());

    kinesisClientLibConfiguration = new KinesisClientLibConfiguration(applicationName, streamName,
            credentialsProvider, workerId).withInitialPositionInStream(initialPositionInStream);
}

From source file:br.com.ingenieux.jenkins.plugins.codecommit.CodeCommitRequestSigner.java

License:Apache License

public CodeCommitRequestSigner(AWSCredentialsProvider credentialsProvider, String repoName, String region,
        Date date) {/*from w ww  . j  a v a 2s  . c  o  m*/
    super(credentialsProvider.getCredentials(), region, "codecommit", date);
    this.repoName = repoName;
}

From source file:br.com.ingenieux.mojo.beanstalk.bundle.CodeCommitRequestSigner.java

License:Apache License

public CodeCommitRequestSigner(AWSCredentialsProvider credentialsProvider, String repoName, Date date) {
    super(credentialsProvider.getCredentials(), "us-east-1", "codecommit", date);
    this.repoName = repoName;
}

From source file:com.amediamanager.util.S3FormSigner.java

License:Apache License

/**
 * The SignRequest method takes a set of AWS credentials and the S3 upload policy string and returns the encoded policy and the signature.
 *
 * @param creds        the AWS credentials to be used for signing the request
 * @param policy    the policy file to applied to the upload
 * @return            an array of strings containing the base 64 encoded policy (index 0) and the signature (index 1).
 *///from w w  w  .  j  a v a 2  s .c o m
String[] signRequest(AWSCredentialsProvider credsProvider, String policy) {

    String[] policyAndSignature = new String[2];

    try {
        // Create a Base64 encoded version of the policy string for placement in the form and
        // for use in signature generation.  Returns are stripped out from the policy string.
        String encodedPolicy = new String(
                Base64.encodeBase64(policy.replaceAll("\n", "").replaceAll("\r", "").getBytes("UTF-8")));

        // AWS signatures are generated using SHA1 HMAC signing.
        Mac hmac = Mac.getInstance("HmacSHA1");

        // Generate the signature using the Secret Key from the AWS credentials
        hmac.init(new SecretKeySpec(credsProvider.getCredentials().getAWSSecretKey().getBytes("UTF-8"),
                "HmacSHA1"));

        String signature = new String(Base64.encodeBase64(hmac.doFinal(encodedPolicy.getBytes("UTF-8"))));

        // Pack the encoded policy and the signature into a string array
        policyAndSignature[0] = encodedPolicy;
        policyAndSignature[1] = signature;

    } catch (UnsupportedEncodingException e) {
        LOG.error("Unsupport encoding", e);
    } catch (NoSuchAlgorithmException e) {
        LOG.error("No such algorithm", e);
    } catch (InvalidKeyException e) {
        LOG.error("Invalid key", e);
    }

    return policyAndSignature;
}

From source file:com.amediamanager.util.S3FormSigner.java

License:Apache License

/**
 * The UploadPolicy method creates the S3 upload policy for the aMediaManager application.
 * Much of this is hard coded and would have to change with any changes to the fields in the S3
 * upload form.// w  ww .j  ava2s.  c  o m
 *
 * @param key            this is not currently used.
 * @param redirectUrl    this is the URL to which S3 will redirect the browser on successful upload.
 * @return                the upload policy string is returned.
 */
String generateUploadPolicy(String s3BucketName, String keyPrefix, AWSCredentialsProvider credsProvider,
        String redirectUrl) {

    Calendar dateTime = Calendar.getInstance();
    // add the offset from UTC
    dateTime.add(Calendar.MILLISECOND, -dateTime.getTimeZone().getOffset(dateTime.getTimeInMillis()));
    // add 15 minutes more for skew
    dateTime.add(Calendar.MINUTE, 15);
    SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");

    String expirationDate = dateFormatter.format(dateTime.getTime());

    StringBuilder sb = new StringBuilder();
    sb.append("{ \"expiration\": \"" + expirationDate + "\",");
    sb.append("\"conditions\": [ { \"bucket\": \"" + s3BucketName + "\" }, ");
    sb.append("[\"starts-with\", \"$key\", \"" + keyPrefix + "/\"], ");
    sb.append("{ \"success_action_redirect\": \"" + redirectUrl + "\" },");
    sb.append("[\"eq\", \"$x-amz-meta-bucket\", \"" + s3BucketName + "\"], ");
    sb.append("[\"starts-with\", \"$x-amz-meta-owner\", \"\"], ");
    sb.append("[\"starts-with\", \"$x-amz-meta-uuid\", \"\"], ");
    sb.append("[\"starts-with\", \"$x-amz-meta-title\", \"\"], ");
    sb.append("[\"starts-with\", \"$x-amz-meta-tags\", \"\"], ");
    sb.append("[\"starts-with\", \"$x-amz-meta-createdDate\", \"\"], ");
    sb.append("[\"starts-with\", \"$x-amz-meta-description\", \"\"], ");
    sb.append("[\"starts-with\", \"$x-amz-meta-privacy\", \"\"], ");
    sb.append("[\"starts-with\", \"$Content-Type\", \"video/\"], ");

    if (credsProvider.getCredentials() instanceof BasicSessionCredentials) {
        sb.append("[\"starts-with\", \"$x-amz-security-token\", \"\"], ");
    }

    sb.append("[\"content-length-range\", 0, 1073741824] ] }");
    return sb.toString();
}

From source file:com.digitalpebble.stormcrawler.aws.s3.AbstractS3CacheBolt.java

License:Apache License

/** Returns an S3 client given the configuration **/
public static AmazonS3Client getS3Client(Map conf) {
    AWSCredentialsProvider provider = new DefaultAWSCredentialsProviderChain();
    AWSCredentials credentials = provider.getCredentials();
    ClientConfiguration config = new ClientConfiguration();

    AmazonS3Client client = new AmazonS3Client(credentials, config);

    String regionName = ConfUtils.getString(conf, REGION);
    if (StringUtils.isNotBlank(regionName)) {
        client.setRegion(RegionUtils.getRegion(regionName));
    }//from   w w w.j  a v  a  2s. c o m

    String endpoint = ConfUtils.getString(conf, ENDPOINT);
    if (StringUtils.isNotBlank(endpoint)) {
        client.setEndpoint(endpoint);
    }
    return client;
}

From source file:com.epam.dlab.auth.aws.service.AwsCredentialRefreshService.java

License:Apache License

private void refresh(AWSCredentialsProvider credentialsProvider) {
    try {/*from  w  ww  .j a v a2s.c  om*/
        credentialsProvider.refresh();
        this.awsUserDAO.updateCredentials(credentialsProvider.getCredentials());
        log.debug("provider credentials refreshed");
    } catch (Exception e) {
        log.error("AWS provider error", e);
        throw e;
    }
}