Java Code Examples for com.amazonaws.auth.AWSCredentials

The following are top voted examples for showing how to use com.amazonaws.auth.AWSCredentials. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: cyberduck   File: AmazonIdentityConfiguration.java   View source code 9 votes vote down vote up
private AmazonIdentityManagement client() {
    return AmazonIdentityManagementClientBuilder.standard()
            .withCredentials(new AWSStaticCredentialsProvider(new AWSCredentials() {
                @Override
                public String getAWSAccessKeyId() {
                    return bookmark.getCredentials().getUsername();
                }

                @Override
                public String getAWSSecretKey() {
                    return bookmark.getCredentials().getPassword();
                }
            }))
            .withClientConfiguration(configuration)
            .withRegion(Regions.DEFAULT_REGION).build();
}
 
Example 2
Project: hekate   File: AwsCredentialsSupplier.java   View source code 6 votes vote down vote up
@Override
public Credentials get() {
    if (getIdentity() == null || getIdentity().trim().isEmpty() || getCredential() == null || getCredential().trim().isEmpty()) {
        DefaultAWSCredentialsProviderChain chain = new DefaultAWSCredentialsProviderChain();

        AWSCredentials cred = chain.getCredentials();

        if (cred instanceof BasicSessionCredentials) {
            BasicSessionCredentials sesCred = (BasicSessionCredentials)cred;

            return new SessionCredentials.Builder()
                .identity(sesCred.getAWSAccessKeyId())
                .credential(sesCred.getAWSSecretKey())
                .sessionToken(sesCred.getSessionToken())
                .build();
        } else {
            return new Credentials.Builder<>()
                .identity(cred.getAWSAccessKeyId())
                .credential(cred.getAWSSecretKey())
                .build();
        }
    }

    return super.get();
}
 
Example 3
Project: oscm   File: EC2CommunicationTest.java   View source code 6 votes vote down vote up
@Test
public void testAWSCredentials() throws Exception {
    // Ask for connection
    AmazonEC2 client = ec2comm.getEC2();
    assertNotNull(client);
    assertNotNull(credProvider);

    AWSCredentials credentials = credProvider.getCredentials();
    assertEquals("access_key", credentials.getAWSAccessKeyId());
    assertEquals("secret_key", credentials.getAWSSecretKey());

    credProvider.refresh();
    credentials = credProvider.getCredentials();
    assertEquals("access_key", credentials.getAWSAccessKeyId());
    assertEquals("secret_key", credentials.getAWSSecretKey());

}
 
Example 4
Project: cyberduck   File: AWSCredentialsConfigurator.java   View source code 6 votes vote down vote up
@Override
public Credentials configure(final Host host) {
    final Credentials credentials = host.getCredentials();
    // Only for AWS
    if(host.getHostname().endsWith(PreferencesFactory.get().getProperty("s3.hostname.default"))) {
        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());
                    break;
                }
                catch(SdkClientException e) {
                    log.debug(String.format("Ignore failure loading credentials from provider %s", provider));
                    // Continue searching with next provider
                }
            }
        }
    }
    return credentials;
}
 
Example 5
Project: dynamodb-client-web-gui   File: AwsConfigTest.java   View source code 6 votes vote down vote up
@Test
public void shouldHaveAwsCredentialsIntanceWhenEndpointUrlIsNotProvidedAndProfileIsProvided() {
    ReflectionTestUtils.setField(config, "ENDPOINT_URL", "");
    ReflectionTestUtils.setField(config, "PROFILE", "default");
    Assert.isInstanceOf(AWSCredentials.class,
            config.awsCredentials(new StubProfileCredentialsProvider()));
}
 
Example 6
Project: aws-codecommit-trigger-plugin   File: MockAwsSqs.java   View source code 6 votes vote down vote up
private void start() throws IOException {
    //this.port = findFreeLocalPort(); @see https://github.com/findify/sqsmock/pull/7
    this.api = new SQSService(this.port, 1);
    this.api.start();

    AWSCredentials credentials = new AnonymousAWSCredentials();
    this.sqsClient = new MockSQSClient(credentials);

    this.endpoint = String.format("http://localhost:%s", this.port);
    this.sqsClient.setEndpoint(endpoint);

    this.sqsUrl = this.sqsClient.createQueue(this.getClass().getSimpleName()).getQueueUrl();
    ((MockSQSClient)this.sqsClient).setQueueUrl(this.sqsUrl);

    this.started = true;
}
 
Example 7
Project: ibm-cos-sdk-java   File: ProfileCredentialsProviderTest.java   View source code 6 votes vote down vote up
@Test
public void testEnvironmentVariable() throws Exception {
    Map<String, String> immutableEnv = System.getenv();

    Class<?> unMap = Class.forName("java.util.Collections$UnmodifiableMap");
    Field m = unMap.getDeclaredField("m");
    m.setAccessible(true);

    @SuppressWarnings("unchecked")
    Map<String, String> env = (Map<String, String>) m.get(immutableEnv);

    try {
        env.put(AwsProfileNameLoader.AWS_PROFILE_ENVIRONMENT_VARIABLE, "test");

        ProfileCredentialsProvider provider = newProvider();

        AWSCredentials credentials = provider.getCredentials();
        Assert.assertEquals("test", credentials.getAWSAccessKeyId());
        Assert.assertEquals("test key", credentials.getAWSSecretKey());

    } finally {
        env.remove(AwsProfileNameLoader.AWS_PROFILE_ENVIRONMENT_VARIABLE);
    }
}
 
Example 8
Project: ibm-cos-sdk-java   File: ProfilesConfigFileWriterTest.java   View source code 6 votes vote down vote up
private static void assertEqualCredentials(AWSCredentials expected, AWSCredentials actual) {
    assertEquals(expected.getAWSAccessKeyId(),
            actual.getAWSAccessKeyId());
    assertEquals(expected.getAWSAccessKeyId(),
            actual.getAWSAccessKeyId());

    if (expected instanceof AWSSessionCredentials) {
        assertTrue(actual instanceof AWSSessionCredentials);

        AWSSessionCredentials expectedSession = (AWSSessionCredentials)expected;
        AWSSessionCredentials actualSession   = (AWSSessionCredentials)actual;
        assertEquals(expectedSession.getSessionToken(),
                actualSession.getSessionToken());
    } else {
        assertFalse(actual instanceof AWSSessionCredentials);
    }
}
 
Example 9
Project: ibm-cos-sdk-java   File: CredentialProfilesTest.java   View source code 6 votes vote down vote up
/**
 * Tests two profiles having same name. The second profile overrides the first profile. Also
 * checks if the AWS Access Key ID and AWS Secret Access Key are mapped properly under the
 * profile.
 */
@Test
public void testTwoProfileWithSameName() throws URISyntaxException {
    ProfilesConfigFile profile = new ProfilesConfigFile(
            ProfileResourceLoader.profilesWithSameProfileName().asFile());

    AWSCredentials defaultCred = profile.getCredentials(DEFAULT_PROFILE_NAME);
    assertNotNull(defaultCred);
    assertTrue(defaultCred instanceof BasicAWSCredentials);

    AWSCredentials testCred = profile.getCredentials(PROFILE_NAME_TEST);
    assertNotNull(testCred);
    assertTrue(testCred instanceof AWSSessionCredentials);
    AWSSessionCredentials testSessionCred = (AWSSessionCredentials) testCred;
    assertEquals(testSessionCred.getAWSAccessKeyId(), "testProfile2");
    assertEquals(testSessionCred.getAWSSecretKey(), "testProfile2");
    assertEquals(testSessionCred.getSessionToken(), "testProfile2");

}
 
Example 10
Project: ibm-cos-sdk-java   File: AmazonWebServiceRequestTest.java   View source code 6 votes vote down vote up
private static void verifyBaseAfterCopy(final ProgressListener listener,
        final AWSCredentials credentials,
        final RequestMetricCollector collector,
        final AmazonWebServiceRequest from, final AmazonWebServiceRequest to) {
    RequestClientOptions toOptions;
    Map<String, String> headers = to.getCustomRequestHeaders();
    assertTrue(2 == headers.size());
    assertEquals("v1", headers.get("k1"));
    assertEquals("v2", headers.get("k2"));
    Map<String, List<String>> parmas = to.getCustomQueryParameters();
    assertTrue(2 == parmas.size());
    assertEquals(Arrays.asList("v1"), parmas.get("k1"));
    assertEquals(Arrays.asList("v2a", "v2b"), parmas.get("k2"));
    assertSame(listener, to.getGeneralProgressListener());
    assertSame(credentials, to.getRequestCredentials());
    assertSame(collector, to.getRequestMetricCollector());

    assertTrue(1234 == to.getReadLimit());
    toOptions = to.getRequestClientOptions();
    assertEquals(
            from.getRequestClientOptions().getClientMarker(
                    Marker.USER_AGENT),
            toOptions.getClientMarker(Marker.USER_AGENT));
    assertTrue(1234 == toOptions.getReadLimit());
}
 
Example 11
Project: ibm-cos-sdk-java   File: CredentialUtilsTest.java   View source code 6 votes vote down vote up
@Test
public void request_credentials_takes_precendence_over_client_credentials() {
    final String awsAccessKeyId = "foo";
    final String awsSecretAccessKey = "bar";
    final AWSCredentials reqCredentials = new BasicAWSCredentials(awsAccessKeyId,
                                                                  awsSecretAccessKey);
    EmptyAmazonWebServiceRequest req = new EmptyAmazonWebServiceRequest();
    req.setRequestCredentials(reqCredentials);
    AWSCredentialsProvider actual = CredentialUtils.getCredentialsProvider(req,
                                                                           null);

    Assert.assertThat(actual, Matchers.instanceOf(StaticCredentialsProvider
                                                          .class));
    assertEquals(awsAccessKeyId, actual.getCredentials().getAWSAccessKeyId());
    assertEquals(awsSecretAccessKey, actual.getCredentials().getAWSSecretKey());
}
 
Example 12
Project: ibm-cos-sdk-java   File: S3QueryStringSigner.java   View source code 6 votes vote down vote up
public void sign(SignableRequest<?> request, AWSCredentials credentials) throws SdkClientException {
    AWSCredentials sanitizedCredentials = sanitizeCredentials(credentials);

    if ( sanitizedCredentials instanceof AWSSessionCredentials ) {
        addSessionCredentials(request, (AWSSessionCredentials) sanitizedCredentials);
    }

    String expirationInSeconds = Long.toString(expiration.getTime() / 1000L);

    String canonicalString = RestUtils.makeS3CanonicalString(
            httpVerb, resourcePath, request, expirationInSeconds);

    String signature = super.signAndBase64Encode(canonicalString, sanitizedCredentials.getAWSSecretKey(), SigningAlgorithm.HmacSHA1);

    request.addParameter("AWSAccessKeyId", sanitizedCredentials.getAWSAccessKeyId());
    request.addParameter("Expires", expirationInSeconds);
    request.addParameter("Signature", signature);
}
 
Example 13
Project: elasticsearch_my   File: AwsS3ServiceImplTests.java   View source code 5 votes vote down vote up
protected void launchAWSCredentialsWithElasticsearchSettingsTest(Settings singleRepositorySettings, Settings settings,
                                                                 String expectedKey, String expectedSecret) {
    String configName = InternalAwsS3Service.CLIENT_NAME.get(singleRepositorySettings);
    AWSCredentials credentials = InternalAwsS3Service.buildCredentials(logger, deprecationLogger, settings,
        singleRepositorySettings, configName).getCredentials();
    assertThat(credentials.getAWSAccessKeyId(), is(expectedKey));
    assertThat(credentials.getAWSSecretKey(), is(expectedSecret));
}
 
Example 14
Project: shabdiz   File: AmazonEC2HostProvider.java   View source code 5 votes vote down vote up
public AmazonEC2HostProvider(final AWSCredentials credentials, final ClientConfiguration configuration, String endpoint, Function<Instance, Host> instance_converter) {

        this.instance_converter = instance_converter;
        ec2_client = new AmazonEC2Client(credentials, configuration);
        ec2_client.setEndpoint(endpoint);
        next_host_index = new AtomicInteger();
    }
 
Example 15
Project: syndesis-qe   File: S3Utils.java   View source code 5 votes vote down vote up
public S3Utils() {
	accountsDirectory = AccountsDirectory.getInstance();
	final Account s3Account = accountsDirectory.getAccount("s3").get();
	final AWSCredentials credentials = new BasicAWSCredentials(
			s3Account.getProperty("accessKey"), s3Account.getProperty("secretKey")
	);

	s3client = AmazonS3ClientBuilder
			.standard()
			.withCredentials(new AWSStaticCredentialsProvider(credentials))
			.withRegion(Regions.US_WEST_1)
			.build();
}
 
Example 16
Project: radosgw-admin4j   File: BaseTest.java   View source code 5 votes vote down vote up
protected static AmazonS3 createS3(String accessKey, String secretKey) {
  AWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);
  ClientConfiguration clientConfig = new ClientConfiguration();
  clientConfig.setProtocol(Protocol.HTTP);
  clientConfig.withSignerOverride("S3SignerType");
  //noinspection deprecation
  AmazonS3 s3 = new AmazonS3Client(credentials, clientConfig);
  s3.setEndpoint(s3Endpoint);
  return s3;
}
 
Example 17
Project: oscm   File: EC2Communication.java   View source code 5 votes vote down vote up
/**
 * Constructor
 * 
 * @param ph
 */
public EC2Communication(PropertyHandler ph) {
    this.ph = ph;
    final String secretKey = ph.getSecretKey();
    final String accessKeyId = ph.getAccessKeyId();

    credentialsProvider = new AWSCredentialsProvider() {

        @Override
        public void refresh() {
        }

        @Override
        public AWSCredentials getCredentials() {

            return new AWSCredentials() {

                @Override
                public String getAWSSecretKey() {
                    return secretKey;
                }

                @Override
                public String getAWSAccessKeyId() {
                    return accessKeyId;
                }
            };
        }
    };
}
 
Example 18
Project: circus-train   File: JceksAWSCredentialProvider.java   View source code 5 votes vote down vote up
@Override
public AWSCredentials getCredentials() {
  if (credentials == null) {
    refresh();
  }
  return credentials;
}
 
Example 19
Project: circus-train   File: JceksAWSCredentialProviderTest.java   View source code 5 votes vote down vote up
@Test
public void credentialsFromFile() throws IOException {
  String jceksPath = "jceks://file" + dataFolder.getFile("aws.jceks").getAbsolutePath();
  JceksAWSCredentialProvider provider = new JceksAWSCredentialProvider(jceksPath);
  AWSCredentials credentials = provider.getCredentials();
  assertThat(credentials.getAWSAccessKeyId(), is("access"));
  assertThat(credentials.getAWSSecretKey(), is("secret"));
}
 
Example 20
Project: circus-train   File: JceksAWSCredentialProviderTest.java   View source code 5 votes vote down vote up
@Test
public void credentialsFromConf() throws IOException {
  when(conf.getPassword(AWSConstants.ACCESS_KEY)).thenReturn("accessKey".toCharArray());
  when(conf.getPassword(AWSConstants.SECRET_KEY)).thenReturn("secretKey".toCharArray());
  JceksAWSCredentialProvider provider = new JceksAWSCredentialProvider(conf);
  AWSCredentials credentials = provider.getCredentials();
  assertThat(credentials.getAWSAccessKeyId(), is("accessKey"));
  assertThat(credentials.getAWSSecretKey(), is("secretKey"));
}
 
Example 21
Project: rxjava2-aws   File: AwsClients.java   View source code 5 votes vote down vote up
public static AmazonSQS createSqsClient(AWSCredentials credentials, ClientConfiguration cc, Regions region) {
    return AmazonSQSClientBuilder //
            .standard() //
            .withCredentials(new AWSStaticCredentialsProvider(credentials)) //
            .withRegion(region) //
            .build();
}
 
Example 22
Project: rxjava2-aws   File: AwsClients.java   View source code 5 votes vote down vote up
public static AmazonS3 createS3Client(AWSCredentials credentials, ClientConfiguration cc, Regions region) {
    return AmazonS3ClientBuilder //
            .standard() //
            .withCredentials(new AWSStaticCredentialsProvider(credentials)) //
            .withRegion(region) //
            .build();
}
 
Example 23
Project: rxjava2-aws   File: AwsClientsTest.java   View source code 5 votes vote down vote up
@Test
public void tests3() {
	AwsClients.createS3Client(new AWSCredentials() {

		@Override
		public String getAWSSecretKey() {
			return "a";
		}

		@Override
		public String getAWSAccessKeyId() {
			return "b";
		}
	}, new ClientConfiguration(), Regions.AP_SOUTHEAST_2);
}
 
Example 24
Project: rxjava2-aws   File: AwsClientsTest.java   View source code 5 votes vote down vote up
@Test
public void testSqs() {
	AwsClients.createSqsClient(new AWSCredentials() {

		@Override
		public String getAWSSecretKey() {
			return "a";
		}

		@Override
		public String getAWSAccessKeyId() {
			return "b";
		}
	}, new ClientConfiguration(), Regions.AP_SOUTHEAST_2);
}
 
Example 25
Project: async-sqs   File: SqsAwsSdkAction.java   View source code 5 votes vote down vote up
@Override
public Request toHttpRequest(AWSCredentials credentials) {
    URI fullUri = URI.create(requestUrl);
    URI endpoint = URI.create(fullUri.getScheme() + SCHEME_SEPERATOR + fullUri.getHost());

    awsHttpRequest = marshaller.marshall(request);
    awsHttpRequest.setEndpoint(endpoint);
    awsHttpRequest.setResourcePath(fullUri.getPath());
    requestSigner.setServiceName(SHORT_SERVICE_NAME);

    requestSigner.sign(awsHttpRequest, credentials);
    return requestConverter.apply(awsHttpRequest);
}
 
Example 26
Project: unitstack   File: MockSnsTest.java   View source code 5 votes vote down vote up
@Before
public void setup() {
  EndpointConfiguration endpoint =
      new EndpointConfiguration(UNIT_STACK_URL + ":" + SNS_PORT, Region.EU_Frankfurt.name());
  AWSCredentials credentials = new BasicAWSCredentials("key", "secret");
  AWSCredentialsProvider credentialsProvider = new AWSStaticCredentialsProvider(credentials);

  sns = AmazonSNSAsyncClientBuilder.standard().withEndpointConfiguration(endpoint)
      .withCredentials(credentialsProvider).build();
}
 
Example 27
Project: unitstack   File: MockS3Test.java   View source code 5 votes vote down vote up
@Before
public void setup() {
  MockParameters params = new MockParameters();
  params.setMockRegion("EU");
  mockS3(params);
  
  EndpointConfiguration endpoint =
      new EndpointConfiguration(UNIT_STACK_URL + ":" + S3_PORT, Region.EU_Frankfurt.name());
  AWSCredentials credentials = new BasicAWSCredentials("key", "secret");
  AWSCredentialsProvider credentialsProvider = new AWSStaticCredentialsProvider(credentials);

  s3 = AmazonS3ClientBuilder.standard().withEndpointConfiguration(endpoint)
      .withCredentials(credentialsProvider).build();
}
 
Example 28
Project: unitstack   File: MockSqsTest.java   View source code 5 votes vote down vote up
@Before
public void setup() {
  mockSqs(null);
  
  EndpointConfiguration endpoint =
      new EndpointConfiguration(UNIT_STACK_URL + ":" + SQS_PORT, "eu-central-1");
  AWSCredentials credentials = new BasicAWSCredentials("key", "secret");
  AWSCredentialsProvider credentialsProvider = new AWSStaticCredentialsProvider(credentials);

  sqs = AmazonSQSAsyncClientBuilder.standard().withEndpointConfiguration(endpoint)
      .withCredentials(credentialsProvider).build();
}
 
Example 29
Project: dynamodb-client-web-gui   File: AwsConfig.java   View source code 5 votes vote down vote up
@Bean
@DependsOn("awsCredentials")
public AmazonDynamoDB amazonDynamoDBClient(AWSCredentials awsCredentials) {
    AmazonDynamoDBClient awsClient = new AmazonDynamoDBClient(awsCredentials);
    if (!ENDPOINT_URL.isEmpty()) {
        LOGGER.info("END POINT " + ENDPOINT_URL);
        awsClient.setEndpoint(ENDPOINT_URL);
        awsClient.setSignerRegionOverride("local");
    }
    return awsClient;
}
 
Example 30
Project: dynamodb-client-web-gui   File: AwsConfigTest.java   View source code 5 votes vote down vote up
@Test
public void shouldHaveAwsCredentialsIntanceWhenEndpointUrlIsNotProvided() {
    ReflectionTestUtils.setField(config, "ENDPOINT_URL", "");
    ReflectionTestUtils.setField(config, "PROFILE", "");
    Assert.isInstanceOf(AWSCredentials.class,
            config.awsCredentials(new StubProfileCredentialsProvider()));
}
 
Example 31
Project: CloudPrime   File: Connection.java   View source code 5 votes vote down vote up
public static String getOwnIP()
{
	AWSCredentials credentials = null;
	try
	{
		credentials = new ProfileCredentialsProvider().getCredentials();
	}
	catch(Exception e){}
	
	AmazonEC2 ec2 = new AmazonEC2Client(credentials);		

	ec2.setEndpoint("ec2.eu-west-1.amazonaws.com");
	DescribeInstancesResult describeInstancesResult = ec2.describeInstances();
	List<Reservation> reservations = describeInstancesResult.getReservations();
	ArrayList<Instance> listOfInstances = new ArrayList<Instance>();
	for(Reservation reservation : reservations)
		listOfInstances.addAll(reservation.getInstances());
	
	String ownIP = null;
	String ownInstanceID = checkInstanceId();
	for(Instance instance: listOfInstances)
	{
		if(instance.getInstanceId().equals(ownInstanceID))
			ownIP = instance.getPublicIpAddress();
	}
	
	return ownIP;
}
 
Example 32
Project: hollow-reference-implementation   File: S3Publisher.java   View source code 5 votes vote down vote up
public S3Publisher(AWSCredentials credentials, String bucketName, String blobNamespace) {
    this.s3 = new AmazonS3Client(credentials);
    this.s3TransferManager = new TransferManager(s3);
    this.bucketName = bucketName;
    this.blobNamespace = blobNamespace;
    this.snapshotIndex = initializeSnapshotIndex();
}
 
Example 33
Project: bluegreen-manager   File: AwsClientFactory.java   View source code 5 votes vote down vote up
/**
 * Constructs an AmazonRDSClient and sets the region.
 */
public AmazonRDSClient makeRegionalRdsClient()
{
  AWSCredentials credentials = new BasicAWSCredentials(awsAccessKeyId, awsSecretAccessKey);
  AmazonRDSClient rds = new AmazonRDSClient(credentials);
  rds.setRegion(awsRegion);
  return rds;
}
 
Example 34
Project: hollow-reference-implementation   File: S3AnnouncementWatcher.java   View source code 5 votes vote down vote up
public S3AnnouncementWatcher(AWSCredentials credentials, String bucketName, String blobNamespace) {
    this.s3 = new AmazonS3Client(credentials);
    this.bucketName = bucketName;
    this.blobNamespace = blobNamespace;
    this.subscribedConsumers = Collections.synchronizedList(new ArrayList<HollowConsumer>());
    
    this.latestVersion = readLatestVersion();

    setupPollingThread();
}
 
Example 35
Project: bayou   File: S3LoggerBase.java   View source code 5 votes vote down vote up
S3LoggerBase(AWSCredentials credentials, String bucketName)
{
    _logger.debug("entering");

    if(bucketName == null)
        throw new NullPointerException("bucketName may not be null");

    if(bucketName.trim().length() == 0)
        throw new IllegalArgumentException("bucketName must have at least one non-whitespace character");

    _credentials = credentials;
    _bucketName = bucketName;
    _logger.debug("exiting");
}
 
Example 36
Project: hadoop   File: BasicAWSCredentialsProvider.java   View source code 5 votes vote down vote up
public AWSCredentials getCredentials() {
  if (!StringUtils.isEmpty(accessKey) && !StringUtils.isEmpty(secretKey)) {
    return new BasicAWSCredentials(accessKey, secretKey);
  }
  throw new AmazonClientException(
      "Access key or secret key is null");
}
 
Example 37
Project: strongbox   File: ProfileCredentialProvider.java   View source code 5 votes vote down vote up
private AWSCredentials getCredentialsFromProfile(final ProfileIdentifier profile) {
    ConfigProviderChain configProvider = new ConfigProviderChain();
    if (!configProvider.hasConfig()) {
        throw new IllegalStateException("When using '--profile', an AWS credentials or config file must be present");
    }

    Optional<RoleARN> roleToAssume = configProvider.getRoleArn(profile);
    if (roleToAssume.isPresent()) {
        return assumeRole(clientConfiguration, configProvider, profile, roleToAssume.get());
    } else {
        return getStaticCredentials(configProvider, profile);
    }
}
 
Example 38
Project: ibm-cos-sdk-java   File: AmazonHttpClient.java   View source code 5 votes vote down vote up
private void runBeforeRequestHandlers() {
    AWSCredentials credentials = getCredentialsFromContext();
    request.addHandlerContext(HandlerContextKey.AWS_CREDENTIALS, credentials);
    // Apply any additional service specific request handlers that need to be run
    for (RequestHandler2 requestHandler2 : requestHandler2s) {
        // If the request handler is a type of CredentialsRequestHandler, then set the credentials in the request handler.
        if (requestHandler2 instanceof CredentialsRequestHandler) {
            ((CredentialsRequestHandler) requestHandler2).setCredentials(credentials);
        }
        requestHandler2.beforeRequest(request);
    }
}
 
Example 39
Project: ibm-cos-sdk-java   File: AmazonHttpClient.java   View source code 5 votes vote down vote up
/**
 * Returns the credentials from the execution if exists. Else returns null.
 */
private AWSCredentials getCredentialsFromContext() {
    final AWSCredentialsProvider credentialsProvider = executionContext.getCredentialsProvider();

    AWSCredentials credentials = null;
    if (credentialsProvider != null) {
        awsRequestMetrics.startEvent(Field.CredentialsRequestTime);
        try {
            credentials = credentialsProvider.getCredentials();
        } finally {
            awsRequestMetrics.endEvent(Field.CredentialsRequestTime);
        }
    }
    return credentials;
}
 
Example 40
Project: ibm-cos-sdk-java   File: ProfilesConfigFile.java   View source code 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();
    }
}