com.amazonaws.auth.DefaultAWSCredentialsProviderChain Java Examples

The following examples show how to use com.amazonaws.auth.DefaultAWSCredentialsProviderChain. 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: CredentialsProviderFactoryBeanTest.java    From spring-cloud-aws with Apache License 2.0 7 votes vote down vote up
@Test
void getObject_withZeroConfiguredProviders_returnsDefaultAwsCredentialsProviderChain()
		throws Exception {
	// Arrange
	CredentialsProviderFactoryBean credentialsProviderFactoryBean = new CredentialsProviderFactoryBean();
	credentialsProviderFactoryBean.afterPropertiesSet();

	// Act
	AWSCredentialsProvider credentialsProvider = credentialsProviderFactoryBean
			.getObject();

	// Assert
	assertThat(credentialsProvider).isNotNull();
	assertThat(
			DefaultAWSCredentialsProviderChain.class.isInstance(credentialsProvider))
					.isTrue();
}
 
Example #2
Source File: AwsRestHighLevelClientFactory.java    From aws-athena-query-federation with Apache License 2.0 7 votes vote down vote up
/**
 * Creates a new Elasticsearch REST client. If useAwsCredentials = true, the client is injected with AWS
 * credentials. If useAwsCredentials = false and username/password are extracted using the credentialsPattern,
 * the client is injected with username/password credentials. Otherwise a default client with no credentials is
 * returned.
 * @param endpoint is the Elasticsearch instance endpoint. The latter may contain username/password credentials
 *                 for Elasticsearch services that are external to Amazon.
 *                 Examples:
 *                 1) https://search-movies-ne3yqu.us-east-1.es.amazonaws.com
 *                 2) http://myusername@mypassword:www.google.com
 * @return an Elasticsearch REST client.
 */
private AwsRestHighLevelClient createClient(String endpoint)
{
    if (useAwsCredentials) {
        return new AwsRestHighLevelClient.Builder(endpoint)
                .withCredentials(new DefaultAWSCredentialsProviderChain()).build();
    }
    else {
        Matcher credentials = credentialsPattern.matcher(endpoint);
        if (credentials.find()) {
            String usernameAndPassword = credentials.group();
            String username = usernameAndPassword.substring(0, usernameAndPassword.indexOf("@"));
            String password = usernameAndPassword.substring(usernameAndPassword.indexOf("@") + 1,
                    usernameAndPassword.lastIndexOf(":"));
            String finalEndpoint = endpoint.replace(usernameAndPassword, "");

            return new AwsRestHighLevelClient.Builder(finalEndpoint).withCredentials(username, password).build();
        }
    }

    logger.debug("Default client w/o credentials");

    // Default client w/o credentials.
    return new AwsRestHighLevelClient.Builder(endpoint).build();
}
 
Example #3
Source File: ContextCredentialsConfigurationRegistrarTest.java    From spring-cloud-aws with Apache License 2.0 6 votes vote down vote up
@Test
void credentialsProvider_defaultCredentialsProviderWithoutFurtherConfig_awsCredentialsProviderConfigured()
		throws Exception {
	// Arrange
	this.context = new AnnotationConfigApplicationContext(
			ApplicationConfigurationWithDefaultCredentialsProvider.class);

	// Act
	AWSCredentialsProvider awsCredentialsProvider = this.context
			.getBean(AWSCredentialsProvider.class);

	// Assert
	assertThat(awsCredentialsProvider).isNotNull();
	assertThat(DefaultAWSCredentialsProviderChain.class
			.isInstance(awsCredentialsProvider)).isTrue();
}
 
Example #4
Source File: AWSClientFactoryTest.java    From aws-codebuild-jenkins-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void testStepContextSessionCreds() throws IOException, InterruptedException {
    EnvVars mockEnvVars = mock(EnvVars.class);
    when(mockEnvVars.get(AWS_ACCESS_KEY_ID)).thenReturn("access");
    when(mockEnvVars.get(AWS_SECRET_ACCESS_KEY)).thenReturn("secret");
    when(mockEnvVars.get(AWS_SESSION_TOKEN)).thenReturn("token");
    when(mockStepContext.get(EnvVars.class)).thenReturn(mockEnvVars);
    when(awsSecretKey.getPlainText()).thenReturn("");

    PowerMockito.mockStatic(DefaultAWSCredentialsProviderChain.class);
    when(DefaultAWSCredentialsProviderChain.getInstance()).thenThrow(new RuntimeException("Should not be accessing the default credentials provider chain."));

    AWSClientFactory awsClientFactory = new AWSClientFactory("keys", "", "", "", "", awsSecretKey, "", REGION, build, mockStepContext);

    assert(awsClientFactory.getCredentialsDescriptor().contains(stepCredentials));
}
 
Example #5
Source File: AWSClientFactoryTest.java    From aws-codebuild-jenkins-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void testStepContextBasicCreds() throws IOException, InterruptedException {
    EnvVars mockEnvVars = mock(EnvVars.class);
    when(mockEnvVars.get(AWS_ACCESS_KEY_ID)).thenReturn("access");
    when(mockEnvVars.get(AWS_SECRET_ACCESS_KEY)).thenReturn("secret");
    when(mockEnvVars.get(AWS_SESSION_TOKEN)).thenReturn(null);
    when(mockStepContext.get(EnvVars.class)).thenReturn(mockEnvVars);
    when(awsSecretKey.getPlainText()).thenReturn("");

    PowerMockito.mockStatic(DefaultAWSCredentialsProviderChain.class);
    when(DefaultAWSCredentialsProviderChain.getInstance()).thenThrow(new RuntimeException("Should not be accessing the default credentials provider chain."));

    AWSClientFactory awsClientFactory = new AWSClientFactory("keys", "", "", "", "", awsSecretKey, "", REGION, build, mockStepContext);

    assert(awsClientFactory.getCredentialsDescriptor().contains(stepCredentials));
}
 
Example #6
Source File: SqsConfigurationTest.java    From spring-cloud-aws with Apache License 2.0 6 votes vote down vote up
@Test
void configuration_withoutAwsCredentials_shouldCreateAClientWithDefaultCredentialsProvider()
		throws Exception {
	// Arrange & Act
	AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(
			ConfigurationWithMissingAwsCredentials.class);

	// Assert
	AmazonSQSBufferedAsyncClient bufferedAmazonSqsClient = applicationContext
			.getBean(AmazonSQSBufferedAsyncClient.class);
	AmazonSQSAsyncClient amazonSqsClient = (AmazonSQSAsyncClient) ReflectionTestUtils
			.getField(bufferedAmazonSqsClient, "realSQS");
	assertThat(DefaultAWSCredentialsProviderChain.class.isInstance(
			ReflectionTestUtils.getField(amazonSqsClient, "awsCredentialsProvider")))
					.isTrue();
}
 
Example #7
Source File: AWSCredentialsProviderControllerServiceTest.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void testDefaultAWSCredentialsProviderChain() throws Throwable {
    final TestRunner runner = TestRunners.newTestRunner(FetchS3Object.class);
    final AWSCredentialsProviderControllerService serviceImpl = new AWSCredentialsProviderControllerService();
    runner.addControllerService("awsCredentialsProvider", serviceImpl);

    runner.enableControllerService(serviceImpl);

    runner.assertValid(serviceImpl);
    final AWSCredentialsProviderService service = (AWSCredentialsProviderService) runner.getProcessContext()
            .getControllerServiceLookup().getControllerService("awsCredentialsProvider");
    Assert.assertNotNull(service);
    final AWSCredentialsProvider credentialsProvider = service.getCredentialsProvider();
    Assert.assertNotNull(credentialsProvider);
    assertEquals("credentials provider should be equal", DefaultAWSCredentialsProviderChain.class,
            credentialsProvider.getClass());
}
 
Example #8
Source File: ZipkinElasticsearchAwsStorageModule.java    From zipkin-aws with Apache License 2.0 6 votes vote down vote up
/** By default, get credentials from the {@link DefaultAWSCredentialsProviderChain} */
@Bean @ConditionalOnMissingBean
AWSCredentials.Provider credentials() {
  return new AWSCredentials.Provider() {
    final AWSCredentialsProvider delegate = new DefaultAWSCredentialsProviderChain();

    @Override public AWSCredentials get() {
      com.amazonaws.auth.AWSCredentials result = delegate.getCredentials();
      String sessionToken =
          result instanceof AWSSessionCredentials
              ? ((AWSSessionCredentials) result).getSessionToken()
              : null;
      return new AWSCredentials(
          result.getAWSAccessKeyId(), result.getAWSSecretKey(), sessionToken);
    }
  };
}
 
Example #9
Source File: HadoopFileUtils.java    From mrgeo with Apache License 2.0 6 votes vote down vote up
/**
 * Return an AmazonS3Client set up with the proper endpoint
 * defined in core-site.xml using a property like fs.s3a.endpoint.
 * This mimics code found in S3AFileSystem.
 *
 * @param conf
 * @param scheme
 * @return
 */
private static AmazonS3Client getS3Client(Configuration conf, String scheme)
{
  AmazonS3Client s3Client = new AmazonS3Client(new DefaultAWSCredentialsProviderChain());
  String endpointKey = "fs." + scheme.toLowerCase() + ".endpoint";
  String endPoint = conf.getTrimmed(endpointKey,"");
  log.debug("Using endpoint setting " + endpointKey);
  if (!endPoint.isEmpty()) {
    try {
      log.debug("Setting S3 client endpoint to " + endPoint);
      s3Client.setEndpoint(endPoint);
    } catch (IllegalArgumentException e) {
      String msg = "Incorrect endpoint: "  + e.getMessage();
      log.error(msg);
      throw new IllegalArgumentException(msg, e);
    }
  }
  return s3Client;
}
 
Example #10
Source File: InvocationClientConfigTest.java    From kafka-connect-lambda with Apache License 2.0 6 votes vote down vote up
@Test
public void minimalConfig() {
    InvocationClient.Builder builder = new InvocationClient.Builder();
    new InvocationClientConfig(builder,
        new HashMap<String, String>() {
        {
            put("aws.lambda.function.arn", "test-function");
        }
    });

    assertEquals("test-function", builder.getFunctionArn());
    assertNull(builder.getRegion());
    assertEquals(InvocationMode.SYNC, builder.getInvocationMode());
    assertEquals(InvocationFailure.STOP, builder.getFailureMode());
    assertEquals(Duration.ofMinutes(5), builder.getInvocationTimeout());
    assertNotNull(builder.getClientConfiguration());
    assertEquals(DefaultAWSCredentialsProviderChain.class, builder.getCredentialsProvider().getClass());
}
 
Example #11
Source File: GlueHiveMetastore.java    From presto with Apache License 2.0 6 votes vote down vote up
private static AWSCredentialsProvider getAwsCredentialsProvider(GlueHiveMetastoreConfig config)
{
    if (config.getAwsAccessKey().isPresent() && config.getAwsSecretKey().isPresent()) {
        return new AWSStaticCredentialsProvider(
                new BasicAWSCredentials(config.getAwsAccessKey().get(), config.getAwsSecretKey().get()));
    }
    if (config.getIamRole().isPresent()) {
        return new STSAssumeRoleSessionCredentialsProvider
                .Builder(config.getIamRole().get(), "presto-session")
                .withExternalId(config.getExternalId().orElse(null))
                .build();
    }
    if (config.getAwsCredentialsProvider().isPresent()) {
        return getCustomAWSCredentialsProvider(config.getAwsCredentialsProvider().get());
    }
    return DefaultAWSCredentialsProviderChain.getInstance();
}
 
Example #12
Source File: KinesisClientManager.java    From presto with Apache License 2.0 6 votes vote down vote up
@Inject
public KinesisClientManager(KinesisConfig config)
{
    if (!isNullOrEmpty(config.getAccessKey()) && !isNullOrEmpty(config.getSecretKey())) {
        BasicAWSCredentials awsCredentials = new BasicAWSCredentials(config.getAccessKey(), config.getSecretKey());
        this.client = new AmazonKinesisClient(awsCredentials);
        this.amazonS3Client = new AmazonS3Client(awsCredentials);
        this.dynamoDbClient = new AmazonDynamoDBClient(awsCredentials);
    }
    else {
        DefaultAWSCredentialsProviderChain defaultChain = new DefaultAWSCredentialsProviderChain();
        this.client = new AmazonKinesisClient(defaultChain);
        this.amazonS3Client = new AmazonS3Client(defaultChain);
        this.dynamoDbClient = new AmazonDynamoDBClient(defaultChain);
    }

    this.client.setEndpoint("kinesis." + config.getAwsRegion() + ".amazonaws.com");
    this.dynamoDbClient.setEndpoint("dynamodb." + config.getAwsRegion() + ".amazonaws.com");
}
 
Example #13
Source File: AwsSessionCredentialClient.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
private AWSSecurityTokenService awsSecurityTokenServiceClient(AwsCredentialView awsCredential) {
    if (!awsEnvironmentVariableChecker.isAwsAccessKeyAvailable(awsCredential)
            || !awsEnvironmentVariableChecker.isAwsSecretAccessKeyAvailable(awsCredential)) {
        LOGGER.debug("AWSSecurityTokenServiceClient will use aws metadata because environment variables are undefined");
        return AWSSecurityTokenServiceClientBuilder.standard()
                .withRegion(awsDefaultZoneProvider.getDefaultZone(awsCredential))
                .withCredentials(new InstanceProfileCredentialsProvider())
                .build();
    } else {
        LOGGER.debug("AWSSecurityTokenServiceClient will use environment variables");
        return AWSSecurityTokenServiceClientBuilder.standard()
                .withRegion(awsDefaultZoneProvider.getDefaultZone(awsCredential))
                .withCredentials(DefaultAWSCredentialsProviderChain.getInstance())
                .build();
    }
}
 
Example #14
Source File: IntegrationTestHelper.java    From strongbox with Apache License 2.0 6 votes vote down vote up
public static void cleanUpFromPreviousRuns(Regions testRegion, String groupPrefix) {
    LOG.info("Cleaning up from previous test runs...");

    // Get time an hour ago to clean up anything that was created more than an hour ago. That should be more than
    // enough time for test runs so anything left over by that time will be junk to clean up.
    Date createdBeforeThreshold = new Date(System.currentTimeMillis() - (60 * 60 * 1000));

    // Resource prefix for the test groups so we only clean up the resources related to the tests.
    // TODO is there a method somewhere that will construct this for me so it will always match the
    // actual names constructed by the code?
    String testResourcePrefix = String.format(
            "strongbox_%s_%s", testRegion.getName(),
            AWSResourceNameSerialization.encodeSecretsGroupName(groupPrefix));

    AWSCredentialsProvider awsCredentials = new DefaultAWSCredentialsProviderChain();

    cleanUpDynamoDBTables(testRegion, testResourcePrefix, createdBeforeThreshold, awsCredentials);
    cleanUpKMSKeys(testRegion, testResourcePrefix, createdBeforeThreshold, awsCredentials);
    cleanUpIAM(testRegion, testResourcePrefix, createdBeforeThreshold, awsCredentials);
}
 
Example #15
Source File: KMSProviderBuilderIntegrationTests.java    From aws-encryption-sdk-java with Apache License 2.0 5 votes vote down vote up
@Test
public void whenBuilderCloned_credentialsAndConfigurationAreRetained() throws Exception {
    AWSCredentialsProvider customProvider1 = spy(new DefaultAWSCredentialsProviderChain());
    AWSCredentialsProvider customProvider2 = spy(new DefaultAWSCredentialsProviderChain());

    KmsMasterKeyProvider.Builder builder = KmsMasterKeyProvider.builder()
            .withCredentials(customProvider1)
            .withKeysForEncryption(KMSTestFixtures.TEST_KEY_IDS[0]);

    KmsMasterKeyProvider.Builder builder2 = builder.clone();

    // This will mutate the first builder to add the new key and change the creds, but leave the clone unchanged.
    MasterKeyProvider<?> mkp2 = builder.withKeysForEncryption(KMSTestFixtures.TEST_KEY_IDS[1]).withCredentials(customProvider2).build();
    MasterKeyProvider<?> mkp1 = builder2.build();

    CryptoResult<byte[], ?> result = new AwsCrypto().encryptData(mkp1, new byte[0]);

    assertEquals(KMSTestFixtures.TEST_KEY_IDS[0], result.getMasterKeyIds().get(0));
    assertEquals(1, result.getMasterKeyIds().size());
    verify(customProvider1, atLeastOnce()).getCredentials();
    verify(customProvider2, never()).getCredentials();

    reset(customProvider1, customProvider2);

    result = new AwsCrypto().encryptData(mkp2, new byte[0]);

    assertTrue(result.getMasterKeyIds().contains(KMSTestFixtures.TEST_KEY_IDS[0]));
    assertTrue(result.getMasterKeyIds().contains(KMSTestFixtures.TEST_KEY_IDS[1]));
    assertEquals(2, result.getMasterKeyIds().size());
    verify(customProvider1, never()).getCredentials();
    verify(customProvider2, atLeastOnce()).getCredentials();
}
 
Example #16
Source File: MultipartUpload.java    From tutorials with MIT License 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    String existingBucketName = "baeldung-bucket";
    String keyName = "my-picture.jpg";
    String filePath = "documents/my-picture.jpg";

    AmazonS3 amazonS3 = AmazonS3ClientBuilder
            .standard()
            .withCredentials(new DefaultAWSCredentialsProviderChain())
            .withRegion(Regions.DEFAULT_REGION)
            .build();

    int maxUploadThreads = 5;

    TransferManager tm = TransferManagerBuilder
            .standard()
            .withS3Client(amazonS3)
            .withMultipartUploadThreshold((long) (5 * 1024 * 1024))
            .withExecutorFactory(() -> Executors.newFixedThreadPool(maxUploadThreads))
            .build();

    ProgressListener progressListener =
            progressEvent -> System.out.println("Transferred bytes: " + progressEvent.getBytesTransferred());

    PutObjectRequest request = new PutObjectRequest(existingBucketName, keyName, new File(filePath));

    request.setGeneralProgressListener(progressListener);

    Upload upload = tm.upload(request);

    try {
        upload.waitForCompletion();
        System.out.println("Upload complete.");
    } catch (AmazonClientException e) {
        System.out.println("Error occurred while uploading file");
        e.printStackTrace();
    }
}
 
Example #17
Source File: TestVectorRunner.java    From aws-encryption-sdk-java with Apache License 2.0 5 votes vote down vote up
@Parameterized.Parameters(name="Compatibility Test: {0}")
@SuppressWarnings("unchecked")
public static Collection<Object[]> data() throws Exception {
    final String zipPath = System.getProperty("testVectorZip");
    if (zipPath == null) {
        return Collections.emptyList();
    }

    final JarURLConnection jarConnection = (JarURLConnection) new URL("jar:" + zipPath + "!/").openConnection();

    try (JarFile jar = jarConnection.getJarFile()) {
        final Map<String, Object> manifest = readJsonMapFromJar(jar, "manifest.json");

        final Map<String, Object> metaData = (Map<String, Object>) manifest.get("manifest");

        // We only support "awses-decrypt" type manifests right now
        if (!"awses-decrypt".equals(metaData.get("type"))) {
            throw new IllegalArgumentException("Unsupported manifest type: " + metaData.get("type"));
        }

        if (!Integer.valueOf(1).equals(metaData.get("version"))) {
            throw new IllegalArgumentException("Unsupported manifest version: " + metaData.get("version"));
        }

        final Map<String, KeyEntry> keys = parseKeyManifest(readJsonMapFromJar(jar, (String) manifest.get("keys")));

        final KmsMasterKeyProvider kmsProv = KmsMasterKeyProvider
                                                     .builder()
                                                     .withCredentials(new DefaultAWSCredentialsProviderChain())
                                                     .build();

        List<Object[]> testCases = new ArrayList<>();
        for (Map.Entry<String, Map<String, Object>> testEntry :
                ((Map<String, Map<String, Object>>) manifest.get("tests")).entrySet()) {
            testCases.add(new Object[]{testEntry.getKey(),
                    parseTest(testEntry.getKey(), testEntry.getValue(), keys, jar, kmsProv)});
        }
        return testCases;
    }
}
 
Example #18
Source File: LambdaClientConfig.java    From aws-lambda-jenkins-plugin with MIT License 5 votes vote down vote up
public AWSLambdaClient getClient() {
    if(useDefaultAWSCredentials){
        return new AWSLambdaClient(new DefaultAWSCredentialsProviderChain(), getClientConfiguration())
                .withRegion(Region.getRegion(Regions.fromName(region)));
    } else {
        return new AWSLambdaClient(new BasicAWSCredentials(accessKeyId, secretKey), getClientConfiguration())
                .withRegion(Region.getRegion(Regions.fromName(region)));
    }
}
 
Example #19
Source File: ContextCredentialsAutoConfigurationTest.java    From spring-cloud-aws with Apache License 2.0 5 votes vote down vote up
@Test
void credentialsProvider_noExplicitCredentialsProviderConfigured_configuresDefaultAwsCredentialsProviderChain() {
	// @checkstyle:on
	this.contextRunner.run((context) -> {
		AWSCredentialsProvider awsCredentialsProvider = context.getBean(
				AmazonWebserviceClientConfigurationUtils.CREDENTIALS_PROVIDER_BEAN_NAME,
				AWSCredentialsProvider.class);
		assertThat(awsCredentialsProvider).isNotNull()
				.isInstanceOf(DefaultAWSCredentialsProviderChain.class);
	});

}
 
Example #20
Source File: ClientAuthenticationFactory.java    From spring-cloud-vault with Apache License 2.0 5 votes vote down vote up
private static AWSCredentialsProvider getAwsCredentialsProvider() {

			DefaultAWSCredentialsProviderChain backingCredentialsProvider = DefaultAWSCredentialsProviderChain
					.getInstance();

			// Eagerly fetch credentials preventing lag during the first, actual login.
			AWSCredentials firstAccess = backingCredentialsProvider.getCredentials();

			AtomicReference<AWSCredentials> once = new AtomicReference<>(firstAccess);

			return new AWSCredentialsProvider() {

				@Override
				public AWSCredentials getCredentials() {

					if (once.compareAndSet(firstAccess, null)) {
						return firstAccess;
					}

					return backingCredentialsProvider.getCredentials();
				}

				@Override
				public void refresh() {
					backingCredentialsProvider.refresh();
				}
			};
		}
 
Example #21
Source File: ZipkinKinesisCredentialsConfiguration.java    From zipkin-aws with Apache License 2.0 5 votes vote down vote up
private static AWSCredentialsProvider getDefaultCredentialsProvider(
    ZipkinKinesisCollectorProperties properties) {
  AWSCredentialsProvider provider = new DefaultAWSCredentialsProviderChain();

  // Create credentials provider from ID and secret if given.
  if (!isNullOrEmpty(properties.getAwsAccessKeyId())
      && !isNullOrEmpty(properties.getAwsSecretAccessKey())) {
    provider =
        new AWSStaticCredentialsProvider(
            new BasicAWSCredentials(properties.getAwsAccessKeyId(), properties.getAwsSecretAccessKey()));
  }

  return provider;
}
 
Example #22
Source File: LoadingBayApp.java    From data-highway with Apache License 2.0 5 votes vote down vote up
@Bean
AmazonS3 s3(
    @Value("${s3.endpoint.url}") String s3EndpointUrl,
    @Value("${s3.endpoint.signingRegion}") String signingRegion) {
  return AmazonS3Client
      .builder()
      .withCredentials(new DefaultAWSCredentialsProviderChain())
      .withEndpointConfiguration(new EndpointConfiguration(s3EndpointUrl, signingRegion))
      .build();
}
 
Example #23
Source File: ProducerUtils.java    From kinesis-aggregation with Apache License 2.0 5 votes vote down vote up
/**
 * Create a new Kinesis producer for publishing to Kinesis.
 * 
 * @param region The region of the Kinesis stream to publish to.
 * 
 * @return An Amazon Kinesis producer for publishing to a Kinesis stream.
 */
public static AmazonKinesis getKinesisProducer(String region)
{
    ClientConfiguration config = new ClientConfiguration();
    config.setMaxConnections(25);
    config.setConnectionTimeout(60000);
    config.setSocketTimeout(60000);

    AmazonKinesis producer = new AmazonKinesisClient(new DefaultAWSCredentialsProviderChain(), config);
    producer.setRegion(Region.getRegion(Regions.fromName(region)));

    return producer;
}
 
Example #24
Source File: AWSClientFactory.java    From pipeline-aws-plugin with Apache License 2.0 5 votes vote down vote up
private static AWSCredentialsProvider getCredentials(EnvVars vars) {
	AWSCredentialsProvider provider = handleStaticCredentials(vars);
	if (provider != null) {
		return provider;
	}

	provider = handleProfile(vars);
	if (provider != null) {
		return provider;
	}

	return new DefaultAWSCredentialsProviderChain();
}
 
Example #25
Source File: LDAPIAMPoller.java    From aws-iam-ldap-bridge with Apache License 2.0 5 votes vote down vote up
public LDAPIAMPoller(DirectoryService directoryService) throws LdapException {
    this.directory = directoryService;

    credentials = new DefaultAWSCredentialsProviderChain();
    try {
        credentials.getCredentials(); // throws
    } catch (AmazonClientException ex) {
        LOG.error("AWS credentials error", ex);
        throw new LdapException("Unable to initialze AWS poller - cannot retrieve valid credentials");
    }
    utils = new ApacheDSUtils(directory);
    runner = new Runner(directory);
    LOG.info("IAMPoller created");
}
 
Example #26
Source File: SimpleStorageServiceWagon.java    From lambadaframework with MIT License 5 votes vote down vote up
@Override
protected void connectToRepository(Repository repository, AuthenticationInfo authenticationInfo,
                                   ProxyInfoProvider proxyInfoProvider) throws AuthenticationException {
    if (this.amazonS3 == null) {

        ClientConfiguration clientConfiguration = S3Utils.getClientConfiguration(proxyInfoProvider);

        this.bucketName = S3Utils.getBucketName(repository);
        this.baseDirectory = S3Utils.getBaseDirectory(repository);

        this.amazonS3 = new AmazonS3Client(new DefaultAWSCredentialsProviderChain(), clientConfiguration);
        Region region = Region.fromLocationConstraint(this.amazonS3.getBucketLocation(this.bucketName));
        this.amazonS3.setEndpoint(region.getEndpoint());
    }
}
 
Example #27
Source File: SNSNotificationsConfig.java    From metacat with Apache License 2.0 5 votes vote down vote up
/**
 * If SNS notifications are desired and no existing client has been created elsewhere
 * in the application create a default client here.
 *
 * @return The configured SNS client
 */
//TODO: See what spring-cloud-aws would provide automatically...
@Bean
@ConditionalOnMissingBean(AmazonSNS.class)
public AmazonSNS amazonSNS() {
    return new AmazonSNSClient(DefaultAWSCredentialsProviderChain.getInstance());
}
 
Example #28
Source File: KinesisDispatcher.java    From haystack-agent with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
AWSCredentialsProvider buildCredsProvider(final Map<String, String> conf) {
    final Object stsRoleArn = conf.remove(STS_ROLE_ARN);
    final Object awsAccessKey = conf.remove(AWS_ACCESS_KEY);
    final Object awsSecretKey = conf.remove(AWS_SECRET_KEY);

    if (Objects.nonNull(awsAccessKey) && Objects.nonNull(awsSecretKey) && Objects.nonNull(stsRoleArn)) {
        return new STSAssumeRoleSessionCredentialsProvider.Builder(stsRoleArn.toString(), "haystack-agent")
            .withStsClient(
                AWSSecurityTokenServiceClientBuilder.standard()
                    .withCredentials(
                        new AWSStaticCredentialsProvider(new BasicAWSCredentials(awsAccessKey.toString(), awsSecretKey.toString()))
                    )
                    .withRegion(conf.get(AWS_REGION))
                    .build()
            ).build();
    } else if (Objects.nonNull(awsAccessKey) && Objects.nonNull(awsSecretKey)) {
        LOGGER.info("Using static credential provider using aws access and secret keys");
        return new AWSStaticCredentialsProvider(
                new BasicAWSCredentials(awsAccessKey.toString(), awsSecretKey.toString()));
    } else {
        if (Objects.nonNull(stsRoleArn)) {
            LOGGER.info("Using aws sts credential provider with role arn={}", stsRoleArn);
            return new STSProfileCredentialsServiceProvider(
                    new RoleInfo().withRoleArn(stsRoleArn.toString()).withRoleSessionName("haystack-agent"));
        } else {
            return DefaultAWSCredentialsProviderChain.getInstance();
        }
    }
}
 
Example #29
Source File: StrongboxGUI.java    From strongbox with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    Singleton.secretsGroupManager = new DefaultSecretsGroupManager();
    Singleton.region = Region.EU_WEST_1;
    Singleton.randomGenerator = new KMSRandomGenerator();
    Singleton.principalAutoSuggestion = PrincipalAutoSuggestion.fromCredentials(new DefaultAWSCredentialsProviderChain(), new ClientConfiguration());
    StrongboxGUI strongboxGUI = new StrongboxGUI();
    strongboxGUI.run();
}
 
Example #30
Source File: ContextCredentialsAutoConfiguration.java    From spring-cloud-aws with Apache License 2.0 5 votes vote down vote up
@Bean(name = CREDENTIALS_PROVIDER_BEAN_NAME)
@ConditionalOnMissingBean(name = CREDENTIALS_PROVIDER_BEAN_NAME)
public AWSCredentialsProvider awsCredentialsProvider(
		AwsCredentialsProperties properties) {

	List<AWSCredentialsProvider> providers = resolveCredentialsProviders(properties);

	if (providers.isEmpty()) {
		return new DefaultAWSCredentialsProviderChain();
	}
	else {
		return new AWSCredentialsProviderChain(providers);
	}
}