

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

# 를 사용하여 코드에 자격 증명 제공 AWS SDK for Java 2.x
<a name="credentials-explicit"></a>

기본 자격 증명 체인이나 특정 또는 사용자 지정 공급자 또는 공급자 체인이 애플리케이션에 작동하지 않는 경우 코드에서 직접 임시 자격 증명을 제공할 수 있습니다. 위에[ 설명된](credentials-temporary.md#credentials-temporary-from-portal) [IAM 역할 자격 증명](https://docs.aws.amazon.com/singlesignon/latest/userguide/howtogetcredentials.html) 또는 AWS Security Token Service ()에서 검색된 임시 자격 증명일 수 있습니다AWS STS. 를 사용하여 임시 자격 증명을 검색한 경우 다음 코드 예제와 같이 AWS 서비스 클라이언트에 AWS STS제공합니다.

1. `StsClient.assumeRole()`를 호출하여 역할을 맡으세요.

1. [StaticCredentialsProvider](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/auth/credentials/StaticCredentialsProvider.html) 객체를 생성하고 `AwsSessionCredentials` 객체와 함께 제공하세요.

1. `StaticCredentialsProvider`를 사용하여 클라이언트 빌더를 구성하고 클라이언트를 빌드합니다.

다음 예시에서는 IAM 수임 역할에 AWS STS 대해에서 반환한 임시 자격 증명을 사용하여 Amazon S3 서비스 클라이언트를 생성합니다.

```
    // The AWS IAM Identity Center identity (user) who executes this method does not have permission to list buckets.
    // The identity is configured in the [default] profile.
    public static void assumeRole(String roleArn, String roleSessionName) {
        // The IAM role represented by the 'roleArn' parameter can be assumed by identities in two different accounts
        // and the role permits the user to only list buckets.

        // The SDK's default credentials provider chain will find the single sign-on settings in the [default] profile.
        // The identity configured with the [default] profile needs permission to call AssumeRole on the STS service.
        try {
            Credentials tempRoleCredentials;
            try (StsClient stsClient = StsClient.create()) {
                AssumeRoleRequest roleRequest = AssumeRoleRequest.builder()
                        .roleArn(roleArn)
                        .roleSessionName(roleSessionName)
                        .build();

                AssumeRoleResponse roleResponse = stsClient.assumeRole(roleRequest);
                tempRoleCredentials = roleResponse.credentials();
            }
            // Use the following temporary credential items for the S3 client.
            String key = tempRoleCredentials.accessKeyId();
            String secKey = tempRoleCredentials.secretAccessKey();
            String secToken = tempRoleCredentials.sessionToken();

            // List all buckets in the account associated with the assumed role
            // by using the temporary credentials retrieved by invoking stsClient.assumeRole().
            StaticCredentialsProvider staticCredentialsProvider = StaticCredentialsProvider.create(
                    AwsSessionCredentials.create(key, secKey, secToken));
            try (S3Client s3 = S3Client.builder()
                    .credentialsProvider(staticCredentialsProvider)
                    .build()) {
                List<Bucket> buckets = s3.listBuckets().buckets();
                for (Bucket bucket : buckets) {
                    System.out.println("bucket name: " + bucket.name());
                }
            }
        } catch (StsException | S3Exception e) {
            logger.error(e.getMessage());
            System.exit(1);
        }
    }
```

## 권한 세트
<a name="credentials-explicit-permission-set"></a>

에 정의된 다음 권한 세트를 AWS IAM Identity Center 사용하면 자격 증명(사용자)이 다음 두 작업을 수행할 수 있습니다.

1. Amazon Simple Storage Service `GetObject` 운영.

1.  AWS Security Token Service의 `AssumeRole` 작업.

역할을 맡지 않으면 예제에 표시된 `s3.listBuckets()` 메서드가 실패합니다.

------
#### [ JSON ]

****  

```
{
	"Version":"2012-10-17",		 	 	 
	"Statement": [
		{
			"Effect": "Allow",
			"Action": [
				"s3:GetObject",
				"sts:AssumeRole"
			],
			"Resource": [
				"*"
			]
		}
	]
}
```

------

## 수임된 역할
<a name="credentials-explicit-role-to-assume"></a>

### 수임된 역할 권한 정책
<a name="credentials-explicit-role-policy"></a>

다음 권한 정책은 이전 예제에 수임된 역할에 연결되어 있습니다. 이 권한 정책은 역할과 동일한 계정의 모든 버킷을 나열하는 기능을 허용합니다.

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "s3:ListAllMyBuckets"
            ],
            "Resource": [
                "*"
            ]
        }
    ]
}
```

------

### 수임된 역할 신뢰 정책
<a name="credentials-explicit-trust-policy"></a>

다음 권한 정책은 이전 예제에 수임된 역할에 연결되어 있습니다. 이 정책을 통해 두 계정의 ID(사용자)가 역할을 수임할 수 있습니다.

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "AWS": [
                    "arn:aws:iam::111122223333:root",
                    "arn:aws:iam::555555555555:root"
                ]
            },
            "Action": "sts:AssumeRole",
            "Condition": {}
        }
    ]
}
```

------