1 /*
2  * Copyright 2012-2020 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  */

15 package com.amazonaws.auth;
16
17 import static com.amazonaws.SDKGlobalConfiguration.ACCESS_KEY_SYSTEM_PROPERTY;
18 import static com.amazonaws.SDKGlobalConfiguration.SECRET_KEY_SYSTEM_PROPERTY;
19 import static com.amazonaws.SDKGlobalConfiguration.SESSION_TOKEN_SYSTEM_PROPERTY;
20
21 import com.amazonaws.SdkClientException;
22 import com.amazonaws.util.StringUtils;
23
24 /**
25  * {@link AWSCredentialsProvider} implementation that provides credentials by
26  * looking at the <code>aws.accessKeyId</code> and <code>aws.secretKey</code>
27  * Java system properties.
28  */

29 public class SystemPropertiesCredentialsProvider implements AWSCredentialsProvider {
30
31     @Override
32     public AWSCredentials getCredentials() {
33         String accessKey = StringUtils.trim(System.getProperty(ACCESS_KEY_SYSTEM_PROPERTY));
34         String secretKey = StringUtils.trim(System.getProperty(SECRET_KEY_SYSTEM_PROPERTY));
35         String sessionToken = StringUtils.trim(System.getProperty(SESSION_TOKEN_SYSTEM_PROPERTY));
36
37         if (StringUtils.isNullOrEmpty(accessKey) || StringUtils.isNullOrEmpty(secretKey)) {
38             throw new SdkClientException(
39                     "Unable to load AWS credentials from Java system "
40                     + "properties (" + ACCESS_KEY_SYSTEM_PROPERTY + " and "
41                     + SECRET_KEY_SYSTEM_PROPERTY + ")");
42         }
43         if (StringUtils.isNullOrEmpty(sessionToken)) {
44             return new BasicAWSCredentials(accessKey, secretKey);
45         } else {
46             return new BasicSessionCredentials(accessKey, secretKey, sessionToken);
47         }
48     }
49
50     @Override
51     public void refresh() {
52     }
53
54     @Override
55     public String toString() {
56         return getClass().getSimpleName();
57     }
58 }