Java Code Examples for com.amazonaws.auth.AWSCredentialsProvider#getCredentials()

The following examples show how to use com.amazonaws.auth.AWSCredentialsProvider#getCredentials() . 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: AWSGlueClientFactoryTest.java    From aws-glue-data-catalog-client-for-apache-hive-metastore with Apache License 2.0 6 votes vote down vote up
@Test
public void testCredentialsCreatedBySessionCredentialsProviderFactory() throws Exception {
  hiveConf.setStrings(SessionCredentialsProviderFactory.AWS_ACCESS_KEY_CONF_VAR, FAKE_ACCESS_KEY);
  hiveConf.setStrings(SessionCredentialsProviderFactory.AWS_SECRET_KEY_CONF_VAR, FAKE_SECRET_KEY);
  hiveConf.setStrings(SessionCredentialsProviderFactory.AWS_SESSION_TOKEN_CONF_VAR, FAKE_SESSION_TOKEN);

  SessionCredentialsProviderFactory factory = new SessionCredentialsProviderFactory();
  AWSCredentialsProvider provider = factory.buildAWSCredentialsProvider(hiveConf);
  AWSCredentials credentials = provider.getCredentials();

  assertThat(credentials, instanceOf(BasicSessionCredentials.class));

  BasicSessionCredentials sessionCredentials = (BasicSessionCredentials) credentials;

  assertEquals(FAKE_ACCESS_KEY, sessionCredentials.getAWSAccessKeyId());
  assertEquals(FAKE_SECRET_KEY, sessionCredentials.getAWSSecretKey());
  assertEquals(FAKE_SESSION_TOKEN, sessionCredentials.getSessionToken());
}
 
Example 2
Source File: TestPrestoS3FileSystem.java    From presto with Apache License 2.0 6 votes vote down vote up
@Test
public void testAssumeRoleStaticCredentials()
        throws Exception
{
    Configuration config = new Configuration(false);
    config.set(S3_ACCESS_KEY, "test_access_key");
    config.set(S3_SECRET_KEY, "test_secret_key");
    config.set(S3_IAM_ROLE, "test_role");

    try (PrestoS3FileSystem fs = new PrestoS3FileSystem()) {
        fs.initialize(new URI("s3n://test-bucket/"), config);
        AWSCredentialsProvider tokenService = getStsCredentialsProvider(fs, "test_role");
        assertInstanceOf(tokenService, AWSStaticCredentialsProvider.class);

        AWSCredentials credentials = tokenService.getCredentials();
        assertEquals(credentials.getAWSAccessKeyId(), "test_access_key");
        assertEquals(credentials.getAWSSecretKey(), "test_secret_key");
    }
}
 
Example 3
Source File: AwsSdkSample.java    From aws-sdk-java-archetype with Apache License 2.0 6 votes vote down vote up
/**
 * 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
 */
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);
}
 
Example 4
Source File: TestS3Accessor.java    From datacollector with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateCredentials() throws Exception {
  CredentialsConfigs credentialsConfigs = new CredentialsConfigs() {
    @Override
    public CredentialValue getAccessKey() {
      return () -> "access";
    }

    @Override
    public CredentialValue getSecretKey() {
      return () -> "secret";
    }
  };
  S3Accessor accessor = new S3Accessor(credentialsConfigs, null, null, null);

  AWSCredentialsProvider provider = accessor.createCredentialsProvider();
  AWSCredentials credentials = provider.getCredentials();
  Assert.assertEquals("access", credentials.getAWSAccessKeyId());
  Assert.assertEquals("secret", credentials.getAWSSecretKey());
}
 
Example 5
Source File: AwsCredentialProviderPlugin.java    From pulsar with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a V2 credential provider for use with the v2 SDK.
 *
 * Defaults to an implementation that pulls credentials from a v1 provider
 */
default software.amazon.awssdk.auth.credentials.AwsCredentialsProvider getV2CredentialsProvider() {
    // make a small wrapper to forward requests to v1, this allows
    // for this interface to not "break" for implementers
    AWSCredentialsProvider v1Provider = getCredentialProvider();
    return () -> {
        AWSCredentials creds = v1Provider.getCredentials();
        if (creds instanceof AWSSessionCredentials) {
            return software.amazon.awssdk.auth.credentials.AwsSessionCredentials.create(
                    creds.getAWSAccessKeyId(),
                    creds.getAWSSecretKey(),
                    ((AWSSessionCredentials) creds).getSessionToken());
        } else {
            return software.amazon.awssdk.auth.credentials.AwsBasicCredentials.create(
                    creds.getAWSAccessKeyId(),
                    creds.getAWSSecretKey());
        }
    };
}
 
Example 6
Source File: AWSCredentialsConfigurator.java    From cyberduck with GNU General Public License v3.0 6 votes vote down vote up
@Override
public Credentials configure(final Host host) {
    final Credentials credentials = new Credentials(host.getCredentials());
    if(!credentials.validate(host.getProtocol(), new LoginOptions(host.getProtocol()).password(false))) {
        // Lookup from default profile if no access key is set in bookmark
        for(AWSCredentialsProvider provider : providers) {
            try {
                final AWSCredentials c = provider.getCredentials();
                credentials.setUsername(c.getAWSAccessKeyId());
                credentials.setPassword(c.getAWSSecretKey());
                if(c instanceof AWSSessionCredentials) {
                    credentials.setToken(((AWSSessionCredentials) c).getSessionToken());
                }
                break;
            }
            catch(SdkClientException e) {
                log.debug(String.format("Ignore failure loading credentials from provider %s", provider));
                // Continue searching with next provider
            }
        }
    }
    return credentials;
}
 
Example 7
Source File: GroupModel.java    From strongbox with Apache License 2.0 6 votes vote down vote up
private AWSCredentialsProvider resolveBaseCredentials(final ClientConfiguration clientConfiguration, final ProfileIdentifier profileIdentifier) {
    try {
        AWSCredentialsProvider credentialsProvider =  new CustomCredentialsProviderChain(clientConfiguration, profileIdentifier, MFAToken.defaultMFATokenSupplier());

        // Test if getCredentials will throw
        credentialsProvider.getCredentials();

        return credentialsProvider;
    } catch (Exception e) {
        throw new RuntimeException(String.format("Failed to resolve credentials.\n" +
                        "\n" +
                        "If you entered an MFA token, the token was incorrect, or the MFA is misconfigured\n" +
                        "\n" +
                        "The following locations are included in the credentials chain:\n" +
                        " - environment variables\n" +
                        " - system properties\n" +
                        " - credential file (%s) and config file (%s)\n" +
                        " - ec2 container metadata\n" +
                        "\n" +
                        "Please refer to the documentation for how to configure credentials",
                AWSCLIConfigFile.getCredentialProfilesFile().map(File::getAbsolutePath).orElse("not specified"),
                AWSCLIConfigFile.getConfigFile().map(File::getAbsolutePath).orElse("not specified")), e);
    }
}
 
Example 8
Source File: CodeBuildBaseCredentials.java    From aws-codebuild-jenkins-plugin with Apache License 2.0 6 votes vote down vote up
@Override
public void refresh() {
    if (!iamRoleArn.isEmpty()) {
        if (!haveCredentialsExpired()) {
            return;
        }

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

        AssumeRoleRequest assumeRequest = new AssumeRoleRequest()
                .withRoleArn(iamRoleArn)
                .withExternalId(externalId)
                .withDurationSeconds(3600)
                .withRoleSessionName(ROLE_SESSION_NAME);

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

        roleCredentials = assumeResult.getCredentials();
    }
}
 
Example 9
Source File: DynamoDBClientTest.java    From emr-dynamodb-connector with Apache License 2.0 6 votes vote down vote up
@Test
public void testBasicSessionCredentials(){
  final String DYNAMODB_ACCESS_KEY = "abc";
  final String DYNAMODB_SECRET_KEY = "xyz";
  final String DYNAMODB_SESSION_KEY = "007";
  Configuration conf = new Configuration();
  conf.set(DynamoDBConstants.DYNAMODB_ACCESS_KEY_CONF, DYNAMODB_ACCESS_KEY);
  conf.set(DynamoDBConstants.DYNAMODB_SECRET_KEY_CONF, DYNAMODB_SECRET_KEY);
  conf.set(DynamoDBConstants.DYNAMODB_SESSION_TOKEN_CONF, DYNAMODB_SESSION_KEY);

  DynamoDBClient dynamoDBClient = new DynamoDBClient();
  AWSCredentialsProvider provider = dynamoDBClient.getAWSCredentialsProvider(conf);
  AWSSessionCredentials sessionCredentials = (AWSSessionCredentials) provider.getCredentials();
  Assert.assertEquals(DYNAMODB_ACCESS_KEY, sessionCredentials.getAWSAccessKeyId());
  Assert.assertEquals(DYNAMODB_SECRET_KEY, sessionCredentials.getAWSSecretKey());
  Assert.assertEquals(DYNAMODB_SESSION_KEY, sessionCredentials.getSessionToken());

}
 
Example 10
Source File: AmazonS3SourceMockTests.java    From spring-cloud-stream-app-starters with Apache License 2.0 6 votes vote down vote up
@Test
@Override
public void test() throws Exception {
	for (int i = 1; i <= 2; i++) {
		Message<?> received = this.messageCollector.forChannel(this.channels.output())
				.poll(10, TimeUnit.SECONDS);
		assertNotNull(received);
		assertThat(received, hasPayload(new File(this.config.getLocalDir(), i + ".test")));
	}

	assertEquals(2, this.config.getLocalDir().list().length);

	AWSCredentialsProvider awsCredentialsProvider =
			TestUtils.getPropertyValue(this.amazonS3, "awsCredentialsProvider", AWSCredentialsProvider.class);

	AWSCredentials credentials = awsCredentialsProvider.getCredentials();
	assertEquals(AWS_ACCESS_KEY, credentials.getAWSAccessKeyId());
	assertEquals(AWS_SECRET_KEY, credentials.getAWSSecretKey());

	assertEquals(Region.US_GovCloud, this.amazonS3.getRegion());
	assertEquals(new URI("https://s3-us-gov-west-1.amazonaws.com"),
			TestUtils.getPropertyValue(this.amazonS3, "endpoint"));
}
 
Example 11
Source File: TestCredentialsProviderFactory.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Test
public void testAnonymousCredentials() throws Throwable {
    final TestRunner runner = TestRunners.newTestRunner(MockAWSProcessor.class);
    runner.setProperty(CredentialPropertyDescriptors.USE_ANONYMOUS_CREDENTIALS, "true");
    runner.assertValid();

    Map<PropertyDescriptor, String> properties = runner.getProcessContext().getProperties();
    final CredentialsProviderFactory factory = new CredentialsProviderFactory();
    final AWSCredentialsProvider credentialsProvider = factory.getCredentialsProvider(properties);
    Assert.assertNotNull(credentialsProvider);
    final AWSCredentials creds = credentialsProvider.getCredentials();
    assertEquals("credentials should be equal", AnonymousAWSCredentials.class, creds.getClass());
}
 
Example 12
Source File: ProfilesConfigFile.java    From bazel with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the AWS credentials for the specified profile.
 */
public AWSCredentials getCredentials(String profileName) {
    final AWSCredentialsProvider provider = credentialProviderCache.get(profileName);
    if (provider != null) {
        return provider.getCredentials();
    } else {
        BasicProfile profile = allProfiles.getProfile(profileName);
        if (profile == null) {
            throw new IllegalArgumentException("No AWS profile named '" + profileName + "'");
        }
        final AWSCredentialsProvider newProvider = fromProfile(profile);
        credentialProviderCache.put(profileName, newProvider);
        return newProvider.getCredentials();
    }
}
 
Example 13
Source File: PooledS3Connection.java    From CloverETL-Engine with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public AWSCredentials getCredentials() {
	AWSCredentials result = null;
	
	AWSCredentialsProvider delegate = getProjectCredentialsProvider();
	if (delegate != null) {
		result = delegate.getCredentials();
	}
	
	if (result == null) {
		result = S3Utils.NULL_CREDENTIALS; // used in a chain, prevent NPE
	}
	
	return result;
}
 
Example 14
Source File: SnsConfigurationTest.java    From circus-train with Apache License 2.0 5 votes vote down vote up
@Test
public void credentials() throws IOException {
  when(conf.getPassword("access.key")).thenReturn("accessKey".toCharArray());
  when(conf.getPassword("secret.key")).thenReturn("secretKey".toCharArray());
  AWSCredentialsProvider credentialsProvider = configuration.awsCredentialsProvider(conf);
  AWSCredentials awsCredentials = credentialsProvider.getCredentials();
  assertThat(awsCredentials.getAWSAccessKeyId(), is("accessKey"));
  assertThat(awsCredentials.getAWSSecretKey(), is("secretKey"));
}
 
Example 15
Source File: JavaKinesisVideoServiceClient.java    From amazon-kinesis-video-streams-producer-sdk-java with Apache License 2.0 5 votes vote down vote up
private static AmazonKinesisVideo createAmazonKinesisVideoClient(
        final AWSCredentialsProvider awsCredentialsProvider,
        final Region region,
        final String endpoint,
        final int timeoutInMillis)
        throws KinesisVideoException {

    final AWSCredentials credentials = awsCredentialsProvider.getCredentials();
    return createAwsKinesisVideoClient(credentials, region, endpoint, timeoutInMillis);
}
 
Example 16
Source File: TestCredentialsProviderFactory.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
@Test
public void testAnonymousCredentials() throws Throwable {
    final TestRunner runner = TestRunners.newTestRunner(MockAWSProcessor.class);
    runner.setProperty(CredentialPropertyDescriptors.USE_ANONYMOUS_CREDENTIALS, "true");
    runner.assertValid();

    Map<PropertyDescriptor, String> properties = runner.getProcessContext().getProperties();
    final CredentialsProviderFactory factory = new CredentialsProviderFactory();
    final AWSCredentialsProvider credentialsProvider = factory.getCredentialsProvider(properties);
    Assert.assertNotNull(credentialsProvider);
    final AWSCredentials creds = credentialsProvider.getCredentials();
    assertEquals("credentials should be equal", AnonymousAWSCredentials.class, creds.getClass());
}
 
Example 17
Source File: AWSAssumeRoleCredentialsProvider.java    From kafka-connect-sqs with Apache License 2.0 5 votes vote down vote up
@Override
public AWSCredentials getCredentials() {
  AWSSecurityTokenServiceClientBuilder clientBuilder = AWSSecurityTokenServiceClientBuilder.standard();
  AWSCredentialsProvider provider = new STSAssumeRoleSessionCredentialsProvider.Builder(roleArn, sessionName)
      .withStsClient(clientBuilder.defaultClient())
      .withExternalId(externalId)
      .build();

  return provider.getCredentials();
}
 
Example 18
Source File: AWSAssumeRoleCredentialsProvider.java    From kafka-connect-lambda with Apache License 2.0 5 votes vote down vote up
@Override
public AWSCredentials getCredentials() {
  AWSSecurityTokenServiceClientBuilder clientBuilder = AWSSecurityTokenServiceClientBuilder.standard();
  AWSCredentialsProvider provider = new STSAssumeRoleSessionCredentialsProvider.Builder(roleArn, sessionName)
      .withStsClient(clientBuilder.defaultClient())
      .withExternalId(externalId)
      .build();

  return provider.getCredentials();
}
 
Example 19
Source File: TestPrestoS3FileSystem.java    From presto with Apache License 2.0 5 votes vote down vote up
private static AWSCredentials getStaticCredentials(Configuration config, PrestoS3FileSystem fileSystem, String uri)
        throws IOException, URISyntaxException
{
    fileSystem.initialize(new URI(uri), config);
    AWSCredentialsProvider awsCredentialsProvider = getAwsCredentialsProvider(fileSystem);
    assertInstanceOf(awsCredentialsProvider, AWSStaticCredentialsProvider.class);
    return awsCredentialsProvider.getCredentials();
}
 
Example 20
Source File: BlobStoreManagedLedgerOffloader.java    From pulsar with Apache License 2.0 4 votes vote down vote up
public static Supplier<Credentials> getCredentials(String driver,
           OffloadPolicies conf) throws IOException {
    // credentials:
    //   for s3, get by DefaultAWSCredentialsProviderChain.
    //   for gcs, use downloaded file 'google_creds.json', which contains service account key by
    //     following instructions in page https://support.google.com/googleapi/answer/6158849

    if (isGcsDriver(driver)) {
        String gcsKeyPath = conf.getGcsManagedLedgerOffloadServiceAccountKeyFile();
        if (Strings.isNullOrEmpty(gcsKeyPath)) {
            throw new IOException(
                "The service account key path is empty for GCS driver");
        }
        try {
            String gcsKeyContent = Files.toString(new File(gcsKeyPath), Charset.defaultCharset());
            return () -> new GoogleCredentialsFromJson(gcsKeyContent).get();
        } catch (IOException ioe) {
            log.error("Cannot read GCS service account credentials file: {}", gcsKeyPath);
            throw new IOException(ioe);
        }
    } else if (isS3Driver(driver)) {
        AWSCredentialsProvider credsChain = CredentialsUtil.getAWSCredentialProvider(conf);
        // try and get creds before starting... if we can't fetch
        // creds on boot, we want to fail
        try {
            credsChain.getCredentials();
        } catch (Exception e) {
            // allowed, some mock s3 service not need credential
            log.error("unable to fetch S3 credentials for offloading, failing", e);
            throw e;
        }

        return () -> {
            AWSCredentials creds = credsChain.getCredentials();
            if (creds == null) {
                // we don't expect this to happen, as we
                // successfully fetched creds on boot
                throw new RuntimeException("Unable to fetch S3 credentials after start, unexpected!");
            }
            // if we have session credentials, we need to send the session token
            // this allows us to support EC2 metadata credentials
            if (creds instanceof AWSSessionCredentials) {
                return SessionCredentials.builder()
                        .accessKeyId(creds.getAWSAccessKeyId())
                        .secretAccessKey(creds.getAWSSecretKey())
                        .sessionToken(((AWSSessionCredentials) creds).getSessionToken())
                        .build();
            } else {
                return new Credentials(creds.getAWSAccessKeyId(), creds.getAWSSecretKey());
            }
        };
    } else {
        throw new IOException(
            "Not support this kind of driver: " + driver);
    }
}