Secrets JDBC client

更新时间:
复制 MD 格式

When connecting to a database with JDBC, you can store your database credentials in an RDS secret or a generic secret. Your application can then use the secrets JDBC client to authenticate to the database with the secret from KMS.

SDK overview

The secrets JDBC client is designed for connecting to databases by using JDBC. The client simplifies integration by automatically retrieving a secret from KMS to authenticate the database connection. For other scenarios that involve retrieving and using secrets, we recommend using the secrets client first, followed by the KMS instance SDK and the Alibaba Cloud SDK. For more information, see SDK Reference.

Note

You can manage secrets only by using the Alibaba Cloud SDK.

The secrets JDBC client provides the following features:

  • Supports Java Database Connectivity (JDBC), including connections that use database connection pools (such as c3p0 and DBCP) and data sources.

  • Supports four database types: MySQL, SQL Server, PostgreSQL, and MariaDB.

  • Supports custom refresh intervals for secrets.

Usage notes

  • Supported secret types: generic secrets and RDS secrets.

    • If you use an RDS secret, we recommend using a dual-account managed RDS secret.

    • If you use a generic secret, the secret value must be in the following JSON format.

      {
          "AccountName":"<your-database-username>",
          "AccountPassword":"<your-database-password>"
      }
  • Supported programming language: Java 8 or later.

  • Supported database connection pools: c3p0, DBCP, HikariCP, and Druid.

Step 1: Create an access credential

Scenario 1: Retrieve secrets by using a shared gateway

The supported network types are the public network and VPC. This method supports RAM-based authentication methods such as an ECS instance RAM role, RamRoleArn, an STS token, and an AccessKey. For more information, see Manage access credentials.

ECS instance RAM role

An ECS instance RAM role allows you to obtain a temporary access credential (STS token) from within an ECS instance to call KMS API operations, without needing to configure an AccessKey pair.

For more information, see Instance RAM roles.

  1. Log on to the RAM console and create a RAM role for a trusted Alibaba Cloud service.

    • Trusted Entity Type: Select Elastic Compute Service.

    • Trusted entity: Select Elastic Compute Service (ECS).

  2. Grant the RAM role permissions to access KMS.

    • Method 1: Configure an identity-based policy

      In the Actions column of the RAM role, click Grant Permission to attach a built-in system permission policy for KMS to the RAM role. For more information about the system permission policies for KMS, see System policies for KMS.

      Note

      You can also create custom permission policies. For more information, see Create a custom policy.

    • Method 2: Configure a resource-based policy

      KMS supports resource-based policies that grant access permissions for individual keys and secrets. You can use these policies to control which Alibaba Cloud accounts, RAM users, and RAM roles can manage or use KMS keys and secrets. For more information, see Key policies and Secret policies.

  3. Log on to the ECS console and attach the RAM role to an ECS instance.image

RamRoleArn

RAM users or cloud services can assume a role to obtain temporary permissions (STS token) instead of using long-term keys, which reduces the risk of key leaks. For example, in a temporary data processing task, a RAM user or cloud service temporarily assumes a role with a specific RamRoleArn. After the task is complete, the role permissions are revoked, minimizing the risk of exposure.

  1. Create a user AccessKey pair

    1. Log on to the RAM console. In the left-side navigation pane, choose Identities > Users. On the Users page, click the name of the target RAM user.

    2. Attach the AliyunSTSAssumeRoleAccess system policy or a custom policy that includes the sts:AssumeRole action to the RAM user.

    3. On the Authentication tab, in the AccessKey section, click Create AccessKey and follow the on-screen instructions.

  2. Create and authorize a RAM role:

    1. In the left-side navigation pane, choose Identities > Roles. On the Roles page, click Create Role. For more information, see Create a RAM role.

    2. Grant the RAM role permissions to access KMS.

      • Method 1: Configure an identity-based policy

        In the Actions column of the RAM role, click Grant Permission to attach a built-in system permission policy for KMS to the RAM role. For more information about the system permission policies for KMS, see System policies for KMS.

        Note

        You can also create custom permission policies. For more information, see Create a custom policy.

      • Method 2: Configure a resource-based policy

        KMS supports resource-based policies that grant access permissions for individual keys and secrets. You can use these policies to control which Alibaba Cloud accounts, RAM users, and RAM roles can manage or use KMS keys and secrets. For more information, see Key policies and Secret policies.

  3. Obtain the RamRoleArn of the target RAM role. For more information, see View the information about a RAM role.

    1. In the left-side navigation pane, choose Identities > Roles. On the Roles page, click the name of the target role.

    2. On the role details page, find the RamRoleArn in the ARN section.

      Note

      The RamRoleArn is the Alibaba Cloud Resource Name (ARN) of the RAM role to assume. The format is acs:ram::$accountID:role/$roleName, where $accountID is the Alibaba Cloud account ID and $roleName is the RAM role name.

STS token

Security Token Service (STS) issues a temporary access credential, an STS token, to a RAM user or RAM role. This token allows access to KMS with specific permissions for a limited validity period. After the token expires, it automatically becomes invalid.

  1. Log on to the RAM console to create a RAM user or a RAM role. For more information, see Create a RAM user and Create a RAM role.

  2. Grant the AliyunSTSAssumeRoleAccess permission to the RAM user or RAM role. For more information, see Manage RAM user permissions and Grant permissions to a RAM role.

  3. Grant the RAM user or RAM role permissions to access KMS.

    • Method 1: Configure an identity-based policy

      In the Actions column of the RAM role or user, click Grant Permission to attach a built-in system permission policy for KMS. For more information about the system permission policies for KMS, see System policies for KMS.

      Note

      You can also create custom permission policies. For more information, see Create a custom policy.

    • Method 2: Configure a resource-based policy

      KMS supports resource-based policies that grant access permissions for individual keys and secrets. You can use these policies to control which Alibaba Cloud accounts, RAM users, and RAM roles can manage or use KMS keys and secrets. For more information, see Key policies and Secret policies.

  4. Use the RAM user or RAM role to call the STS AssumeRole operation to obtain a temporary STS access credential. For more information, see AssumeRole.

AccessKey

Warning

By default, an Alibaba Cloud account has administrator permissions for all resources, which cannot be modified. To ensure resource security, we recommend that you use a RAM user to create an AccessKey pair and grant it only the necessary permissions.

  1. Log on to the RAM console. On the Users page, click the name of the target RAM user.

  2. On the Authentication tab, in the AccessKey section, click Create AccessKey and follow the on-screen instructions.

  3. Grant the RAM user permissions to access KMS.

    • Method 1: Configure an identity-based policy

      In the Actions column of the RAM user, click Grant Permission to attach a built-in system permission policy for KMS to the RAM user. For more information about the system permission policies for KMS, see System policies for KMS.

      Note

      You can also create custom permission policies. For more information, see Create a custom policy.

    • Method 2: Configure a resource-based policy

      KMS supports resource-based policies that grant access permissions for individual keys and secrets. You can use these policies to control which Alibaba Cloud accounts, RAM users, and RAM roles can manage or use KMS keys and secrets. For more information, see Key policies and Secret policies.

ClientKey (not recommended)

  1. Log on to the Key Management Service console. In the top navigation bar, select a region. In the left-side navigation pane, choose Application Access > Multi-Cloud Access (formerly AAP).

  2. (Optional) Create a network rule.

    Note

    Configuring a network rule to restrict access by source IP address is optional. However, we recommend configuring one for better security.

    1. Click the Network Access Rules tab and then click Create Network Access Rule.

    2. In the Create Network Access Rule panel, set Network Type to Public, enter the Allowed Source IP Addresses, and click OK.

  3. Create a permission policy.

    1. Click the Policies tab and then click Create Policy.

    2. In the Create Policy panel, configure the parameters for the shared gateway as described below, and then click OK.

      1. Scope: Shared KMS Gateway

      2. Accessible Resources: Select the secrets you want to access.

      3. (Optional) Network Access Rules: Select the network rule created in the previous step.

  4. Create an application access point (AAP).

    1. Click the Application Access tab and then click Create AAP.

    2. In the Create AAP panel, set Mode to Standard Creation, and then configure the parameters as described below.

      Parameter

      Description

      Authentication Method

      Select ClientKey.

      Encryption Password

      Enter an 8- to 64-character string that contains digits, letters, and special characters: ~!@#$%^&*?_-.

      Validity Period

      Important

      We recommend setting the validity period to one year to reduce the risk of ClientKey leaks. Be sure to rotate the ClientKey before it expires to avoid service interruptions. For more information, see Rotate a ClientKey.

      Policies

      Select the permission policy that you created in the previous step.

    3. Click OK. The browser automatically downloads the ClientKey. The ClientKey includes the following files:

      • Credential (ClientKeyContent): The default filename is clientKey_****.json.

      • Credential password (ClientKeyPassword): The default filename is clientKey_****_Password.txt.

Scenario 2: Retrieve secrets by using a dedicated gateway (not recommended)

The network type is a KMS private network, and ClientKey is the only supported access credential.

You can create a ClientKey by using either Quick Create or Standard Create mode. For more information about ClientKeys, see Application access points and Create an application access point.

  • Method 1: Quick Create

    This method is convenient and efficient, making it suitable for rapid testing and development. The access credential created this way has full access to all resources in the KMS instance.

    1. Log on to the Key Management Service console. In the top navigation bar, select a region. In the left-side navigation pane, choose Application Access > Multi-Cloud Access (formerly AAP).

    2. On the Application Access tab, click Create AAP. In the Create AAP panel, configure the parameters.

      Parameter

      Description

      Mode

      Select Quick Creation.

      Scope (KMS Instance)

      Select the KMS instance that your application needs to access.

      Application Access Point Name

      Enter a name for the application access point.

      Authentication Method

      This is set to ClientKey and cannot be changed.

      Default Permission Policy

      The value is key/* secret/* and cannot be changed. This means the application can access all keys and secrets in the specified KMS instance.

    3. Click OK. The browser automatically downloads the ClientKey. The ClientKey includes the following files:

      • Credential (ClientKeyContent): The default filename is clientKey_****.json.

      • Credential password (ClientKeyPassword): The default filename is clientKey_****_Password.txt.

  • Method 2: Standard Create

    If you need to configure fine-grained access permissions for resources, we recommend that you use the Standard Create method.

    1. Follow the Standard Create instructions in Create an application access point to create a ClientKey for accessing the dedicated gateway. The key parameters are described below:

      1. When configuring network rules, select Private for the network type.

      2. When you configure the scope of the permission rule, select the corresponding KMS Instance ID.

    2. After creation, your browser automatically downloads the ClientKey, which includes:

      • Credential (ClientKeyContent): The file is named clientKey_****.json by default.

      • Credential password (ClientKeyPassword): The file is named clientKey_****_Password.txt by default.

Step 2: Install the client

Install the secrets JDBC client by using Maven.

<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>aliyun-secretsmanager-jdbc</artifactId>
    <version>x.x.x</version>
</dependency>
<dependency>
  <groupId>com.aliyun</groupId>
  <artifactId>aliyun-java-sdk-core</artifactId>
  <version>4.x.x</version>
</dependency>
Note

We recommend that you install the latest version of the SDK. For more information about the installation and source code, visit aliyun-secretsmanager-jdbc.

Step 3: Initialize the client with secretsmanager.properties

Add a configuration file named secretsmanager.properties to your project. The parameters that you need to configure vary based on the access credential.

AccessKey

## The type of the access credential.
credentials_type=ak
## The AccessKey ID.
credentials_access_key_id=#credentials_access_key_id#
## The AccessKey secret.
credentials_access_secret=#credentials_access_secret#
## The region of the associated KMS service.
cache_client_region_id=[{"regionId":"#regionId#"}]
## The custom refresh interval. Default value: 6 hours. Minimum value: 5 minutes. Unit: milliseconds.
refresh_secret_ttl=21600000

RamRoleArn

## The type of the access credential.
credentials_type=ram_role
## The AccessKey ID.
credentials_access_key_id=#credentials_access_key_id#
## The AccessKey secret.
credentials_access_secret=#credentials_access_secret#
## The session name of the access credential.
credentials_role_session_name=#credentials_role_session_name#
## The ARN of the RAM role.
credentials_role_arn=#credentials_role_arn#
## The policy of the access credential.
credentials_policy=#credentials_policy#
## The region of the associated KMS service.
cache_client_region_id=[{"regionId":"#regionId#"}]
## The custom refresh interval. Default value: 6 hours. Minimum value: 5 minutes. Unit: milliseconds.
refresh_secret_ttl=21600000

ECS instance RAM role

## The type of the access credential.
credentials_type=ecs_ram_role
## The name of the ECS RAM role.
credentials_role_name=#credentials_role_name#
## The region of the associated KMS service.
cache_client_region_id=[{"regionId":"#regionId#"}]
## The custom refresh interval. Default value: 6 hours. Minimum value: 5 minutes. Unit: milliseconds.
refresh_secret_ttl=21600000

STS token

## The type of the access credential.
credentials_type=sts
## The AccessKey ID.
credentials_access_key_id=#credentials_access_key_id#
## The AccessKey secret.
credentials_access_secret=#credentials_access_secret#
## The session name of the access credential.
credentials_role_session_name=#credentials_role_session_name#
## The ARN of the RAM role.
credentials_role_arn=#credentials_role_arn#
## The policy of the access credential.
credentials_policy=#credentials_policy#
## The region of the associated KMS service.
cache_client_region_id=[{"regionId":"#regionId#"}]
## The custom refresh interval. Default value: 6 hours. Minimum value: 5 minutes. Unit: milliseconds.
refresh_secret_ttl=21600000

ClientKey (shared gateway)

## The type of the access credential.
credentials_type=client_key
# The file path of the ClientKey.
client_key_private_key_path=#your client key private key file path#
## The decryption password of the ClientKey. You can read the password from an environment variable or a file.
client_key_password_from_env_variable=#your client key private key password environment variable name#
client_key_password_from_file_path=#your client key private key password file path#
## The region of the associated KMS service.
cache_client_region_id=[{"regionId":"#regionId#"}]
## The custom refresh interval. Default value: 6 hours. Minimum value: 5 minutes. Unit: milliseconds.
## The following configuration sets the secret refresh interval to 1 hour.
refresh_secret_ttl=3600000

ClientKey (dedicated gateway)

Approach 1: Configure the file path


cache_client_dkms_config_info=[{"regionId":"<your_dkms_region_id>","endpoint":"<your_dkms_endpoint>","passwordFromFilePath":"<your_password_file_path>","clientKeyFile":"<your_client_key_file_path>","ignoreSslCerts":false,"caFilePath":"<your_ca_certificate_file_path>"}]
              

Approach 2: Configure the password via environment variable


cache_client_dkms_config_info=[{"regionId":"<your_dkms_region_id>","endpoint":"<your_dkms_endpoint>","passwordFromEnvVariable":"<YOUR_PASSWORD_ENV_VARIABLE>","clientKeyFile":"<your_client_key_file_path>","ignoreSslCerts":false,"caFilePath":"<your_ca_certificate_file_path>"}]
              

Step 4: Connect to the database

Important

The following examples show only the properties that you must modify. Configure other properties based on your business requirements.

Connect to a database by using JDBC

  • MySQL database

    Note

    Replace #your-mysql-secret-name#, <your-mysql-ip>, <your-mysql-port>, and <your-database-name> with the actual secret name, server IP address, port, and database name.

    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    
    public class SecretManagerJDBCSample {
        public static void main(String[] args) throws Exception {
            // Load the Alibaba Cloud secrets JDBC driver: com.aliyun.kms.secretsmanager.MysqlSecretsManagerSimpleDriver
            Class.forName("com.aliyun.kms.secretsmanager.MysqlSecretsManagerSimpleDriver");
            Connection connect = null;
            try {
                connect = DriverManager.getConnection("secrets-manager:mysql://<your-mysql-ip>:<your-mysql-port>/<your-database-name>", "#your-mysql-secret-name#","");
            } catch(SQLException e) {
                e.printStackTrace();
            }
        }
    }
  • SQL Server database

    Note

    Replace #your-sqlserver-secret-name#, <your-sqlserver-ip>, <your-sqlserver-port>, and <your-database-name> with the actual secret name, server IP address, port, and database name.

    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    
    public class SecretManagerJDBCSqlServerSample {
    
        public static void main(String[] args) throws Exception{
            // Load the Alibaba Cloud secrets JDBC driver: com.aliyun.kms.secretsmanager.MssqlSecretsManagerSimpleDriver
            Class.forName("com.aliyun.kms.secretsmanager.MssqlSecretsManagerSimpleDriver");
            Connection connect = null;
            try {
                connect = DriverManager.getConnection("secrets-manager:sqlserver://<your-sqlserver-ip>:<your-sqlserver-port>;databaseName=<your-database-name>", "#your-sqlserver-secret-name#", "");
            }  catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
  • PostgreSQL database

    Note

    Replace #your-postgresql-secret-name#, <your-postgresql-ip>, <your-postgresql-port>, and <your-database-name> with the actual secret name, server IP address, port, and database name.

    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    
    public class SecretManagerJDBCPostgreSQLSample {
        public static void main(String[] args) throws Exception {
            // Load the Alibaba Cloud secrets JDBC driver: com.aliyun.kms.secretsmanager.PostgreSQLSecretManagerSimpleDriver
            Class.forName("com.aliyun.kms.secretsmanager.PostgreSQLSecretManagerSimpleDriver");
            Connection connect = null;
            try {
                connect = DriverManager.getConnection("secrets-manager:postgresql://<your-postgresql-ip>:<your-postgresql-port>/<your-database-name>", "#your-postgresql-secret-name#", "");
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
  • MariaDB database

    Note

    Replace #your-mariadb-secret-name#, <your-mariadb-ip>, <your-mariadb-port>, and <your-database-name> with the actual secret name, server IP address, port, and database name.

    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    
    public class SecretManagerJDBCMarialDBSample {
    
    	public static void main(String[] args) throws Exception{
    		// Load the Alibaba Cloud secrets JDBC driver: com.aliyun.kms.secretsmanager.MariaDBSecretManagerSimpleDriver
    		Class.forName("com.aliyun.kms.secretsmanager.MariaDBSecretManagerSimpleDriver");
    		Connection connect = null;
    		try {
    			connect = DriverManager.getConnection("secrets-manager:mariadb://<your-mariadb-ip>:<your-mariadb-port>/<your-database-name>", "#your-mariadb-secret-name#", "");
    		}  catch (SQLException e) {
    			e.printStackTrace();
    		}
    	}
    }

Connect by using a database connection pool

Set c3p0.user, c3p0.driverClass, and c3p0.jdbcUrl in the c3p0.properties configuration file. c3p0.user is the secret name, c3p0.driverClass is the Alibaba Cloud secret JDBC Driver class name, and c3p0.jdbcUrl must start with secrets-manager.

  • MySQL database

    Note

    Replace #your-mysql-secret-name#, <your-mysql-ip>, <your-mysql-port>, and <your-database-name> with the actual secret name, server IP address, port, and database name.

    c3p0.user=#your-mysql-secret-name#
    c3p0.driverClass=com.aliyun.kms.secretsmanager.MysqlSecretsManagerSimpleDriver
    c3p0.jdbcUrl=secrets-manager:mysql://<your-mysql-ip>:<your-mysql-port>/<your-database-name>
  • SQL Server database

    Note

    Replace #your-sqlserver-secret-name#, <your-sqlserver-ip>, <your-sqlserver-port>, and <your-database-name> with the actual secret name, server IP address, port, and database name.

    c3p0.user=#your-sqlserver-secret-name#
    c3p0.driverClass=com.aliyun.kms.secretsmanager.MssqlSecretsManagerSimpleDriver
    c3p0.jdbcUrl=secrets-manager:sqlserver://<your-sqlserver-ip>:<your-sqlserver-port>/<your-database-name>
  • PostgreSQL database

    Note

    Replace #your-postgresql-secret-name#, <your-postgresql-ip>, <your-postgresql-port>, and <your-database-name> with the actual secret name, server IP address, port, and database name.

    c3p0.user=#your-postgresql-secret-name#
    c3p0.driverClass=com.aliyun.kms.secretsmanager.PostgreSQLSecretManagerSimpleDriver
    c3p0.jdbcUrl=secrets-manager:postgresql://<your-postgresql-ip>:<your-postgresql-port>/<your-database-name>
  • MariaDB database

    Note

    Replace #your-mariadb-secret-name#, <your-mariadb-ip>, <your-mariadb-port>, and <your-database-name> with the actual secret name, server IP address, port, and database name.

    c3p0.user=#your-mariadb-secret-name#
    c3p0.driverClass=com.aliyun.kms.secretsmanager.MariaDBSecretManagerSimpleDriver
    c3p0.jdbcUrl=secrets-manager:mariadb://<your-mariadb-ip>:<your-mariadb-port>/<your-database-name>

Connect by using a data source

This example uses a c3p0 ComboPooledDataSource and a MySQL database. Add the following configuration to the Spring configuration file.

Note

Replace #your-mysql-secret-name#, <your-mysql-ip>, <your-mysql-port>, and <your-database-name> with the actual secret name, server IP address, port, and database name.

<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" >
      <property name="driverClass" value="com.aliyun.kms.secretsmanager.MysqlSecretsManagerSimpleDriver" />
      <property name="user" value="#your-mysql-secret-name#" />
      <property name="jdbcUrl" value="secrets-manager:mysql://<your-mysql-ip>:<your-mysql-port>/<your-database-name>" />
      <property name="maxPoolSize" value="***" />
      <property name="minPoolSize" value="***" />
      <property name="initialPoolSize" value="***" />
  </bean>
  <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate" >
      <property name="dataSource" ref="dataSource" />
  </bean>
Note

Set the values of the maxPoolSize, minPoolSize, and initialPoolSize parameters based on your business requirements.

Connect by using a Druid connection pool

This example uses a MySQL database. You must modify the following properties in the configuration file.

Note

Replace #your-mysql-secret-name#, <your-mysql-ip>, <your-mysql-port>, and <your-database-name> with the actual secret name, server IP address, port, and database name.

  • Use a properties configuration file

    username=#your-mysql-secret-name#
    driverClassName=com.aliyun.kms.secretsmanager.MysqlSecretsManagerSimpleDriver
    url=secrets-manager:mysql://<your-mysql-ip>:<your-mysql-port>/<your-database-name>
  • Use bean configuration

    • Method 1: XML configuration file

      <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> 
           <property name="username" value="${your-mysql-secret-name}" />
           <property name="driverClassName" value="com.aliyun.kms.secretsmanager.MysqlSecretsManagerSimpleDriver" />
           <property name="url" value="secrets-manager:mysql://<your-mysql-ip>:<your-mysql-port>/<your-database-name>" />
      </bean>
      
    • Method 2: Property injection

      Create a configuration class in your application to load database connection information.

      @Configuration
      public class DataConfig {
      
          @Value("${your-mysql-secret-name}")
          private String username;
      
          @Value("com.aliyun.kms.secretsmanager.MysqlSecretsManagerSimpleDriver")
          private String driverClassName;
      
          @Value("secrets-manager:mysql://<your-mysql-ip>:<your-mysql-port>/<your-database-name>")
          private String url;
      
          @Bean(name = "dataSource",initMethod = "init",destroyMethod = "close")
          public DruidDataSource dataSource(){
              DruidDataSource druidDataSource = new DruidDataSource();
              druidDataSource.setUsername(username);
              druidDataSource.setDriverClassName(driverClassName);
              druidDataSource.setUrl(url);
              return druidDataSource;
          }
      }