

As traduções são geradas por tradução automática. Em caso de conflito entre o conteúdo da tradução e da versão original em inglês, a versão em inglês prevalecerá.

# Conectar-se a bancos de dados do Amazon Neptune usando o IAM com o Gremlin Java
<a name="iam-auth-connecting-gremlin-java"></a>

Aqui está um exemplo de como se conectar ao Neptune usando a API Gremlin Java com assinatura Sig4 (pressupõe conhecimento geral sobre o uso do Maven). Este exemplo usa a biblioteca [Amazon Neptune SigV4 Signer](https://github.com/aws/amazon-neptune-sigv4-signer) para auxiliar na assinatura de solicitações. Primeiro, defina as dependências como parte do arquivo `pom.xml`:

**nota**  
Os exemplos a seguir usam`requestInterceptor()`, que foi introduzido em TinkerPop 3.6.6. Se você estiver usando uma TinkerPop versão anterior à 3.6.6 (mas 3.5.5 ou superior), use `requestInterceptor()` em `handshakeInterceptor()` vez dos exemplos de código abaixo.

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

 O Amazon Neptune SigV4 Signer é compatível com as versões 1.x e 2.x do Java SDK. AWS Os exemplos a seguir usam 2.x, onde `DefaultCredentialsProvider` é uma `software.amazon.awssdk.auth.credentials.AwsCredentialsProvider` instância. Se você estiver atualizando da versão 1.x para a versão 2.x, consulte as [alterações do provedor de credenciais](https://docs.aws.amazon.com//sdk-for-java/latest/developer-guide/migration-client-credentials.html) na documentação do SDK for AWS Java 2.x. 

```
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);
}
```

## Autenticação do IAM entre contas
<a name="iam-auth-connecting-gremlin-java-cross-account"></a>

 O Amazon Neptune oferece suporte à autenticação do IAM entre contas por meio do uso da suposição de perfil, também conhecida como [encadeamento de perfis](https://docs.aws.amazon.com//neptune/latest/userguide/bulk-load-tutorial-chain-roles.html#bulk-load-tutorial-chain-cross-account). Para fornecer acesso a um cluster Neptune a partir de um aplicativo hospedado em uma conta diferente: AWS 
+  Crie um novo usuário ou função do IAM na AWS conta do aplicativo, com uma política de confiança que permita que o usuário ou a função assumam outra função do IAM. Atribua esse perfil à computação que hospeda a aplicação (instância do EC2, função do Lambda, tarefa do ECS, etc.). 

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

****  

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

------
+  Crie uma nova função do IAM na conta do banco de dados do Neptune que permita o acesso ao AWS banco de dados do Neptune e permita a suposição do papel a partir do usuário/função do IAM da conta do aplicativo. Use uma política de confiança de: 

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

****  

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

------
+  Use o exemplo de código a seguir como orientação para usar esses dois perfis para permitir que a aplicação acesse o Neptune. Neste exemplo, a função da conta do aplicativo será assumida por meio do [DefaultCredentialProviderChain](https://docs.aws.amazon.com//sdk-for-java/v1/developer-guide/credentials.html)ao criar `STSclient` o. Em seguida, `STSclient` é usado por meio do `STSAssumeRoleSessionCredentialsProvider` para assumir a função hospedada na conta do banco de dados 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();
    }
  ```