Use Alibaba Cloud SDK para llamar a GetSecretValue y recuperar el valor de un secreto mediante una puerta de enlace compartida o dedicada. Ambas puertas de enlace solo difieren en la inicialización del cliente; el código de solicitud y de manejo de excepciones es idéntico.
Elija una puerta de enlace
|
Puerta de enlace compartida |
Puerta de enlace dedicada |
|
|
Cuándo usarla |
Cargas de trabajo generales que acceden a KMS a través de la red pública o VPC |
Cargas de trabajo que requieren una instancia de KMS dedicada con mayor aislamiento |
|
Formato del endpoint |
Red pública: |
|
|
Certificado de CA |
No obligatorio |
SDK V2.0: obligatorio / SDK V1.0: no compatible; establezca |
Requisitos previos
Antes de empezar, asegúrese de contar con lo siguiente:
Una cuenta de Alibaba Cloud con un secreto creado en KMS
Las variables de entorno
ALIBABA_CLOUD_ACCESS_KEY_IDyALIBABA_CLOUD_ACCESS_KEY_SECRETconfiguradas
Almacenar pares de AccessKey en el código fuente conlleva riesgo de fuga de credenciales. Use tokens de Security Token Service (STS) para las cargas de trabajo en producción.
Obtener el valor de un secreto mediante una puerta de enlace compartida
Ejemplo completo
package com.aliyun.sample;
import com.aliyun.tea.*;
public class Sample {
/**
* Use your AccessKey ID and AccessKey Secret to initialize the client.
* @return Client
* @throws Exception
*/
public static com.aliyun.kms20160120.Client createClient() throws Exception {
// If the project code is leaked, the AccessKey pair may be leaked and resources in your account become insecure. The following code is for reference only.
// We recommend that you use Security Token Service (STS) tokens, which provide higher security. For more information about authentication methods, see https://www.alibabacloud.com/help/en/sdk/developer-reference/v2-manage-access-credentials.
com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
// Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured in the code runtime environment.
.setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
// Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured in the code runtime environment.
.setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
// For more information about endpoints, see https://api.alibabacloud.com/product/Kms.
config.endpoint = "kms.ap-southeast-1.aliyuncs.com";
return new com.aliyun.kms20160120.Client(config);
}
public static void main(String[] args_) throws Exception {
java.util.List<String> args = java.util.Arrays.asList(args_);
com.aliyun.kms20160120.Client client = Sample.createClient();
com.aliyun.kms20160120.models.GetSecretValueRequest getSecretValueRequest = new com.aliyun.kms20160120.models.GetSecretValueRequest()
.setSecretName("test****");
com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
try {
// If you copy and run the sample code, write your own code to display the response of the API operation if necessary.
client.getSecretValueWithOptions(getSecretValueRequest, runtime);
} catch (TeaException error) {
// Handle exceptions with caution based on your actual business scenario and do not ignore exceptions in your project. The error messages displayed in this example are for reference only.
// Print error messages
System.out.println(error.getMessage());
// Provide the URL that is used for troubleshooting.
System.out.println(error.getData().get("Recommend"));
com.aliyun.teautil.Common.assertAsString(error.message);
} catch (Exception _error) {
TeaException error = new TeaException(_error.getMessage(), _error);
// Handle exceptions with caution based on your actual business scenario and do not ignore exceptions in your project. The error messages displayed in this example are for reference only.
// Print error messages
System.out.println(error.getMessage());
// Provide the URL that is used for troubleshooting.
System.out.println(error.getData().get("Recommend"));
com.aliyun.teautil.Common.assertAsString(error.message);
}
}
}
Análisis del ejemplo
Inicializar el cliente
Establezca el endpoint en la dirección de la puerta de enlace compartida correspondiente a su región. Este ejemplo usa el endpoint de red pública de Singapur (ap-southeast-1).
com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
.setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
.setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
// For more information about endpoints, see https://api.alibabacloud.com/product/Kms.
config.endpoint = "kms.ap-southeast-1.aliyuncs.com";
Llamar a GetSecretValue
Reemplace test**** por su SecretName real.
com.aliyun.kms20160120.models.GetSecretValueRequest getSecretValueRequest = new com.aliyun.kms20160120.models.GetSecretValueRequest()
.setSecretName("test****");
com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
try {
client.getSecretValueWithOptions(getSecretValueRequest, runtime);
} catch (TeaException error) {
System.out.println(error.getMessage());
System.out.println(error.getData().get("Recommend"));
com.aliyun.teautil.Common.assertAsString(error.message);
} catch (Exception _error) {
TeaException error = new TeaException(_error.getMessage(), _error);
System.out.println(error.getMessage());
System.out.println(error.getData().get("Recommend"));
com.aliyun.teautil.Common.assertAsString(error.message);
}
La respuesta contiene el valor del secreto y sus metadatos. Para ver la lista completa de campos de respuesta, consulte GetSecretValue.
Obtener el valor de un secreto mediante una puerta de enlace dedicada
Ejemplo completo
package com.aliyun.sample;
import com.aliyun.tea.*;
public class Sample {
/**
* Use your AccessKey ID and AccessKey Secret to initialize the client.
* @return Client
* @throws Exception
*/
public static com.aliyun.kms20160120.Client createClient() throws Exception {
// If the project code is leaked, the AccessKey pair may be leaked and resources in your account become insecure. The following code is for reference only.
// We recommend that you use Security Token Service (STS) tokens, which provide higher security. For more information about authentication methods, see https://www.alibabacloud.com/help/en/sdk/developer-reference/v2-manage-access-credentials.
com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
// Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured in the code runtime environment.
.setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
// Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured in the code runtime environment.
.setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
// Dedicated gateway endpoint
config.endpoint = "kst-hzz65f176a0ogplgq****.cryptoservice.kms.aliyuncs.com";
// KMS instance CA certificate
config.ca = "-----BEGIN CERTIFICATE-----MIIDuzCCAqOgAwIBAgIJALTKwWAjvbMiMA0GCS****";
return new com.aliyun.kms20160120.Client(config);
}
public static void main(String[] args_) throws Exception {
java.util.List<String> args = java.util.Arrays.asList(args_);
com.aliyun.kms20160120.Client client = Sample.createClient();
com.aliyun.kms20160120.models.GetSecretValueRequest getSecretValueRequest = new com.aliyun.kms20160120.models.GetSecretValueRequest()
.setSecretName("test****");
com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
try {
// If you copy and run the sample code, write your own code to display the response of the API operation if necessary.
client.getSecretValueWithOptions(getSecretValueRequest, runtime);
} catch (TeaException error) {
// Handle exceptions with caution based on your actual business scenario and do not ignore exceptions in your project. The error messages displayed in this example are for reference only.
// Print error messages
System.out.println(error.getMessage());
// Provide the URL that is used for troubleshooting.
System.out.println(error.getData().get("Recommend"));
com.aliyun.teautil.Common.assertAsString(error.message);
} catch (Exception _error) {
TeaException error = new TeaException(_error.getMessage(), _error);
// Handle exceptions with caution based on your actual business scenario and do not ignore exceptions in your project. The error messages displayed in this example are for reference only.
// Print error messages
System.out.println(error.getMessage());
// Provide the URL that is used for troubleshooting.
System.out.println(error.getData().get("Recommend"));
com.aliyun.teautil.Common.assertAsString(error.message);
}
}
}
Análisis del ejemplo
Inicializar el cliente
La puerta de enlace dedicada requiere dos campos adicionales: el endpoint de la instancia de KMS y el certificado de CA.
// Dedicated gateway endpoint
config.endpoint = "kst-hzz65f176a0ogplgq****.cryptoservice.kms.aliyuncs.com";
// KMS instance CA certificate
config.ca = "-----BEGIN CERTIFICATE-----MIIDuzCCAqOgAwIBAgIJALTKwWAjvbMiMA0GCS****";
Reemplace kst-hzz65f176a0ogplgq**** por el ID de su instancia de KMS y sustituya el valor del certificado de CA por el certificado descargado desde su instancia de KMS.
El SDK V1.0 no admite certificados de CA. En su lugar, establezca HTTPSInsecure en true: client.SetHTTPSInsecure(true).
Llamar a GetSecretValue
El código de solicitud y de manejo de excepciones es idéntico al del ejemplo de la puerta de enlace compartida. Reemplace test**** por su SecretName real.
com.aliyun.kms20160120.models.GetSecretValueRequest getSecretValueRequest = new com.aliyun.kms20160120.models.GetSecretValueRequest()
.setSecretName("test****");
com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
try {
client.getSecretValueWithOptions(getSecretValueRequest, runtime);
} catch (TeaException error) {
System.out.println(error.getMessage());
System.out.println(error.getData().get("Recommend"));
com.aliyun.teautil.Common.assertAsString(error.message);
} catch (Exception _error) {
TeaException error = new TeaException(_error.getMessage(), _error);
System.out.println(error.getMessage());
System.out.println(error.getData().get("Recommend"));
com.aliyun.teautil.Common.assertAsString(error.message);
}