Programming Language | Installation URL | Sample Code URL |
Java | ||
.NET | ||
Go | ||
Node.js | ||
PHP | ||
Python |
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 |
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 SecretIdconfig.put("secretId", secretId);// Replace with your TencentCloud api key SecretKeyconfig.put("secretKey", secretKey);// Initialize the policyPolicy 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 bucketconfig.put("bucket", "examplebucket-1250000000");// Replace with the region where your bucket is locatedconfig.put("region", "ap-chongqing");// Start building a statementStatement 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 !");}}}
Field | Reference Value | Description | Required |
secretId | Use the actually obtained SecretId as the reference. | Yes | |
secretKey | Use the actually obtained SecretKey as the reference. | 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 | Yes |
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 informationString tmpSecretId = "COS_SECRETID"; // Replace with the temporary SecretId returned by the STS APIString tmpSecretKey = "COS_SECRETKEY"; // Replace with the temporary SecretKey returned by the STS APIString 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 clientCOSClient cosclient = new COSClient(cred, clientConfig);// The bucket name must contain appidString 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 fieldObjectMetadata 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();}}
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. |
Apakah halaman ini membantu?
Anda juga dapat Menghubungi Penjualan atau Mengirimkan Tiket untuk meminta bantuan.
masukan