· 7 years ago · Apr 09, 2018, 07:18 AM
1/*
2 * Copyright 2012-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License").
5 * You may not use this file except in compliance with the License.
6 * A copy of the License is located at
7 *
8 * http://aws.amazon.com/apache2.0
9 *
10 * or in the "license" file accompanying this file. This file is distributed
11 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
12 * express or implied. See the License for the specific language governing
13 * permissions and limitations under the License.
14 */
15package com.amazonaws.auth;
16
17import static com.amazonaws.SDKGlobalConfiguration.ACCESS_KEY_ENV_VAR;
18import static com.amazonaws.SDKGlobalConfiguration.ALTERNATE_ACCESS_KEY_ENV_VAR;
19import static com.amazonaws.SDKGlobalConfiguration.ALTERNATE_SECRET_KEY_ENV_VAR;
20import static com.amazonaws.SDKGlobalConfiguration.SECRET_KEY_ENV_VAR;
21import static com.amazonaws.SDKGlobalConfiguration.AWS_SESSION_TOKEN_ENV_VAR;
22
23import com.amazonaws.AmazonClientException;
24import com.amazonaws.util.StringUtils;
25
26/**
27 * {@link AWSCredentialsProvider} implementation that provides credentials
28 * by looking at the: <code>AWS_ACCESS_KEY_ID</code> (or <code>AWS_ACCESS_KEY</code>) and
29 * <code>AWS_SECRET_KEY</code> (or <code>AWS_SECRET_ACCESS_KEY</code>) environment variables.
30 */
31public class EnvironmentVariableCredentialsProvider implements AWSCredentialsProvider {
32 @Override
33 public AWSCredentials getCredentials() {
34 String accessKey = System.getenv(ACCESS_KEY_ENV_VAR);
35 if (accessKey == null) {
36 accessKey = System.getenv(ALTERNATE_ACCESS_KEY_ENV_VAR);
37 }
38
39 String secretKey = System.getenv(SECRET_KEY_ENV_VAR);
40 if (secretKey == null) {
41 secretKey = System.getenv(ALTERNATE_SECRET_KEY_ENV_VAR);
42 }
43
44 accessKey = StringUtils.trim(accessKey);
45 secretKey = StringUtils.trim(secretKey);
46 String sessionToken =
47 StringUtils.trim(System.getenv(AWS_SESSION_TOKEN_ENV_VAR));
48
49 if (StringUtils.isNullOrEmpty(accessKey)
50 || StringUtils.isNullOrEmpty(secretKey)) {
51
52 throw new AmazonClientException(
53 "Unable to load AWS credentials from environment variables " +
54 "(" + ACCESS_KEY_ENV_VAR + " (or " + ALTERNATE_ACCESS_KEY_ENV_VAR + ") and " +
55 SECRET_KEY_ENV_VAR + " (or " + ALTERNATE_SECRET_KEY_ENV_VAR + "))");
56 }
57
58 return sessionToken == null ?
59 new BasicAWSCredentials(accessKey, secretKey)
60 :
61 new BasicSessionCredentials(accessKey, secretKey, sessionToken);
62 }
63
64 @Override
65 public void refresh() {}
66
67 @Override
68 public String toString() {
69 return getClass().getSimpleName();
70 }
71}