tencent cloud

Cloud Object Storage

Generating and Using Temporary Keys

Download
Mode fokus
Ukuran font
Terakhir diperbarui: 2026-07-15 11:21:48
A key is an identity authentication credential for making requests to COS, including temporary keys and permanent keys. Temporary keys are suitable for temporary authorization scenarios such as frontend direct upload. Permanent keys are suitable for trusted users and high-security scenarios. This document describes how to use temporary keys.

Introduction to Temporary Keys

Temporary keys (temporary access credentials) are keys with restricted permissions that are obtained through the interface provided by the CAM TencentCloud API. To initiate a COS API request, you need to use the TmpSecretId, TmpSecretKey, and Token fields from the information returned by the temporary key acquisition interface to calculate the signature. For details about temporary key permissions, see Accessing COS with Temporary Keys.
Attention:
When authorizing access with temporary keys, always grant permissions based on business needs and follow the principle of least privilege.
Granting permissions to all resources (resource:*) or all actions (action:*) directly poses a data security risk due to overly broad permission scopes.
When you apply for a temporary key and specify its action permission scope, the obtained temporary key can only be used within that scope. For example, if you specify a permission scope that allows uploading files to the bucket examplebucket-1-1250000000 when you apply for a temporary key, the obtained key cannot be used to upload files to examplebucket-2-1250000000, and cannot be used to download files from examplebucket-1-1250000000.
The API for generating temporary keys has a default request frequency limit of 600 requests per second.

Methods for Generating Temporary Keys

During the temporary key application process, you can restrict operations and resources by configuring the policy field of the permission policy, thereby limiting permissions to a specified scope.
For COS API authorization policies, see:
Temporary keys are generated in the following two ways:
Method 1: COS STS SDK, which is suitable for development language scenarios.
Method 2: STS TencentCloud API, which is suitable for users to generate keys more conveniently and quickly.

Method 1: COS STS SDK

COS provides SDKs and samples for STS, with samples currently available in multiple languages such as Java, Node.js, PHP, Python, and Go. You can obtain temporary keys via the provided COS STS SDK method. For usage instructions of each SDK, see the README and samples on GitHub. The GitHub addresses for each language are listed in the following table:
Attention:
The STS SDK returns a parameter structure that may not be completely consistent with the STS API, in order to mask differences between versions of the STS API itself. For details, see the Java SDK documentation.

Method 2: STS TencentCloud API

Obtain temporary keys via the STS TencentCloud API. For request parameters, see Obtain Federated Identity Temporary Access Credentials. Example parameters are as follows:
Input parameters
Reference Value
Description
Required
Region
North China (Beijing) ap-beijing
The region to which the operated resources belong is Beijing.
Yes
Name
test
The English name of the custom caller is test.
Yes
Policy
{"version":"2.0","statement":[{"effect":"allow","action":["name/cos:PutObject","name/cos:DeleteObject"],"resource":"*"}]}
Describe the policy syntax version as "2.0".
The effect of the described statement is "allow".
The allowed operations are described as "name/cos:PutObject" (upload object) and "name/cos:DeleteObject" (delete object). For more APIs, see CAM-Supported COS Business APIs.
Describe the specific data resource for authorization, granting operational permissions for all resources of the action.
Yes
DurationSeconds
3600
Specifies the validity period of the temporary key as 3600 seconds. If not specified, the default is 1800 seconds.
No
After selecting or entering reference values in the input parameters, click Initiate Request to obtain TmpSecretId, TmpSecretKey, and Token.


Sample Code for Generating Temporary Keys

Assuming you are using the Java SDK, first download the Java SDK, and then run the following code to obtain a temporary key sample:
Import the java sts sdk using the maven integration method provided on github, and use version 3.1.1 or higher.

import java.util.TreeMap;
import com.tencent.cloud.CosStsClient;
import com.tencent.cloud.Policy;
import com.tencent.cloud.Response;
import com.tencent.cloud.Statement;
import com.tencent.cloud.cos.util.Jackson;

public class demo {
public static void main(String[] args) {
TreeMap<String, Object> config = new TreeMap<String, Object>();
try {
The SecretId and SecretKey here represent the permanent identity (such as a root account or sub-account) used to apply for temporary keys. The sub-account must have permissions to operate the bucket.
String secretId = System.getenv("secretId"); // The user's SecretId. It is recommended to use a sub-account key, follow the principle of least privilege for authorization, and reduce usage risks. For information on obtaining sub-account keys, see https://www.tencentcloud.com/document/product/598/32675.
String secretKey = System.getenv("secretKey"); // The user's SecretKey. It is recommended to use a sub-account key, follow the principle of least privilege for authorization, and reduce usage risks. For information on obtaining sub-account keys, see https://www.tencentcloud.com/document/product/598/32675.
// Replace with your TencentCloud api key SecretId
config.put("secretId", secretId);
// Replace with your TencentCloud api key SecretKey
config.put("secretKey", secretKey);

// Initialize the policy
Policy policy = new Policy();

// Set the domain name:
// If you are using Tencent Cloud cvm, you can set an internal domain name.
//config.put("host", "sts.internal.tencentcloudapi.com");

// The validity period of a temporary key, measured in seconds, defaults to 1800 seconds. Currently, the maximum duration is 2 hours (7200 seconds) for a root account and 36 hours (129600 seconds) for a sub-account.
config.put("durationSeconds", 1800);
// Replace with your bucket
config.put("bucket", "examplebucket-1250000000");
// Replace with the region where your bucket is located
config.put("region", "ap-chongqing");

// Start building a statement
Statement statement = new Statement();
// The result of the declaration setting is to allow the operation.
statement.setEffect("allow");
/**
* Permissions list for the key. You must specify the permissions required for this temporary key here.
* For the permissions list, see https://www.tencentcloud.com/document/product/436/30580.
* The rule is {project}:{interfaceName}
* project: Product abbreviation. For COS-related authorizations, the value is `cos`. For CI (data processing)-related authorizations, the value is `ci`.
* To authorize all APIs, use an asterisk (*), for example, `cos:*` and `ci:*`.
* Add a batch of operation permissions:
*/
statement.addActions(new String[]{
"cos:PutObject",
// Form upload, Mini Program upload
"cos:PostObject",
// Multipart upload
"cos:InitiateMultipartUpload",
"cos:ListMultipartUploads",
"cos:ListParts",
"cos:UploadPart",
"cos:CompleteMultipartUpload",
// Processing-related APIs are generally part of the CI product, and their permissions start with `ci`.
// Create an MPS task
"ci:CreateMediaJobs",
// File compression
"ci:CreateFileProcessJobs"
});

/**
* Change this to the allowed path prefix. You can determine the specific upload paths allowed based on your website's user login status.
* Resource expression rules are categorized into two types: cos (object storage) and ci (data processing).
* APIs related to data processing and review require ci resource permissions.
* cos : qcs::cos:{region}:uid/{appid}:{bucket}/{path}
* ci : qcs::ci:{region}:uid/{appid}:bucket/{bucket}/{path}
* List several typical {path} authorization scenarios:
* 1. Allow access to all objects: "*"
* 2. Allow access to specified objects: "a/a1.txt", "b/b1.txt"
* 3. Allow access to objects with specified prefixes: "a*", "a/*", "b/*"
* Specifying "*" grants users access to all resources. Unless required by business needs, follow the principle of least privilege to grant users the appropriate scope of access permissions.
*
* Example: Grant all resources under the examplebucket-1250000000 bucket directory to cos and ci. Authorize two Resources.
*/
statement.addResources(new String[]{
"qcs::cos:ap-chongqing:uid/1250000000:examplebucket-1250000000/*",
"qcs::ci:ap-chongqing:uid/1250000000:bucket/examplebucket-1250000000/*"});

// Add a statement to the policy
// Multiple entries can be added.
policy.addStatement(statement);
// To convert a Policy example into a String, you can use any json conversion method. The method described here is the recommended one provided by this SDK.
config.put("policy", Jackson.toJsonPrettyString(policy));

Response response = CosStsClient.getCredential(config);
System.out.println(response.credentials.tmpSecretId);
System.out.println(response.credentials.tmpSecretKey);
System.out.println(response.credentials.sessionToken);
} catch (Exception e) {
e.printStackTrace();
throw new IllegalArgumentException("no valid secret !");
}
}
}
The configuration parameters are described as follows:
Field
Reference Value
Description
Required
secretId
Use the actually obtained SecretId as the reference.
For obtaining sub-account keys, see Sub-account Access Key Management.
Yes
secretKey
Use the actually obtained SecretKey as the reference.
For obtaining sub-account keys, see Sub-account Access Key Management.
Yes
durationSeconds
1800
Specifies the validity period of the temporary key as 1800 seconds.
No
bucket
examplebucket-1250000000
Use the actual bucket name.
Yes
region
ap-guangzhou
Use the actual region of the bucket.
Yes
allowPrefixes
"*"
Allows access to all objects. Unless required by business needs, grant users the corresponding scope of access permissions according to the principle of least privilege.
Yes
allowActions
"cos:PutObject",
"cos:PostObject",
"cos:InitiateMultipartUpload",
"cos:ListMultipartUploads",
"cos:ListParts",
"cos:UploadPart",
"cos:CompleteMultipartUpload",
// Processing-related APIs are generally part of the CI product, and their permissions start with "ci".
"ci:CreateMediaJobs",
"ci:CreateFileProcessJobs"
PutObject: Upload object
PostObject: Upload object via form
InitiateMultipartUpload: Initialize a multipart upload task
ListMultipartUploads: Query multipart upload tasks
ListParts: Query uploaded parts
UploadPart: Upload object parts
CompleteMultipartUpload: Complete a multipart upload task
CreateMediaJobs: Create MPS jobs
CreateFileProcessJobs: File compression
For more APIs, see cos action and CI action.
Yes

Use Case: Accessing COS with Temporary Keys

When accessing COS services with temporary keys via the COS API, pass the temporary sessionToken through the x-cos-security-token field and calculate the signature using the temporary SecretId and SecretKey.
Using the COS Java SDK as an example, the following sample demonstrates how to access COS with temporary keys:
Note:
Before running the following example, go to the GitHub project to obtain the cos-java-sdk-v5 installation package.
Import the cos xml java sdk using the maven integration method provided on github.

import com.qcloud.cos.COSClient; import com.qcloud.cos.ClientConfig; import com.qcloud.cos.auth.BasicSessionCredentials; import com.qcloud.cos.auth.COSCredentials; import com.qcloud.cos.exception.CosClientException; import com.qcloud.cos.exception.CosServiceException; import com.qcloud.cos.model.ObjectMetadata; import com.qcloud.cos.model.PutObjectRequest; import com.qcloud.cos.model.PutObjectResult; import com.qcloud.cos.region.Region; import java.io.File;
public class Demo {
public static void main(String[] args) throws Exception {

// Basic user information
String tmpSecretId = "COS_SECRETID"; // Replace with the temporary SecretId returned by the STS API
String tmpSecretKey = "COS_SECRETKEY"; // Replace with the temporary SecretKey returned by the STS API
String sessionToken = "Token"; // Replace with the temporary Token returned by the STS API

// 1 Initializing user identity information (secretId, secretKey)
COSCredentials cred = new BasicSessionCredentials(tmpSecretId, tmpSecretKey, sessionToken);
// 2 Set the bucket region. For details, see COS Regions at https://www.tencentcloud.com/document/product/436/6224?from_cn_redirect=1.
ClientConfig clientConfig = new ClientConfig(new Region("ap-guangzhou"));
// 3 Generating a COS client
COSClient cosclient = new COSClient(cred, clientConfig);
// The bucket name must contain appid
String bucketName = "examplebucket-1250000000";

String key = "exampleobject";
// Upload object. It is recommended to use this interface for files smaller than 20 M.
File localFile = new File("src/test/resources/text.txt");
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, localFile);

// Set the x-cos-security-token header field
ObjectMetadata objectMetadata = new ObjectMetadata();
objectMetadata.setSecurityToken(sessionToken);
putObjectRequest.setMetadata(objectMetadata);

try {
PutObjectResult putObjectResult = cosclient.putObject(putObjectRequest);
// Success: putobjectResult returns the file's etag.
String etag = putObjectResult.getETag();
} catch (CosServiceException e) {
// Failure: a CosServiceException is thrown.
e.printStackTrace();
} catch (CosClientException e) {
// Failure: a CosClientException is thrown.
e.printStackTrace();
}

// Disable the client.
cosclient.shutdown();

}
}
The configuration parameters are described as follows:
Field
Reference Value
Description
COS_SECRETID
Use the actually obtained SecretId as the reference.
Replace it with the temporary SecretId returned to you by the STS API.
COS_SECRETKEY
Use the actually obtained SecretKey as the reference.
Replace it with the temporary SecretKey returned to you by the STS API.
Token
Use the actually obtained Token as the reference.
Replace it with the temporary Token returned to you by the STS API.
new Region
ap-guangzhou
Use the actual region of the bucket.
bucketName
examplebucket-1250000000
Use the actual bucket name.
key
exampleobject
For example, /test/demo.txt. The uploaded object will be located in /test and named demo.txt.
new File
src/test/resources/text.txt
The local path of the object to be uploaded is src/test/resources/, the file name is test, and the format is txt.

FAQs

JSONObject Package Conflict Causing NoSuchMethodError?

A: Use version 3.1.0 or later.

Bantuan dan Dukungan

Apakah halaman ini membantu?

masukan