All Products
Search
Document Center

Tablestore:Use temporary access credentials obtained from STS to initiate requests

更新時間:Sep 25, 2024

You can use Security Token Service (STS) to grant temporary access credentials to other users. Then, other users can use the temporary access credentials to access Tablestore resources within the validity period of the temporary access credentials. After the validity period ends, the temporary access credentials become invalid and other users cannot use the temporary access credentials to access Tablestore resources. This ensures flexible and time-limited access control.

Step 1: Create a RAM user

  1. Log on to the RAM console by using an Alibaba Cloud account or a RAM user who has administrative rights.

  2. In the left-side navigation pane, choose Identities > Users.

  3. On the Users page, click Create User.

  4. In the User Account Information section of the Create User page, configure the following parameters:

    • Logon Name: The logon name can be up to 64 characters in length, and can contain letters, digits, periods (.), hyphens (-), and underscores (_).

    • Display Name: The display name can be up to 128 characters in length.

    • Tag: Click the edit icon and enter a tag key and a tag value. You can add one or more tags to the RAM user. This way, you can manage the RAM user based on the tags.

    Note

    You can click Add User to create multiple RAM users at a time.

  5. In the Access Mode section, select OpenAPI Access and click ok.

  6. Follow the on-screen instructions to complete security verification.

  7. Click Copy to save the AccessKey pair of the RAM user.

    Important

    You can obtain the AccessKey secret of a RAM user only when you create the RAM user. You cannot query the AccessKey secret in subsequent operations. Record and keep your AccessKey secret confidential.

Step 2: Grant the RAM user the permissions to call the AssumeRole operation

After you create the RAM user, grant the RAM user the permissions to call the AssumeRole operation of STS.

  1. On the Users page, find the RAM user that you created and click Add Permissions in the Actions column.

  2. In the Grant Permission panel, select the AliyunSTSAssumeRoleAccess system policy.

    Note

    The AliyunSTSAssumeRoleAccess policy grants the RAM user the permissions to call the AssumeRole operation. The permissions required to call the AssumeRole operation are independent of the permissions required to obtain temporary access credentials from STS and the permissions required to initiate requests to Tablestore by using the temporary access credentials.

    image.png

  3. Click Grant permissions.

Step 3: Create a RAM role

Create a RAM role to specify the Tablestore access permissions of the RAM role when the RAM role is assumed.

  1. In the left-side navigation pane, choose Identities > Roles.

  2. Click Create Role. In the Select Role Type step of the Create Role wizard, set Select Trusted Entity to Alibaba Cloud Account and click Next.

  3. In the Create Role step of the Create Role wizard, set RAM Role Name to RamTablestoreTest and select Current Alibaba Cloud Account for Select Trusted Alibaba Cloud Account.

  4. Click OK. After you create the RAM role, click Close.

  5. On the Roles page, enter the role name RamTablestoreTest in the search box and click the search icon. Then, click RamTablestoreTest.

  6. Click Copy to the right of Alibaba Cloud Resource Name (ARN) on the RamTablestoreTest page to save the ARN of the RAM role.

    image

Step 4: Grant Tablestore read-only access to the RAM role

Attach one or more policies to the RAM role to specify the Tablestore access permissions of the RAM role when the RAM role is assumed. For example, you can attach a policy to the RAM role to grant Tablestore read-only access to the RAM role when a RAM user assumes the RAM role.

  1. Create a custom policy.

    1. In the left-side navigation pane, choose Permissions > Policies.

    2. On the Policies page, click Create Policy.

    3. On the Create Policy page, click the JSON tab. Enter the following script in the code editor to grant Tablestore read-only access to the RAM role.

      Warning

      The following example is provided for reference only. You must configure fine-grained RAM policies based on your business requirements to avoid granting excessive permissions to the RAM role. For information about how to configure fine-grained policies, see Create a custom policy.

      {
        "Version": "1",
        "Statement": [
          {
            "Effect": "Allow",
            "Action": [
              "ots:BatchGet*",
              "ots:Describe*",
              "ots:Get*",
              "ots:List*",
              "ots:Consume*",
              "ots:Search",
              "ots:ComputeSplitPointsBySize"
            ],
            "Resource": [
              "acs:ots:*:*:instance/ram-test-app*"
            ],
            "Condition": {}
          }
        ]
      }     
    4. Click Next to edit policy information.

    5. In the Basic information section, set Name to RamTestPolicy and click OK.

  2. Attach the custom policy to the RamTablestoreTest RAM role.

    1. In the left-side navigation pane, choose Identities > Roles.

    2. On the Roles page, find the RamTablestoreTest RAM role.

    3. Click Grant Permission on the right of the RamTablestoreTest RAM role in the Actions column.

    4. In the Grant Permission panel, select Custom Policy from the drop-down list in the Policy section and then select the RamTestPolicy policy.

    5. Click Grant permissions.

Step 5: Use the RAM user to assume the RAM role to obtain temporary access credentials

After you grant Tablestore read-only access to the RAM role, the RAM user must assume the RAM role to obtain temporary access credentials. Temporary access credentials include a security token (SecurityToken), temporary AccessKey pair (AccessKey ID and AccessKey secret), and validity period (Expiration).

Use STS SDKs

You can use STS SDKs to obtain temporary access credentials.

Java

In this example, STS SDK for Java is used.

Note

SDK installation information

  • SDK package name: com.aliyun/sts20150401

  • SDK package version: 1.1.4

  • SDK package management platform: maven

  • SDK installation command:

    <dependency>
      <groupId>com.aliyun</groupId>
      <artifactId>sts20150401</artifactId>
      <version>1.1.4</version>
    </dependency>
import com.aliyun.tea.*;

public class Sample {

    /**
     * <b>description</b> :
     * <p>Use your AccessKey ID and AccessKey secret to initialize a client.</p>
     *
     * @return Client
     * @throws Exception
     */
    public static com.aliyun.sts20150401.Client createClient() throws Exception {
        // If the project code is leaked, the AccessKey pair may be leaked and the security of all resources within your account may be compromised. The following sample code is provided for reference only. 
        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. 
                .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
                // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured. 
                .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
        // Specify the endpoint. For more information, visit https://api.aliyun.com/product/Sts.
        config.endpoint = "sts.cn-hangzhou.aliyuncs.com";
        return new com.aliyun.sts20150401.Client(config);
    }

    public static void main(String[] args_) throws Exception {
        java.util.List<String> args = java.util.Arrays.asList(args_);
        com.aliyun.sts20150401.Client client = Sample.createClient();
        com.aliyun.sts20150401.models.AssumeRoleRequest assumeRoleRequest = new com.aliyun.sts20150401.models.AssumeRoleRequest()
                // Specify the validity period of the temporary access credentials. Unit: seconds. The minimum validity period is 900 seconds. The maximum validity period is the same as the maximum session duration specified for the current role. The maximum session duration of the current role ranges from 3,600 seconds to 43,200 seconds. The default maximum session duration of the current role is 3,600 seconds. 
                .setDurationSeconds(3600L)
                // Specify the external ID of the role. This parameter is provided by an external party and is used to prevent the confused deputy problem. 
                //.setExternalId(null)
                // Configure the policy that specifies the permissions of the STS token. You can use this parameter to grant the STS token fewer permissions than the permissions granted to the RAM role. 
                //.setPolicy(null)
                // Required. Make sure that the TABLESTORE_STS_ROLE_ARN environment variable is configured. The ARN is the RamRoleArn of the RAM role that is created in Step 3. 
                .setRoleArn(System.getenv("TABLESTORE_STS_ROLE_ARN"))
                // Specify the session name for the role to distinguish different tokens. 
                .setRoleSessionName("yourRoleSessionName");
        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.
            client.assumeRoleWithOptions(assumeRoleRequest, 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. 
            // Display error messages.
            System.out.println(error.getMessage());
            // Provide the URL 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. 
            // Display error messages.
            System.out.println(error.getMessage());
            // Provide the URL for troubleshooting.
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
    }
}

Go

In this example, STS SDK for Go is used.

Note

SDK installation information

  • SDK package name: github.com/alibabacloud-go/sts-20150401/v2

  • SDK package version: v2.0.2

  • SDK package management platform: github

  • SDK installation command:

    go get github.com/alibabacloud-go/sts-20150401/v2
package main

import (
  "encoding/json"
  "strings"
  "fmt"
  "os"
  sts20150401  "github.com/alibabacloud-go/sts-20150401/v2/client"
  openapi  "github.com/alibabacloud-go/darabonba-openapi/v2/client"
  util  "github.com/alibabacloud-go/tea-utils/v2/service"
  "github.com/alibabacloud-go/tea/tea"
)


// Description:
// 
// Use your AccessKey ID and AccessKey secret to initialize a client.
// 
// @return Client
// 
// @throws Exception
func CreateClient () (_result *sts20150401.Client, _err error) {
  // If the project code is leaked, the AccessKey pair may be leaked and the security of all resources within your account may be compromised. The following sample code is provided for reference only. 
  config := &openapi.Config{
    // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured. 
    AccessKeyId: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")),
    // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured. 
    AccessKeySecret: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")),
  }
  // Specify the endpoint. For more information, visit https://api.aliyun.com/product/Sts.
  config.Endpoint = tea.String("sts.cn-hangzhou.aliyuncs.com")
  _result = &sts20150401.Client{}
  _result, _err = sts20150401.NewClient(config)
  return _result, _err
}

func _main (args []*string) (_err error) {
  client, _err := CreateClient()
  if _err != nil {
    return _err
  }

	assumeRoleRequest := &sts20150401.AssumeRoleRequest{
    // Required. Make sure that the TABLESTORE_STS_ROLE_ARN environment variable is configured. The ARN is the RamRoleArn of the RAM role that is created in Step 3. 
    RoleArn: tea.String(os.Getenv("TABLESTORE_STS_ROLE_ARN")),
    // Specify the validity period of the temporary access credentials. Unit: seconds. The minimum validity period is 900 seconds. The maximum validity period is the same as the maximum session duration specified for the current role. The maximum session duration of the current role ranges from 3,600 seconds to 43,200 seconds. The default maximum session duration of the current role is 3,600 seconds. 
    DurationSeconds: tea.Int64(3600),
    // Configure the policy that specifies the permissions of the STS token. You can use this parameter to grant the STS token fewer permissions than the permissions granted to the RAM role. 
    //Policy: ,
    // Specify the session name for the role to distinguish different tokens. 
    RoleSessionName: tea.String("yourRoleSessionName"),
    // Specify the external ID of the role. This parameter is provided by an external party and is used to prevent the confused deputy problem.
    //ExternalId: ,
}
  runtime := &util.RuntimeOptions{}
  tryErr := func()(_e error) {
    defer func() {
      if r := tea.Recover(recover()); r != nil {
        _e = r
      }
    }()
    // If you copy and run the sample code, write your own code to display the response of the API operation.
    _, _err = client.AssumeRoleWithOptions(assumeRoleRequest, runtime)
    if _err != nil {
      return _err
    }

    return nil
  }()

  if tryErr != nil {
    var error = &tea.SDKError{}
    if _t, ok := tryErr.(*tea.SDKError); ok {
      error = _t
    } else {
      error.Message = tea.String(tryErr.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. 
    // Display error messages.
    fmt.Println(tea.StringValue(error.Message))
    // Provide the URL for troubleshooting.
    var data interface{}
    d := json.NewDecoder(strings.NewReader(tea.StringValue(error.Data)))
    d.Decode(&data)
    if m, ok := data.(map[string]interface{}); ok {
      recommend, _ := m["Recommend"]
      fmt.Println(recommend)
    }
    _, _err = util.AssertAsString(error.Message)
    if _err != nil {
      return _err
    }
  }
  return _err
}


func main() {
  err := _main(tea.StringSlice(os.Args[1:]))
  if err != nil {
    panic(err)
  }
}

Python

In this example, STS SDK for Python is used.

Note

SDK installation information

  • SDK package name: alibabacloud_sts20150401

  • SDK package version: 1.1.4

  • SDK package management platform: pypi

  • SDK installation command:

    pip install alibabacloud_sts20150401==1.1.4
# -*- coding: utf-8 -*-
# This file is auto-generated, don't edit it. Thanks.
import os
import sys

from typing import List

from alibabacloud_sts20150401.client import Client as Sts20150401Client
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_sts20150401 import models as sts_20150401_models
from alibabacloud_tea_util import models as util_models
from alibabacloud_tea_util.client import Client as UtilClient


class Sample:
    def __init__(self):
        pass

    @staticmethod
    def create_client() -> Sts20150401Client:
        """
        Use your AccessKey ID and AccessKey secret to initialize a client.
        @return: Client
        @throws Exception
        """
        # If the project code is leaked, the AccessKey pair may be leaked and the security of all resources within your account may be compromised. The following sample code is provided for reference only. 
        config = open_api_models.Config(
            # Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured. ,
            access_key_id=os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'],
            # Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured. ,
            access_key_secret=os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
        )
        # Specify the endpoint. For more information, visit https://api.aliyun.com/product/Sts.
        config.endpoint = f'sts.cn-hangzhou.aliyuncs.com'
        return Sts20150401Client(config)

    @staticmethod
    def main(
        args: List[str],
    ) -> None:
        client = Sample.create_client()
        assume_role_request = sts_20150401_models.AssumeRoleRequest(
            # Specify the validity period of the temporary access credentials. Unit: seconds. The minimum validity period is 900 seconds. The maximum validity period is the same as the maximum session duration specified for the current role. The maximum session duration of the current role ranges from 3,600 seconds to 43,200 seconds. The default maximum session duration of the current role is 3,600 seconds. 
            duration_seconds=3600,
            # Specify the external ID of the role. This parameter is provided by an external party and is used to prevent the confused deputy problem. 
            # external_id=None,
            # Configure the policy that specifies the permissions of the STS token. You can use this parameter to grant the STS token fewer permissions than the permissions granted to the RAM role. 
            # policy=None,
            # Required. Make sure that the TABLESTORE_STS_ROLE_ARN environment variable is configured. The ARN is the RamRoleArn of the RAM role that is created in Step 3. 
            role_arn=os.environ['TABLESTORE_STS_ROLE_ARN'],
            # Specify the session name for the role to distinguish different tokens. 
            role_session_name="yourRoleSessionName"
        )
        runtime = util_models.RuntimeOptions()
        try:
            # If you copy and run the sample code, write your own code to display the response of the API operation.
            client.assume_role_with_options(assume_role_request, runtime)
        except Exception as 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. 
            # Display error messages.
            print(error.message)
            # Provide the URL for troubleshooting.
            print(error.data.get("Recommend"))
            UtilClient.assert_as_string(error.message)

    @staticmethod
    async def main_async(
        args: List[str],
    ) -> None:
        client = Sample.create_client()
        assume_role_request = sts_20150401_models.AssumeRoleRequest()
        runtime = util_models.RuntimeOptions()
        try:
            # If you copy and run the sample code, write your own code to display the response of the API operation.
            await client.assume_role_with_options_async(assume_role_request, runtime)
        except Exception as 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. 
            # Display error messages.
            print(error.message)
            # Provide the URL for troubleshooting.
            print(error.data.get("Recommend"))
            UtilClient.assert_as_string(error.message)


if __name__ == '__main__':
    Sample.main(sys.argv[1:])

Node.js

In this example, STS SDK for Node.js is used.

Note

SDK installation information

  • SDK package name: @alicloud/sts20150401

  • SDK package version: 1.1.4

  • SDK package management platform: npm

  • SDK installation command:

    npm install @alicloud/sts20150401@1.1.4
'use strict';
const Sts20150401 = require('@alicloud/sts20150401');
const OpenApi = require('@alicloud/openapi-client');
const Util = require('@alicloud/tea-util');
const Tea = require('@alicloud/tea-typescript');

class Client {

  /**
   * Use your AccessKey ID and AccessKey secret to initialize a client.
   * @return Client
   * @throws Exception
   */
  static createClient() {
    // If the project code is leaked, the AccessKey pair may be leaked and the security of all resources within your account may be compromised. The following sample code is provided for reference only. 
    let config = new OpenApi.Config({
      // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured. 
      accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'],
      // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured. 
      accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
    });
    // Specify the endpoint. For more information, visit https://api.aliyun.com/product/Sts.
    config.endpoint = `sts.cn-hangzhou.aliyuncs.com`;
    return new Sts20150401.default(config);
  }

  static async main(args) {
    let client = Client.createClient();
    let assumeRoleRequest = new Sts20150401.AssumeRoleRequest({
        // Specify the validity period of the temporary access credentials. Unit: seconds. The minimum validity period is 900 seconds. The maximum validity period is the same as the maximum session duration specified for the current role. The maximum session duration of the current role ranges from 3,600 seconds to 43,200 seconds. The default maximum session duration of the current role is 3,600 seconds. 
        durationSeconds: 3600,
        // Specify the external ID of the role. This parameter is provided by an external party and is used to prevent the confused deputy problem. 
        //externalId: null,
        // Configure the policy that specifies the permissions of the STS token. You can use this parameter to grant the STS token fewer permissions than the permissions granted to the RAM role. 
        //policy: null,
        // Required. Make sure that the TABLESTORE_STS_ROLE_ARN environment variable is configured. The ARN is the RamRoleArn of the RAM role that is created in Step 3. 
        roleArn: process.env.TABLESTORE_STS_ROLE_ARN,
        // Specify the session name for the role to distinguish different tokens. 
        roleSessionName: 'yourRoleSessionName'
     });
    let runtime = new Util.RuntimeOptions({ });
    try {
      // If you copy and run the sample code, write your own code to display the response of the API operation.
      await client.assumeRoleWithOptions(assumeRoleRequest, runtime);
    } catch (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. 
      // Display error messages.
      console.log(error.message);
      // Provide the URL for troubleshooting.
      console.log(error.data["Recommend"]);
      Util.default.assertAsString(error.message);
    }    
  }

}

exports.Client = Client;
Client.main(process.argv.slice(2));

PHP

In this example, STS SDK for PHP is used.

Note

SDK installation information

  • SDK package name: alibabacloud/sts-20150401

  • SDK package version: 1.1.4

  • SDK package management platform: packagist

  • SDK installation command:

    composer require alibabacloud/sts-20150401 1.1.4
<?php

namespace AlibabaCloud\SDK\Sample;

use AlibabaCloud\SDK\Sts\V20150401\Sts;
use \Exception;
use AlibabaCloud\Tea\Exception\TeaError;
use AlibabaCloud\Tea\Utils\Utils;

use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Sts\V20150401\Models\AssumeRoleRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;

class Sample {

    /**
     * Use your AccessKey ID and AccessKey secret to initialize a client.
     * @return Sts Client
     */
    public static function createClient(){
        // If the project code is leaked, the AccessKey pair may be leaked and the security of all resources within your account may be compromised. The following sample code is provided for reference only. 
        $config = new Config([
            // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured. 
            "accessKeyId" => getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"),
            // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured. 
            "accessKeySecret" => getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
        ]);
        // Specify the endpoint. For more information, visit https://api.aliyun.com/product/Sts.
        $config->endpoint = "sts.cn-hangzhou.aliyuncs.com";
        return new Sts($config);
    }

    /**
     * @param string[] $args
     * @return void
     */
    public static function main($args){
        $client = self::createClient();
        $assumeRoleRequest = new AssumeRoleRequest([
            // Specify the validity period of the temporary access credentials. Unit: seconds. The minimum validity period is 900 seconds. The maximum validity period is the same as the maximum session duration specified for the current role. The maximum session duration of the current role ranges from 3,600 seconds to 43,200 seconds. The default maximum session duration of the current role is 3,600 seconds. 
            "durationSeconds" => 3600,
            // Specify the session name for the role to distinguish different tokens. 
            "roleSessionName" => "yourRoleSessionName",
            // Required. Make sure that the TABLESTORE_STS_ROLE_ARN environment variable is configured. The ARN is the RamRoleArn of the RAM role that is created in Step 3. 
            "roleArn" =>  getenv("TABLESTORE_STS_ROLE_ARN"),
        ]);
        $runtime = new RuntimeOptions([]);
        try {
            // If you copy and run the sample code, write your own code to display the response of the API operation.
            $client->assumeRoleWithOptions($assumeRoleRequest, $runtime);
        }
        catch (Exception $error) {
            if (!($error instanceof TeaError)) {
                $error = new TeaError([], $error->getMessage(), $error->getCode(), $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. 
            // Display error messages.
            var_dump($error->message);
            // Provide the URL for troubleshooting.
            var_dump($error->data["Recommend"]);
            Utils::assertAsString($error->message);
        }
    }
}
$path = __DIR__ . \DIRECTORY_SEPARATOR . '..' . \DIRECTORY_SEPARATOR . 'vendor' . \DIRECTORY_SEPARATOR . 'autoload.php';
if (file_exists($path)) {
    require_once $path;
}
Sample::main(array_slice($argv, 1));

For information about STS SDKs for other programming languages, see STS SDK overview. For information about STS endpoints, see Endpoints.

Use the RESTful API

You can call the AssumeRole operation of STS to obtain temporary access credentials.

Step 6: Use temporary access credentials obtained from STS to query the names of Tablestore tables

The following Java sample code provides an example on how to use temporary access credentials to query the names of Tablestore tables before the temporary access credentials expire.

Note
  • The expiration time of temporary access credentials is in UTC, which is eight hours later than UTC+8. For example, if the expiration time of temporary access credentials is 2024-04-18T11:33:40Z, the temporary access credentials expire on April 18, 2024 at 19:33:40 (UTC+8).

  • You can use temporary access credentials multiple times before they expire.

Java sample code:

import com.alicloud.openservices.tablestore.SyncClient;
import com.alicloud.openservices.tablestore.core.ResourceManager;
import com.alicloud.openservices.tablestore.core.auth.CredentialsProviderFactory;
import com.alicloud.openservices.tablestore.core.auth.EnvironmentVariableCredentialsProvider;
import com.alicloud.openservices.tablestore.model.ListTableResponse;

public class StsAccessKeySample {
    public static void main(String[] args) {
        // Specify the name of the Tablestore instance. 
        String instanceName = "yourInstance";
        // Specify the endpoint of the Tablestore instance. Example: https://yourInstance.cn-hangzhou.ots.aliyuncs.com. 
        String endPoint = "yourEndpoint";

        // We recommend that you do not save access credentials in the project code. Otherwise, access credentials may be leaked, which compromises the security of all resources in your account. 
        // In this example, access credentials are obtained from environment variables. Before you run the sample code, make sure that the TABLESTORE_ACCESS_KEY_ID, TABLESTORE_ACCESS_KEY_SECRET, and TABLESTORE_SESSION_TOKEN environment variables are configured. 
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();

        // Create an OTSClient instance.
        SyncClient client = new SyncClient(endPoint, credentialsProvider, instanceName, null, new ResourceManager(null, null));

        // Query the names of tables.
        ListTableResponse listTableResponse = client.listTable();
        listTableResponse.getTableNames().forEach(System.out::println);

        // Shut down the OTSClient instance.
        client.shutdown();
    }
}

FAQ

What do I do if the You are not authorized to do this action. You should be authorized by RAM. error message is returned?

In Step 5, the RAM user must use its AccessKey pair (AccessKey ID and AccessKey secret), not the AccessKey pair of the Alibaba Cloud account, to assume the RAM role to obtain temporary access credentials.

What do I do if the error message The Min/Max value of DurationSeconds is 15min/1hr. is returned?

This error is returned when the validity period of the temporary access credentials does not fall within the valid range. Specify the validity period based on the following rules:

  • If the default maximum session duration of the role (3,600 seconds) is used, the minimum validity period is 900 seconds and the maximum validity period is 3,600 seconds for the temporary access credentials.

  • If a custom maximum session duration is specified for the role, the minimum validity period is 900 seconds and the maximum validity period is the same as the specified maximum session duration. The maximum session duration of the role ranges from 3,600 to 43,200 seconds.

You can check the maximum session duration for the role in the RAM console. For more information, see View the information about a RAM role.

What do I do if the error message The security token you provided is invalid. is returned?

Make sure that you specify the security token obtained in Step 5.

Can I obtain multiple sets of temporary access credentials at the same time?

Yes, you can obtain multiple sets of temporary access credentials at the same time. You can obtain a set of temporary access credentials by sending a request to STS. If you want to obtain multiple sets of temporary access credentials from STS, send multiple requests to STS. You can simultaneously use multiple sets of temporary access credentials within the validity periods of the temporary access credentials.