Suministro de credenciales en código utilizando AWS SDK for Java 2.x - AWS SDK for Java 2.x

Suministro de credenciales en código utilizando AWS SDK for Java 2.x

Si la cadena de credenciales predeterminada o un proveedor o cadena de proveedores específicos o personalizados no funcionan para su código, puede proporcionar mediante código las credenciales temporales que desee. Puede tratarse de credenciales de rol de IAM, tal como se describió anteriormente, o credenciales temporales recuperadas de AWS Security Token Service (AWS STS). Si ha obtenido credenciales temporales utilizando AWS STS, proporciónelas a un cliente Servicio de AWS, como figura en el siguiente ejemplo de código.

  1. Asuma un rol llamando a StsClient.assumeRole().

  2. Cree un objeto StaticCredentialsProvider y suminístrelo con el objeto AwsSessionCredentials.

  3. Configure el compilador del cliente con StaticCredentialsProvider y compile el cliente.

En el siguiente ejemplo se crea un cliente de servicio de Amazon S3 con las credenciales temporales devueltas AWS STS por un rol asumido de IAM.

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

El siguiente conjunto de permisos, definido en AWS IAM Identity Center permite a la identidad (usuario) hacer las dos operaciones siguientes

  1. La GetObject operación del Amazon Simple Storage Service.

  2. La operación AssumeRole del AWS Security Token Service.

Sin asumir el rol, fallaría el método s3.listBuckets() que se muestra en el ejemplo.

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

Política de permisos del rol asumidos

La política de permisos siguiente está asociada al rol que se asume en el ejemplo anterior. Esta política de permisos permite enumerar todos los buckets de la misma cuenta que el rol.

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

Política de confianza del rol asumido

La política de permisos siguiente está asociada al rol que se asume en el ejemplo anterior. La política permite que las identidades (usuarios) de dos cuentas asuman el rol.

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