

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

# Gremlin Java와 함께 IAM을 사용하여 Amazon Neptune 데이터베이스에 연결
<a name="iam-auth-connecting-gremlin-java"></a>

다음은 Sig4 서명과 함께 Gremlin Java API를 사용하여 Neptune에 연결하는 방법의 예입니다(Maven 사용에 대한 일반적인 지식을 가정함). 이 예제에서는 [Amazon Neptune SigV4 Signer](https://github.com/aws/amazon-neptune-sigv4-signer) 라이브러리를 사용하여 요청 서명을 지원합니다. 먼저 종속성을 `pom.xml` 파일의 일부로 정의합니다.

**참고**  
다음 예제에서는 TinkerPop 3.6.6에 도입`requestInterceptor()`된를 사용합니다. 3.6.6 이전(3.5.5 이상)의 TinkerPop 버전을 사용하는 경우 아래 코드 예제`requestInterceptor()`에서 `handshakeInterceptor()` 대신를 사용합니다.

```
<dependency>
  <groupId>com.amazonaws</groupId>
  <artifactId>amazon-neptune-sigv4-signer</artifactId>
  <version>3.1.0</version>
</dependency>
```

 Amazon Neptune SigV4 서명자는 AWS Java SDK 버전 1.x 및 2.x를 모두 지원합니다. 다음 예제에서는 2.x를 사용합니다. 여기서 `DefaultCredentialsProvider`는 `software.amazon.awssdk.auth.credentials.AwsCredentialsProvider` 인스턴스입니다. 1.x에서 2.x로 업그레이드하는 경우 Java 2.x용 AWS SDK 설명서의 [자격 증명 공급자 변경](https://docs.aws.amazon.com//sdk-for-java/latest/developer-guide/migration-client-credentials.html) 사항을 참조하세요.

```
import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
import com.amazonaws.neptune.auth.NeptuneNettyHttpSigV4Signer;
import com.amazonaws.neptune.auth.NeptuneSigV4SignerException;

 {{...}}

System.setProperty("aws.accessKeyId","{{your-access-key}}");
System.setProperty("aws.secretKey","{{your-secret-key}}");

 {{...}}

Cluster cluster = Cluster.build({{(your cluster)}})
                 .enableSsl(true)
                 .requestInterceptor( r ->
                  {
                    try {
                      NeptuneNettyHttpSigV4Signer sigV4Signer =
                        new NeptuneNettyHttpSigV4Signer("{{(your region)}}", DefaultCredentialsProvider.create());
                      sigV4Signer.signRequest(r);
                    } catch (NeptuneSigV4SignerException e) {
                      throw new RuntimeException("Exception occurred while signing the request", e);
                    }
                    return r;
                  }
                 ).create();
try {
  Client client = cluster.connect();
  client.submit("g.V().has('code','IAD')").all().get();
} catch (Exception e) {
  throw new RuntimeException("Exception occurred while connecting to cluster", e);
}
```

## 교차 계정 IAM 인증
<a name="iam-auth-connecting-gremlin-java-cross-account"></a>

 Amazon Neptune은 [역할 체인](https://docs.aws.amazon.com//neptune/latest/userguide/bulk-load-tutorial-chain-roles.html#bulk-load-tutorial-chain-cross-account)이라고도 하는 역할 가정을 사용하여 교차 계정 IAM 인증을 지원합니다. 다른 AWS 계정에 호스팅된 애플리케이션에서 Neptune 클러스터에 대한 액세스를 제공하려면: 
+  사용자 또는 역할이 다른 IAM 역할을 수임하도록 허용하는 신뢰 정책을 사용하여 애플리케이션 AWS 계정에서 새 IAM 사용자 또는 역할을 생성합니다. 애플리케이션을 호스트하는 컴퓨팅(EC2 인스턴스, Lambda 함수, ECS 태스크 등)에 이 역할을 할당합니다.

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

****  

  ```
  {
    "Version":"2012-10-17",		 	 	 
    "Statement": [
      {
        "Sid": "assumeRolePolicy",
        "Effect": "Allow",
        "Action": "sts:AssumeRole",
        "Resource": "arn:aws:iam::{{111122223333}}:role/{{role-name}}"
      }
    ]
  }
  ```

------
+  Neptune 데이터베이스 AWS 계정에서 Neptune 데이터베이스에 대한 액세스를 허용하고 애플리케이션 계정 IAM 사용자/역할의 역할 가정을 허용하는 새 IAM 역할을 생성합니다. 다음과 같은 신뢰 정책을 사용합니다.

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

****  

  ```
  {
      "Version":"2012-10-17",		 	 	 
      "Statement": [
          {
              "Effect": "Allow",
              "Principal": {
                  "AWS": [
                      "(ARN of application account IAM user or role)"
                  ]
              },
              "Action": "sts:AssumeRole",
              "Condition": {}
          }
      ]
  }
  ```

------
+  다음 코드 예제를 이 두 역할을 사용하여 애플리케이션이 Neptune에 액세스하도록 허용하는 방법에 대한 지침으로 사용합니다. 이 예제에서는 `STSclient`를 생성할 때 [DefaultCredentialProviderChain](https://docs.aws.amazon.com//sdk-for-java/v1/developer-guide/credentials.html)을 통해 애플리케이션 계정 역할이 인수됩니다. 그런 다음 `STSclient`를 통해 `STSAssumeRoleSessionCredentialsProvider`를 사용하여 Neptune 데이터베이스 AWS 계정에서 호스팅되는 역할을 수임합니다.

  ```
  public static void main( String[] args )
    {
  
      /* 
       * Establish an STS client from the application account.
       */
      AWSSecurityTokenService client = AWSSecurityTokenServiceClientBuilder
          .standard()
          .build();
  
      /*
       * Define the role ARN that you will be assuming in the database account where the Neptune cluster resides.
       */
      String roleArnToAssume = "arn:aws:iam::012345678901:role/CrossAccountNeptuneRole";
      String crossAccountSessionName = "cross-account-session-" + UUID.randomUUID();
  
      /*
       * Change the Credentials Provider in the SigV4 Signer to use the STSAssumeRole Provider and provide it
       * with both the role to be assumed, the original STS client, and a session name (which can be
       * arbitrary.)
       */
      Cluster cluster = Cluster.build()
                   .addContactPoint("neptune-cluster.us-west-2.neptune.amazonaws.com")
                   .enableSsl(true)
                   .port(8182)
                   .requestInterceptor( r ->
                    {
                      try {
                        NeptuneNettyHttpSigV4Signer sigV4Signer =
                          // new NeptuneNettyHttpSigV4Signer("us-west-2", DefaultCredentialsProvider.create());
                          new NeptuneNettyHttpSigV4Signer(
                                  "us-west-2",  
                                   new STSAssumeRoleSessionCredentialsProvider
                                      .Builder(roleArnToAssume, crossAccountSessionName)
                                          .withStsClient(client)
                                          .build());
                        sigV4Signer.signRequest(r);
                      } catch (NeptuneSigV4SignerException e) {
                        throw new RuntimeException("Exception occurred while signing the request", e);
                      }
                      return r;
                    }
                   ).create();
  
      GraphTraversalSource g = traversal().withRemote(DriverRemoteConnection.using(cluster));
  
      /* whatever application code is necessary */
  
      cluster.close();
    }
  ```