You need to enable JavaScript to run this app.
Torch Object Storage

Torch Object Storage

Copy page
Download PDF
Granting temporary access
Accessing TOS with temporary credentials of Security Token Service
Copy page
Download PDF
Accessing TOS with temporary credentials of Security Token Service
You can use Security Token Service (STS) to generate temporary access credentials for users. These credentials limit access to TOS resources and expire after a set period. This topic describes how to use the temporary credentials of STS to access TOS.​
Use cases​
For security purposes, we recommend using temporary credentials instead of permanent ones in the client code when files are uploaded to TOS directly from mobile applications or PC clients. Specifically, the application server obtains the access key ID (AK) and secret access key (SK) via the STS mechanism and delivers the temporary credentials to the client. This solution has the following strengths:​
  • Temporary credentials become invalid upon expiration, protecting data security.​
  • You can restrict the permissions of temporary credentials to mitigate the risks associated with leakage, such as cracking or hijacking.​
Steps​
The steps are as follows.​
​​​
​
Step 1: Create an IAM user and grant it the STSAssumeRoleAccess permission​
This section describes how to create an IAM user, for example, tos_user, and grant it the permission.​
  1. Log in to the IAM console.​
  1. In the left navigation pane, select User management > User.​
  1. On the User page, click Create New User.​
  1. On the Create User page, choose your preferred method for creating a user.​
tip​
In this topic, the user is created by username. For more information on other methods, see Create user.​
  1. In the Basic information settings wizard, enter your username and other information. Then, check the box for Programmatic access and click Next.​
  1. In the Permission settings wizard, check the box for STSAssumeRoleAccess and click Next.​
tip​
This is a predefined system policy. You can search for and link it at the top of the pane.​
  1. In the Review wizard, verify your username and click Next.​
Step 2: Create an IAM role​
This section describes how to create an IAM role, for example, tos_role.​
  1. In the left navigation pane, click Role Management.​
  1. On the Role Management page, click Create New Role.​
  1. In the Create New Role panel, select Account under Select trust identity, and The current account under Select identity. Then, click Next.​
  1. In the Configure role wizard, enter your Role name and other information. Then, click Next.​
  1. In the Authorize wizard, click Skip.​
Step 3: Specify the user in the trust policy​
This section describes how to specify a user in the trust policy, for example, to change the user to tos_user.​
  1. On the Role Management page, click the role name created in Step 2.​
  1. On the Role detail page, click the Trust relationship tab.​
  1. On the Trust relationship tab, click Edit trust policy.​
  1. Replace the root user with the user created in Step 1 and click Save.​
  • Below is the sample trust policy.​
  • ​
    {​
    "Statement": [​
    {​
    "Effect": "Allow",​
    "Action": [​
    "sts:AssumeRole"​
    ],​
    "Principal": {​
    "IAM": [​
    "trn:iam::2100*****4:user/tos_user"​
    ]​
    }​
    }​
    ]​
    }​
    ​
tip​
The trust policy should be in the following format:​
  • The default trust policy is trn:iam::2100*****4:root. You need to replace root with the created IAM user, for example, trn:iam::2100*****4:user/tos_user.​
  • The trn user is in the format of trn:iam::{accountID}:user/{userName}, where {accountID} is the account ID of the role, and {userName} is the username.​
Step 4: Create an IAM policy​
Create an authorization policy based on your business scenario.​
  1. In the left navigation pane, click Permission policy.​
  1. On the Permission policy page, click Create Policy.​
  1. On the Create Policy page, enter your Policy name. Then, click the JSON editor tab and enter the policy content.​
  • This section describes how to grant the upload and download permissions for bucket tos-sts. Below is the sample policy.​
  • ​
    {​
    "Statement": [​
    {​
    "Effect": "Allow",​
    "Action": [​
    "tos:PutObject",​
    "tos:GetObject"​
    ],​
    "Resource": [​
    "trn:tos:::tos-sts/*"​
    ]​
    }​
    ]​
    }​
    ​
  • The parameters are described below.​
  • ​
    Parameter​
    Required​
    Description​
    Code block​
    Effect​
    Yes​
    Specifies whether to allow or deny an action. The options are:​
    • Allow​
    • Deny​
    ​
    "Effect": "Allow"​
    ​
    Action​
    Yes​
    Specifies the actions that the policy allows or denies. For a list of supported actions, see Actions supported by IAM policies.​
    • It is a case-insensitive string in the format of "Action":["tos:Action name"].​
    • Wildcards (*) are allowed, which indicates that all possible operations can be performed on the resource.​
    • For example, "Action":["tos:List*"] indicates that all the list actions can be performed on the resource.​
    ​
    "Action": ["tos:List*"]​
    ​
    Resource​
    No​
    Specifies the resources on which the specified operations can be performed. If this parameter is not specified, no resources can be manipulated.​
    • It is a case-insensitive string in the format of "Resource": ["trn:tos:::{BucketName}/{ObjectName}"].​
    • To manipulate a bucket, specify the bucket name only, for example, "Resource": ["trn:tos:::{BucketName}"].​
    • To manipulate objects in a bucket, specify the objects, for example, "Resource": ["trn:tos:::{BucketName}/{ObjectName}"].​
    • Wildcards (*) are allowed, which indicates that all resources will be manipulated.​
    ​
    "Resource": [​
    "trn:tos:::bucket/*",​
    "trn:tos:::bucket"​
    ]​
    ​
    ​
  1. Once you have finished configuring, click Submit.​
Step 5: Grant corresponding permissions to the role​
After creating the policy, grant policy permissions to the role created in Step 2.​
  1. On the Permission policy page, click the name of the policy you just created.​
  1. On the Policy detail page, click Authorize.​
  1. On the Authorize page, select the Role tab under Identity. Then, select the role created in Step 2 and click Submit.​
Step 6: Obtain the temporary credentials through the AssumeRole API​
warning​
  • The permissions of the temporary credentials are the intersection of the permissions of the role and the IAM policy.​
  • If no IAM policy is specified, the temporary credentials have the permissions of the prelinked policy of the specified role.​
  • If the role has no prelinked policy, the temporary credentials will have no permissions, even if the IAM policy is specified.​
Although some headers differ, Volcano Engine APIs use signature algorithms that are largely consistent with AWS Signature Version 4. For more information, see Signature Mechanism . You can call the AssumeRole API of STS to get temporary credentials. You can call this API through the following SDKs:​
Below are the complete request parameters.​
​
GET /?RoleTrn=trn:iam::2100****4:role/tos_role&RoleSessionName=tos_role_session&DurationSeconds=3600&Action=AssumeRole&Version=2018-01-01 HTTP/1.1​
Accept: application/json​
Content-Type: application/x-www-form-urlencoded​
Host: open.volcengineapi.com​
X-Date: Specify when making the request​
​
Authorization: To be signed (use the credentials of the IAM user tos_user here)​
​
tip​
When calling AssumeRole to obtain temporary access credentials, you can specify the duration of the credentials using the DurationSeconds parameter. For more information, see AssumeRole.​
Alternatively, you can calculate a signature and request temporary access credentials using the code examples provided below, which are illustrated in Python and Go.​
​
Go
Python
​
​
package main​
​
import (​
"crypto/hmac"​
"crypto/sha256"​
"encoding/hex"​
"fmt"​
"io/ioutil"​
"net/http"​
"net/url"​
"time"​
)​
​
func sign(key []byte, value string) []byte {​
h := hmac.New(sha256.New, key)​
h.Write([]byte(value))​
return h.Sum(nil)​
}​
​
func getSigningKey(key []byte, dateStamp string, regionName, serviceName string) []byte {​
kDate := sign(key, dateStamp)​
kRegion := sign(kDate, regionName)​
kService := sign(kRegion, serviceName)​
kSigning := sign(kService, "request")​
return kSigning​
}​
​
type SignHeaderInput struct {​
method string​
service string​
host string​
region string​
params url.Values​
accessKey string​
secretKey string​
}​
​
const (​
iso8601Layout = "20060102T150405Z"​
yyMMdd = "20060102"​
emptySHA256 = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"​
)​
​
func getSigningHeader(input SignHeaderInput) map[string]string {​
contentType := "application/x-www-form-urlencoded"​
accept := "application/json"​
t := time.Now().UTC()​
xdate := t.Format(iso8601Layout)​
datestamp := t.Format(yyMMdd)​
// ************* 1: Construct canonical request *************​
canonicalUri := "/"​
canonicalQueryString := input.params.Encode()​
canonicalHeaders := "content-type:" + contentType + "\\n" + "host:" + input.host + "\\n" + "x-date:" + xdate + "\\n"​
signedHeaders := "content-type;host;x-date"​
canonicalRequest := input.method + "\\n" + canonicalUri + "\\n" + canonicalQueryString + "\\n" + canonicalHeaders + "\\n" + signedHeaders + "\\n" + emptySHA256​
// ************* 2: Construct string to sign *************​
algorithm := "HMAC-SHA256"​
credentialScope := datestamp + "/" + input.region + "/" + input.service + "/" + "request"​
cr256 := sha256.Sum256([]byte(canonicalRequest))​
stringToSign := algorithm + "\\n" + xdate + "\\n" + credentialScope + "\\n" + hex.EncodeToString(cr256[:])​
​
// ************* 3: Calculate signature *************​
signingKey := getSigningKey([]byte(input.secretKey), datestamp, input.region, input.service)​
​
signature := sign(signingKey, stringToSign)​
// ************* 4: Add signature to request header *************​
authorizationHeader := algorithm + " " + "Credential=" + input.accessKey + "/" + credentialScope + ", " + "SignedHeaders=" + signedHeaders + ", " + "Signature=" + hex.EncodeToString(signature)​
​
headers := map[string]string{"Accept": accept, "Content-Type": contentType, "X-Date": xdate, "Authorization": authorizationHeader}​
return headers​
}​
​
func main() {​
service := "sts"​
host := "open.volcengineapi.com"​
endpoint := "https://open.volcengineapi.com"​
region := "{your region ID}"​
accessKey := "{your access key}"​
secretKey := "{your secret key}"​
queryParams := url.Values{"Action": []string{"AssumeRole"},​
"RoleSessionName": []string{"{your session name}"},​
"RoleTrn": []string{"trn:iam::{your account ID}:role/{your role name}"},​
"Version": []string{"2018-01-01"},​
​
}​
header := getSigningHeader(SignHeaderInput{​
method: http.MethodGet,​
service: service,​
host: host,​
region: region,​
params: queryParams,​
accessKey: accessKey,​
secretKey: secretKey,​
})​
req, err := http.NewRequest(http.MethodGet, endpoint+"?"+queryParams.Encode(), nil)​
if err != nil {​
panic(err)​
}​
for key, value := range header {​
req.Header.Set(key, value)​
}​
resp, err := http.DefaultClient.Do(req)​
if err != nil {​
panic(err)​
}​
defer resp.Body.Close()​
body, err := ioutil.ReadAll(resp.Body)​
if err != nil {​
panic(err)​
}​
fmt.Println(fmt.Sprintf("status code:%d, body: %s", resp.Status, string(body)))​
}​
​
​
The parameters are described below.​
​
Parameter​
Example value​
Description​
service​
sts​
Specifies the requested service, which is sts by default.​
host​
open.volcengineapi.com​
Specifies the request host, which is open.volcengineapi.com by default.​
endpoint​
https://open.volcengineapi.com​
Specifies the request endpoint, which is https://open.volcengineapi.com by default.​
tip​
To generate temporary access credentials for a private network, set the endpoint to a private network endpoint, such as https://tos-cn-beijing.ivolces.com.​
region​
cn-beijing​
Specifies the requested region. For more information on TOS regions, see Regions and endpoints.​
accessKey​
AKLTYTMyNTRlMTY5NmM0NDdiMjg3MmRlMzFl****NjU​
Specifies the AK of the user created in Step 1.​
secretKey​
TWpoaU9HRmlPV1ZrTURJNExxxxxx4WkRoaF****​
Specifies the SK of the user created in Step 1. For instructions on how to view the AK and SK, see Access Key Management​
action​
AssumeRole​
Specifies the API name, which is AssumeRole by default.​
RoleSessionName​
tos_role_session​
Specifies the temporary name of the request, which can be set as needed.​
RoleTrn​
trn:iam::2100xxxx4:role/tos_role​
Specifies the trn of the role created in Step 2 in the format of trn:iam::{accountID}:role/{roleName}.​
  • {accountID} is the account ID of the role.​
  • {roleName} is the role name.​
For example, the role created in this topic is tos_role, so the trn is trn:iam::2100xxxx4:role/tos_role.​
Version​
2018-01-01​
Specifies the request version, which is 2018-01-01 by default.​
​
Below is an example of a successful response.​
​
Response code: 200​
{​
"ResponseMetadata": {​
"RequestId": "20220626182126010212063166****",​
"Action": "AssumeRole",​
"Version": "2018-01-01",​
"Service": "sts"​
},​
"Result": {​
"Credentials": {​
"CurrentTime": "2022-06-26T18:21:27+08:00",​
"ExpiredTime": "2022-06-26T19:21:27+08:00",​
"AccessKeyId": "AKTPYmI1ZGQwMDA0NjlhNGFkMzhjNzM0N2Q0OTQ3ZTV****",​
"SecretAccessKey": "T1dJM01UUXpOak0wTVdWak5EUmtOR0poWldJNU1HWmxaV1V5TkdReVl6****",​
"SessionToken": "STSeyJBY2NvdW50SWQiOjIxMDAwMDUyMjQsIklkZW50aXR5VHlwZSI6NCwiSWRlbnRpdHlJZCI6MTE3MjI5NiwiQ2hhbm5lbCI6IlVzZXIiLCJBY2Nlc3NLZXlJZCI6IkFLVFBZbUkxWkdRd01EQTBOamxoTkdGa016aGpOek0wTjJRME9UUTNaVFZqTXpFIiwiU2lnbmVkU2VjcmV0QWNjZXNzS2V5IjoidVIvMmhvTE9Yd1lwNlR6QkxUOVZQVDQrbVVaQjMzMEJoQ0NPWk9JMVBRWkpZMFZPcGRPendybFNVYytGNlorRVR1ZDJsMlg0UkUyMWJEYnZ1QWl6S3c9PSIsIkV4cGlyZWRUaW1lIjoxNjU2MjQyNDg3LCJQb2xpY3lTdHJpbmciOiIiLCJTaWduYXR1cmUiOiIzOTlmMjZkNjIzZWUxMmU2NWViMDIwY2RlOWZkMDZkZDc4MTBkNjhkYjQyYzBjZTE3ZDA5MjY4NWYwMDQyYThlIiwiU2Vzc2lvbk5hbWUiOiJ0b3Nfcm9sZV9z************"​
},​
"AssumedRoleUser": {​
"Trn": "trn:sts::21000****4:assumed-role/tos_role/tos_role_session",​
"AssumedRoleId": "117****:tos_role_session"​
}​
}​
}​
​
Step 7: Use the temporary credentials to access TOS​
After obtaining the temporary credentials, you can access TOS with either TOS SDKs or AWS S3 SDKs. This section describes how to do so with the TOS Go SDK.​
tip​
  • For sample code to configure STS using TOS SDKs, see the following documents:​
​
package main​
​
import (​
"context"​
"fmt"​
"strings"​
​
"github.com/volcengine/ve-tos-golang-sdk/v2/tos"​
)​
​
func main() {​
// Enter the temporary AK/SK+Token obtained in the previous step​
ak := "AKTPYmI1ZGQwMDA0NjlhNGFkMzhjNzM0N2Q0OTQ3ZTV****"​
sk := "T1dJM01UUXpOak0wTVdWak5EUmtOR0poWldJNU1HWmxaV1V5TkdReVl6****"​
stToken := "STSeyJBY2NvdW50SWQiOjIxMDAwMDUyMjQsIklkZW50aXR5VHlwZSI6NCwiSWRlbnRpdHlJZCI6MTE3MjI5NiwiQ2hhbm5lbCI6IlVzZXIiLCJBY2Nlc3NLZXlJZCI6IkFLVFBZbUkxWkdRd01EQTBOamxoTkdGa016aGpOek0wTjJRME9UUTNaVFZqTXpFIiwiU2lnbmVkU2VjcmV0QWNjZXNzS2V5IjoidVIvMmhvTE9Yd1lwNlR6QkxUOVZQVDQrbVVaQjMzMEJoQ0NPWk9JMVBRWkpZMFZPcGRPendybFNVYytGNlorRVR1ZDJsMlg0UkUyMWJEYnZ1QWl6S3c9PSIsIkV4cGlyZWRUaW1lIjoxNjU2MjQyNDg3LCJQb2xpY3lTdHJpbmciOiIiLCJTaWduYXR1cmUiOiIzOTlmMjZkNjIzZWUxMmU2NWViMDIwY2RlOWZkMDZkZDc4MTBkNjhkYjQyYzBjZTE3ZDA5MjY4NWYwMDQyYThlIiwiU2Vzc2lvbk5hbWUiOiJ0b3Nfcm9sZV9z************"​
// Use TOS endpoint. For more information, see https://www.volcengine.com/docs/6349/107356​
endpoint := "https://tos-cn-beijing.volces.com"​
region := "cn-beijing"​
// Create a TosClient instance​
cred := tos.NewStaticCredentials(ak, sk)​
cred.WithSecurityToken(stToken)​
client, err := tos.NewClientV2(endpoint, tos.WithRegion(region), tos.WithCredentials(cred))​
if err != nil {​
panic(err)​
}​
res, err := client.PutObjectV2(context.Background(), &tos.PutObjectV2Input{PutObjectBasicInput: tos.PutObjectBasicInput{Bucket: "tos-sts", Key: "sts.txt"}, Content: strings.NewReader("hello STS")})​
​
if err != nil {​
panic(err)​
}​
fmt.Println(res)​
}​
​
​
Last updated: 2026.10.13 10:34:49