

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 使用 IAM 搭配 Gremlin Java 連線至 Amazon Neptune 資料庫
<a name="iam-auth-connecting-gremlin-java"></a>

以下是如何使用 Gremlin Java API 搭配 Sig4 簽署來連線至 Neptune 的範例 （它假設具有使用 Maven 的一般知識）。此範例使用 [Amazon Neptune SigV4 Signer](https://github.com/aws/amazon-neptune-sigv4-signer) 程式庫協助簽署請求。首先，將相依性定義為 `pom.xml` 檔案的一部分：

**注意**  
下列範例使用在 TinkerPop 3.6.6 中引入`requestInterceptor()`的 。如果您使用的 TinkerPop 版本早於 3.6.6 （但為 3.5.5 或更新版本），請使用 `handshakeInterceptor()`，而不是下列程式碼範例中`requestInterceptor()`的 。

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

 Amazon Neptune SigV4 Signer 同時支援 AWS Java 開發套件的 1.x 和 2.x 版本。下列範例使用 2.x，其中 `DefaultCredentialsProvider` 是`software.amazon.awssdk.auth.credentials.AwsCredentialsProvider`執行個體。如果您要從 1.x 升級到 2.x，請參閱適用於 Java 的 AWS SDK 2.x 文件中的[登入資料提供者變更](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 透過使用角色假設支援跨帳戶 IAM 身分驗證，有時也稱為[角色鏈結](https://docs.aws.amazon.com//neptune/latest/userguide/bulk-load-tutorial-chain-roles.html#bulk-load-tutorial-chain-cross-account)。若要從託管在不同 AWS 帳戶中的應用程式提供 Neptune 叢集的存取權：
+  在應用程式 AWS 帳戶中建立新的 IAM 使用者或角色，其信任政策允許使用者或角色擔任另一個 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 帳戶中建立新的 IAM 角色，允許存取 Neptune 資料庫，並允許應用程式帳戶 IAM 使用者/角色擔任角色。使用信任政策：

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

****  

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

------
+  使用以下程式碼範例做為如何使用這兩個角色以允許應用程式存取 Neptune 的指引。在此範例中，應用程式帳戶角色會在建立 時透過 [DefaultCredentialProviderChain](https://docs.aws.amazon.com//sdk-for-java/v1/developer-guide/credentials.html) 擔任`STSclient`。`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();
    }
  ```