Estos contenidos se han traducido de forma automática para su comodidad, pero Huawei Cloud no garantiza la exactitud de estos. Para consultar los contenidos originales, acceda a la versión en inglés.
Cómputo
Elastic Cloud Server
Bare Metal Server
Auto Scaling
Image Management Service
Dedicated Host
FunctionGraph
Cloud Phone Host
Huawei Cloud EulerOS
Redes
Virtual Private Cloud
Elastic IP
Elastic Load Balance
NAT Gateway
Direct Connect
Virtual Private Network
VPC Endpoint
Cloud Connect
Enterprise Router
Enterprise Switch
Global Accelerator
Gestión y gobernanza
Cloud Eye
Identity and Access Management
Cloud Trace Service
Resource Formation Service
Tag Management Service
Log Tank Service
Config
Resource Access Manager
Simple Message Notification
Application Performance Management
Application Operations Management
Organizations
Optimization Advisor
Cloud Operations Center
Resource Governance Center
Migración
Server Migration Service
Object Storage Migration Service
Cloud Data Migration
Migration Center
Cloud Ecosystem
KooGallery
Partner Center
User Support
My Account
Billing Center
Cost Center
Resource Center
Enterprise Management
Service Tickets
HUAWEI CLOUD (International) FAQs
ICP Filing
Support Plans
My Credentials
Customer Operation Capabilities
Partner Support Plans
Professional Services
Análisis
MapReduce Service
Data Lake Insight
CloudTable Service
Cloud Search Service
Data Lake Visualization
Data Ingestion Service
GaussDB(DWS)
DataArts Studio
IoT
IoT Device Access
Otros
Product Pricing Details
System Permissions
Console Quick Start
Common FAQs
Instructions for Associating with a HUAWEI CLOUD Partner
Message Center
Seguridad y cumplimiento
Security Technologies and Applications
Web Application Firewall
Host Security Service
Cloud Firewall
SecMaster
Data Encryption Workshop
Database Security Service
Cloud Bastion Host
Data Security Center
Cloud Certificate Manager
Blockchain
Blockchain Service
Servicios multimedia
Media Processing Center
Video On Demand
Live
SparkRTC
Almacenamiento
Object Storage Service
Elastic Volume Service
Cloud Backup and Recovery
Storage Disaster Recovery Service
Scalable File Service
Volume Backup Service
Cloud Server Backup Service
Data Express Service
Dedicated Distributed Storage Service
Contenedores
Cloud Container Engine
SoftWare Repository for Container
Application Service Mesh
Ubiquitous Cloud Native Service
Cloud Container Instance
Bases de datos
Relational Database Service
Document Database Service
Data Admin Service
Data Replication Service
GeminiDB
GaussDB
Distributed Database Middleware
Database and Application Migration UGO
TaurusDB
Middleware
Distributed Cache Service
API Gateway
Distributed Message Service for Kafka
Distributed Message Service for RabbitMQ
Distributed Message Service for RocketMQ
Cloud Service Engine
EventGrid
Dedicated Cloud
Dedicated Computing Cluster
Aplicaciones empresariales
ROMA Connect
Message & SMS
Domain Name Service
Edge Data Center Management
Meeting
AI
Face Recognition Service
Graph Engine Service
Content Moderation
Image Recognition
Data Lake Factory
Optical Character Recognition
ModelArts
ImageSearch
Conversational Bot Service
Speech Interaction Service
Huawei HiLens
Developer Tools
SDK Developer Guide
API Request Signing Guide
Terraform
Koo Command Line Interface
Distribución de contenido y cómputo de borde
Content Delivery Network
Intelligent EdgeFabric
CloudPond
Soluciones
SAP Cloud
High Performance Computing
Servicios para desarrolladores
ServiceStage
CodeArts
CodeArts PerfTest
CodeArts Req
CodeArts Pipeline
CodeArts Build
CodeArts Deploy
CodeArts Artifact
CodeArts TestPlan
CodeArts Check
Cloud Application Engine
aPaaS MacroVerse
KooPhone
KooDrive

Rotación de un secreto para dos usuarios

Actualización más reciente 2024-09-13 GMT+08:00

Descripción general

Puede actualizar la información de dos usuarios en un secreto.

Por ejemplo, si su aplicación requiere alta disponibilidad y realiza la rotación de un solo usuario, es posible que no pueda acceder a la aplicación al cambiar la contraseña de usuario y actualizar el contenido secreto. En este caso, debe utilizar la política de rotación de secreto de multiusuarios.

Debe tener una cuenta. Por ejemplo, Admin que tenga permiso para crear y cambiar las contraseñas de user1 y user2. Primero, cree un secreto, cree la cuenta y contraseña de user1 y regístrelas como user1/password1. Luego, cree user2 agregando la versión del secreto v2 y guarde la contraseña de user2 como user2/password2. Si cambia la contraseña de user1, deberá agregar una versión de secreto v3 y registrarla como user1/password3. Cuando se crea la versión de secreto v3, la aplicación utiliza la versión de secreto v2 existente para obtener información. Una vez que v3 esté lista, se cambiará la etiqueta de almacenamiento temporal y la aplicación podrá utilizar v3 para obtener información.

Restricciones

Asegúrese de que su cuenta tenga permiso de KMS Administrator o de KMS CMKFullAccess. Para obtener más detalles, consulte Gestión de permisos de DEW.

API de rotación de secreto

Puede invocar a las siguientes API para rotar secretos localmente.

API

Descripción

Creación de una versión de secreto

Crear una versión de secreto.

Consulta de la versión y el valor de del secreto

La información sobre una versión del secreto específica y el valor del secreto de texto plano de la versión.

Actualización del estado de versión de un secreto

Actualizar el estado de versión de un secreto.

Consulta del estado de una versión del secreto

Consultar el estado de una versión del secreto especificada.

Ejemplo de rotación del secreto de las cuentas dobles

  1. Cree un secreto en la consola de Huawei Cloud como administrador. Para obtener más detalles, consulte Creación de un secreto.
  2. Prepare la información básica de autenticación.
    • ACCESS_KEY: Clave de acceso de la cuenta de Huawei
    • SECRET_ACCESS_KEY: Clave de acceso secreta de la cuenta de Huawei
    • PROJECT_ID: ID de proyecto de un sitio de Huawei Cloud. Para obtener más detalles, véase Proyecto.
    • CSMS_ENDPOINT: punto de conexión para acceder al CSMS. Consulte Puntos de conexión para obtener más detalles.
    • There will be security risks if the AK/SK used for authentication is directly written into code. Encrypt the AK/SK in the configuration file or environment variables for storage.
    • In this example, the AK/SK stored in the environment variables are used for identity authentication. Configure the environment variables HUAWEICLOUD_SDK_AK and HUAWEICLOUD_SDK_SK in the local environment first.
  3. Rotate the secret for two users.

    In the example code,

    • secretName indicates the name of the secret created on the Huawei Cloud console.
    • secretString indicates the value saved in the secret created on the Huawei Cloud console.
    • versionId indicates the secret ID automatically generated after a secret is created on the Huawei Cloud console.
    • LATEST_VERSION indicates the secret version.
      import com.huaweicloud.sdk.core.auth.BasicCredentials;
      import com.huaweicloud.sdk.csms.v1.CsmsClient;
      import com.huaweicloud.sdk.csms.v1.model.CreateSecretVersionRequest;
      import com.huaweicloud.sdk.csms.v1.model.CreateSecretVersionRequestBody;
      import com.huaweicloud.sdk.csms.v1.model.CreateSecretVersionResponse;
      import com.huaweicloud.sdk.csms.v1.model.ListSecretStageRequest;
      import com.huaweicloud.sdk.csms.v1.model.ListSecretStageResponse;
      import com.huaweicloud.sdk.csms.v1.model.ShowSecretVersionRequest;
      import com.huaweicloud.sdk.csms.v1.model.ShowSecretVersionResponse;
      import com.huaweicloud.sdk.csms.v1.model.UpdateSecretStageRequest;
      import com.huaweicloud.sdk.csms.v1.model.UpdateSecretStageRequestBody;
      
      import java.util.Collections;
      import java.util.List;
      
      public class CsmsDualAccountExample {
          /**
           * Basic authentication information:
           * - ACCESS_KEY: Access key of the Huawei account
           * - SECRET_ACCESS_KEY: Secret access key of the Huawei account
           * - PROJECT_ID: Huawei Cloud project ID. For details, see https://support.huaweicloud.com/intl/en-us/productdesc-iam/iam_01_0023.html
      * - CSMS_ENDPOINT: endpoint address for accessing CSMS. For details, see https://support.huaweicloud.com/intl/en-us/api-dew/dew_02_0052.html.
           * - There will be security risks if the AK/SK used for authentication is directly written into code. Encrypt the AK/SK in the configuration file or environment variables for storage;
           * - In this example, the AK/SK stored in the environment variables are used for identity authentication. Configure the environment variables HUAWEICLOUD_SDK_AK and HUAWEICLOUD_SDK_SK in the local environment first.
           */
          private static final String ACCESS_KEY = System.getenv("HUAWEICLOUD_SDK_AK");
          private static final String SECRET_ACCESS_KEY = System.getenv("HUAWEICLOUD_SDK_SK");
          private static final String PROJECT_ID = "<ProjectID>";
          private static final String CSMS_ENDPOINT = "<CsmsEndpoint>";
      
          //Version ID used to query the latest secret version details.
          private static final String LATEST_VERSION = "latest";
          private static final String HW_CURRENT_STAGE = "SYSCURRENT";
          private static final String HW_PENDING_STAGE = "HW_PENDING";
      
          public static void main(String[] args) {
              String secretName = args[0];
              String secretString = args[1];
      
              dualAccountRotation(secretName, secretString);
          }
      
          /**
           * Example: secret rotation for two accounts
           *
           * @param secretName
           * @param secretString
           */
          private static void dualAccountRotation(String secretName, String secretString) {
              // Create a new secret version with a custom version status. Assume that the secret content is the account password of service A.
              CreateSecretVersionResponse newSecretVersion = createNewSecretVersionWithStage(secretName,
                      secretString, Collections.singletonList(HW_PENDING_STAGE));
              String versionId = newSecretVersion.getVersionMetadata().getId();
      
              // Before rotation, check whether the pending state is modified.
              ListSecretStageResponse listSecretStageResponse = showSecretStage(secretName, HW_PENDING_STAGE);
              assert listSecretStageResponse.getStage().getVersionId().equals(versionId);
      
              // After the account and password of service A are updated, the version status of the new secret is updated to SYSCURRENT. The old secret is still stored in the service and cannot be accessed by specifying latest.
              updateSecretStage(secretName, versionId, HW_CURRENT_STAGE);
      
              // Query the secret of the latest version by specifying latest to complete the dual-account secret rotation.
              ShowSecretVersionResponse secretResponse = showVersionDetail(secretName, LATEST_VERSION);
      
              assert secretResponse.getVersion().getSecretString().equals(secretString);
          }
      
          /**
           * Example of creating a secret
           * If you add a secret version by customizing the version status, the program will not point the SYSCURRENT version status to this version.
           *
           * @param secretName
           * @param newSecretVersionText
           * @param stageList
           * @return
           */
          private static CreateSecretVersionResponse createNewSecretVersionWithStage(String secretName,
                                                                                     String newSecretVersionText,
                                                                                     List<String> stageList) {
              CsmsClient csmsClient = getCsmsClient();
      
              //Host the new secret in CSMS.
              CreateSecretVersionRequest createSecretVersionRequest = new CreateSecretVersionRequest()
                      .withSecretName(secretName)
                      .withBody(new CreateSecretVersionRequestBody()
                              .withSecretString(newSecretVersionText)
                              .withVersionStages(stageList));
      
              CreateSecretVersionResponse secretVersion = csmsClient.createSecretVersion(createSecretVersionRequest);
      
              System.out.printf("Created new version success, version id: %s", secretVersion.getVersionMetadata().getId());
      
              return secretVersion;
          }
      
          /**
           * Point the input version state to the specified secret version.
           * @param secretName
           * @param versionId
           * @param newStageName
           */
          private static void updateSecretStage(String secretName, String versionId, String newStageName) {
              UpdateSecretStageRequest updateSecretStageRequest = new UpdateSecretStageRequest().withSecretName(secretName)
                      .withStageName(newStageName).withBody(new UpdateSecretStageRequestBody().withVersionId(versionId));
      
              CsmsClient csmsClient = getCsmsClient();
      
              csmsClient.updateSecretStage(updateSecretStageRequest);
      
              System.out.printf("Version stage update success. version id:%s, new stage name:%s", versionId, newStageName);
          }
      
          /**
           * Query the secret of a specified version.
           * @param secretName
           * @param versionId
           * @return
           */
          private static ShowSecretVersionResponse showVersionDetail(String secretName, String versionId) {
              ShowSecretVersionRequest showSecretVersionRequest = new ShowSecretVersionRequest().withSecretName(secretName)
                      .withVersionId(versionId);
      
              CsmsClient csmsClient = getCsmsClient();
              ShowSecretVersionResponse secretDetail = csmsClient.showSecretVersion(showSecretVersionRequest);
      
              System.out.printf("Query latest version success. version id:%s",
       secretDetail.getVersion().getVersionMetadata().getId());
              return secretDetail;
          }
      
          /**
           * Query the status of a specified version.
           * @param secretName
           * @param stageName
           * @return
           */
          private static ListSecretStageResponse showSecretStage(String secretName, String stageName) {
              ShowSecretStageRequest showSecretStageRequest = new ShowSecretStageRequest()
                      .withSecretName(secretName).withStageName(stageName);
              CsmsClient csmsClient = getCsmsClient();
              return csmsClient.showSecretStage(showSecretStageRequest);
          }
      
          /**
           * Obtain the CSMS client.
           *
           * @return
           */
          private static CsmsClient getCsmsClient() {
              BasicCredentials auth = new BasicCredentials()
                      .withAk(ACCESS_KEY)
                      .withSk(SECRET_ACCESS_KEY)
                      .withProjectId(PROJECT_ID);
              return CsmsClient.newBuilder().withCredential(auth).withEndpoint(CSMS_ENDPOINT).build();
          }
      }

Utilizamos cookies para mejorar nuestro sitio y tu experiencia. Al continuar navegando en nuestro sitio, tú aceptas nuestra política de cookies. Descubre más

Comentarios

Comentarios

Comentarios

0/500

Seleccionar contenido

Enviar el contenido seleccionado con los comentarios