使用STS临时访问凭证访问OSS

更新时间:
复制 MD 格式

STS lets you generate temporary credentials to access policy-restricted OSS resources. These credentials automatically expire after a defined period, providing flexible and time-bound access control.

Video tutorial

Watch the following video to learn how to quickly use temporary credentials from STS to access OSS.

Use case

An e-commerce company, Company A, stores large amounts of product data in OSS. A supplier, Company B, needs to regularly upload data to Company A's OSS bucket and integrate with Company A's Alibaba Cloud resources from its own system.

Company A has the following security requirements:

  • Data security: Company A does not want to expose its permanent AccessKey pair to Company B, to prevent unauthorized access to its core data.

  • Permission control: Company A wants to grant Company B only upload permissions and be able to adjust them later for more precise access control.

  • Permission management: Company A needs to generate unique credentials for different partners or temporary requirements without having to manage and configure multiple permanent AccessKey pairs.

  • Time-limited access control: Company A wants to limit the validity of Company B's access credentials based on specific needs. When the credentials expire, access is automatically revoked, providing strict, time-based control over data access.

How it works

Company A uses temporary credentials to authorize Company B to securely upload files to OSS.

image

First, Company A creates a RAM user and a RAM role and grants them the necessary permissions. Company A calls the AssumeRole operation to obtain temporary credentials from STS and sends the credentials to Company B. Company B can then use these credentials to upload data to Company A's OSS bucket.

Prerequisites

Company A must have an existing bucket. For more information, see Create buckets.

Step 1: Company A issues temporary credentials

1. Create a RAM user

Use your Alibaba Cloud account or a RAM user with RAM administrative permissions to create a RAM user.

  1. Log on to the RAM console.

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

  3. Click Create User.

  4. Enter a Logon Name and Display Name.

  5. In the Access Mode section, select Using permanent AccessKey to access and then click OK.

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

  7. Copy the AccessKey ID and AccessKey secret.

    Important

    The AccessKey secret for a RAM user is displayed only when the user is created and cannot be retrieved later. We strongly recommend that you download the CSV file containing the AccessKey pair and store it in a secure location.

    image

2. Grant AssumeRole permission

After you create the RAM user, use your Alibaba Cloud account or a RAM user with RAM administrative permissions to grant the RAM user permission to call the AssumeRole operation.

  1. Log on to the RAM console.

  2. In the left-side navigation pane, choose Identities > Users. Find the RAM user that you created and click Add Permissions in the Actions column.

  3. On the Grant Permission page, select the AliyunSTSAssumeRoleAccess system policy.

    Note

    The fixed permission that allows a RAM user to call the AssumeRole API of STS is AliyunSTSAssumeRoleAccess, which is separate from the permissions required to obtain temporary credentials or make OSS requests with them.

    image

  4. Click Grant permissions.

3. Create a RAM role

Create a RAM role by using your Alibaba Cloud account or a RAM user with RAM administrative permissions. This role defines the OSS access permissions that its temporary credentials will have.

  1. Log on to the RAM console.

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

  3. On the Roles page, click Create Role.

  4. On the Create Role page, select Cloud Account as the Principal Type, select Current Account as the Principal Name, and then click OK.

    image

  5. In the Create Role dialog box, enter a role name, and then click OK.

  6. Click Copy next to the ARN and save the role's ARN.

    image

4. Grant file upload permissions

After you create the RAM role, attach one or more policies to it by using your Alibaba Cloud account or a RAM user with RAM administrative permissions. These policies define the permissions for accessing OSS resources. For example, to allow anyone assuming this role to upload files only to a specific bucket, you must add a policy with write permissions to the role.

  1. Create a custom policy for file uploads.

    1. Log on to the RAM console.

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

    3. On the Policies page, click Create Policy.

    4. On the Create Policy page, click the JSON tab. In the policy editor, grant the role the permission to upload files to examplebucket. The following code provides an example:

      Warning

      The following sample policy is for reference only. Configure a more fine-grained policy based on your needs to avoid granting excessive permissions. For more information about how to configure fine-grained policies, see Authorize other users by using RAM or STS.

      {
          "Version": "1",
          "Statement": [
           {
                 "Effect": "Allow",
                 "Action": [
                   "oss:PutObject"
                 ],
                 "Resource": [
                   "acs:oss:*:*:examplebucket/*"             
                 ]
           }
          ]
      }
      Note

      The OSS permissions of a RAM role depend on the Action configuration. For example, if the oss:PutObject permission is granted, a RAM user that assumes the RAM role can perform operations such as simple upload, form upload, append upload, multipart upload, and resumable upload on the specified bucket. For more information, see OSS Action reference.

    5. After you configure the policy, click OK. In the Create Policy dialog box, enter a name for the policy, such as RamTestPolicy. Verify the information and click OK again.

  2. Grant the custom policy to the RAM role RamOssTest.

    1. Log on to the RAM console.

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

    3. On the Roles page, find the target RAM role RamOssTest.

    4. Click Grant Permission in the Actions column for the RAM role RamOssTest.

    5. On the Grant Permission page, in the Policies section, select Custom Policy as the policy type. Then, select the custom policy RamTestPolicy from the policy list.

    6. Click Grant permissions.

5. Obtain temporary credentials

Important

You must use a RAM user's AccessKey pair, not an Alibaba Cloud account's, to call STS API operations. Using an account's AccessKey pair will cause an error. The following examples use a RAM user's credentials.

  • The following examples use an STS SDK to obtain temporary credentials that have oss:PutObject (simple upload) permission. For more STS SDK examples in other languages, see STS SDK overview.

  • For faster STS responses, select an endpoint in the same region as your server, or a nearby one. For more information about STS endpoints, see Endpoints.

Java

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.aliyuncs.auth.sts.AssumeRoleRequest;
import com.aliyuncs.auth.sts.AssumeRoleResponse;
public class StsServiceSample {
    public static void main(String[] args) { 
        // The STS endpoint. Example: sts.cn-hangzhou.aliyuncs.com. You can access STS over the public internet or a VPC.       
        String endpoint = "sts.cn-hangzhou.aliyuncs.com";
        // Obtain the AccessKey ID and AccessKey secret of the RAM user created in Step 1.1 from environment variables.
        String accessKeyId = System.getenv("ACCESS_KEY_ID");
        String accessKeySecret = System.getenv("ACCESS_KEY_SECRET");
        // Obtain the ARN of the RAM role created in Step 1.3 from environment variables.
        String roleArn = System.getenv("RAM_ROLE_ARN");
        // Specify a custom role session name to distinguish different tokens. Example: SessionTest.        
        String roleSessionName = "yourRoleSessionName";   
        // By default, the temporary credentials have all the permissions granted to the role.      
        String policy = null;
        // The validity period of the temporary credentials, in seconds. Minimum value: 900. Maximum value: the maximum session duration of the current role. The maximum session duration of the current role can be 3,600 seconds to 43,200 seconds. The default value is 3,600 seconds.
        // For time-consuming operations like large file uploads, set a longer duration to avoid re-fetching credentials.
        Long durationSeconds = 3600L;
        try {
            // The region where the STS request is initiated. We recommend that you keep the default value, which is an empty string ("").
            String regionId = "";
            // Add an endpoint. This is applicable to Java SDK 3.12.0 and later.
            DefaultProfile.addEndpoint(regionId, "Sts", endpoint);
            // Add an endpoint. This is applicable to Java SDK versions earlier than 3.12.0.
            // DefaultProfile.addEndpoint("",regionId, "Sts", endpoint);
            // Construct a default profile.
            IClientProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret);
            // Construct a client.
            DefaultAcsClient client = new DefaultAcsClient(profile);
            final AssumeRoleRequest request = new AssumeRoleRequest();
            // This is applicable to Java SDK 3.12.0 and later.
            request.setSysMethod(MethodType.POST);
            // This is applicable to Java SDK versions earlier than 3.12.0.
            // request.setMethod(MethodType.POST);
            request.setRoleArn(roleArn);
            request.setRoleSessionName(roleSessionName);
            request.setPolicy(policy); 
            request.setDurationSeconds(durationSeconds); 
            final AssumeRoleResponse response = client.getAcsResponse(request);
            System.out.println("Expiration: " + response.getCredentials().getExpiration());
            System.out.println("Access Key Id: " + response.getCredentials().getAccessKeyId());
            System.out.println("Access Key Secret: " + response.getCredentials().getAccessKeySecret());
            System.out.println("Security Token: " + response.getCredentials().getSecurityToken());
            System.out.println("RequestId: " + response.getRequestId());
        } catch (ClientException e) {
            System.out.println("Failed:");
            System.out.println("Error code: " + e.getErrCode());
            System.out.println("Error message: " + e.getErrMsg());
            System.out.println("RequestId: " + e.getRequestId());
        }
    }
}

Python

# -*- coding: utf-8 -*-

from aliyunsdkcore import client
from aliyunsdkcore.request import CommonRequest
import json
import oss2
import os

# Obtain the AccessKey ID and AccessKey secret of the RAM user created in Step 1.1 from environment variables.
access_key_id = os.getenv("ACCESS_KEY_ID")
access_key_secret = os.getenv("ACCESS_KEY_SECRET")
# Obtain the ARN of the RAM role created in Step 1.3 from environment variables.
role_arn = os.getenv("RAM_ROLE_ARN")

# Create a client.
clt = client.AcsClient(access_key_id, access_key_secret, 'cn-hangzhou')
request = CommonRequest(product="Sts", version='2015-04-01', action_name='AssumeRole')
request.set_method('POST')
request.set_protocol_type('https')
request.add_query_param('RoleArn', role_arn)
# Specify a custom role session name to distinguish different tokens. Example: sessiontest.
request.add_query_param('RoleSessionName', 'sessiontest')
# Specify that the STS temporary credentials expire in 3,600 seconds.
request.add_query_param('DurationSeconds', '3600')
request.set_accept_format('JSON')

body = clt.do_action_with_exception(request)

# Use the AccessKey pair of the RAM user to request temporary credentials from STS.
token = json.loads(oss2.to_unicode(body))
# Print the temporary AccessKey ID, AccessKey secret, security token, and expiration time returned by STS.
print('AccessKeyId: ' + token['Credentials']['AccessKeyId'])
print('AccessKeySecret: ' + token['Credentials']['AccessKeySecret'])
print('SecurityToken: ' + token['Credentials']['SecurityToken'])
print('Expiration: ' + token['Credentials']['Expiration'])

Node.js

const { STS } = require('ali-oss');
const express = require("express");
const app = express();

app.get('/sts', (req, res) => {
 let sts = new STS({
  // Obtain the AccessKey ID and AccessKey secret of the RAM user created in Step 1.1 from environment variables.
   accessKeyId : process.env.ACCESS_KEY_ID,
   accessKeySecret : process.env.ACCESS_KEY_SECRET
});
  // process.env.RAM_ROLE_ARN is the ARN of the RAM role created in Step 1.3, obtained from an environment variable.
  // Specify a custom policy to further restrict the permissions of the STS temporary credentials. If you do not specify a policy, the returned credentials have all the permissions granted to the specified role.
  // The final permissions of the temporary credentials are the intersection of the role permissions set in Step 4 and the permissions set in this policy.
  // The expiration parameter specifies the validity period of the temporary credentials in seconds. The minimum value is 900, and the maximum value is the maximum session duration of the current role. This example sets the validity period to 3,600 seconds.
  // The sessionName parameter specifies a custom role session name to distinguish different tokens. Example: sessiontest.
  sts.assumeRole('process.env.RAM_ROLE_ARN', ``, '3600', 'sessiontest').then((result) => {
    console.log(result);
    res.set('Access-Control-Allow-Origin', '*');
    res.set('Access-Control-Allow-METHOD', 'GET');
    res.json({
      AccessKeyId: result.credentials.AccessKeyId,
      AccessKeySecret: result.credentials.AccessKeySecret,
      SecurityToken: result.credentials.SecurityToken,
      Expiration: result.credentials.Expiration
    });
  }).catch((err) => {
    console.log(err);
    res.status(400).json(err.message);
  });
});
app.listen(8000,()=>{
   console.log("server listen on:8000")
})

Go

package main

import (
    "fmt"
    "os"

    openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
    sts20150401 "github.com/alibabacloud-go/sts-20150401/v2/client"
    util "github.com/alibabacloud-go/tea-utils/v2/service"
    "github.com/alibabacloud-go/tea/tea"
)

func main() {
    // Obtain the AccessKey ID and AccessKey secret of the RAM user created in Step 1.1 from environment variables.
    accessKeyId := os.Getenv("ACCESS_KEY_ID")
    accessKeySecret := os.Getenv("ACCESS_KEY_SECRET")
    // Obtain the ARN of the RAM role created in Step 1.3 from an environment variable.
    roleArn := os.Getenv("RAM_ROLE_ARN")

    // Create a client.
    config := &openapi.Config{
        // Required. The AccessKey ID obtained in Step 1.1.
        AccessKeyId: tea.String(accessKeyId),
        // Required. The AccessKey secret obtained in Step 1.1.
        AccessKeySecret: tea.String(accessKeySecret),
    }
    // For more information about endpoints, see https://api.aliyun.com/product/Sts.
    config.Endpoint = tea.String("sts.cn-hangzhou.aliyuncs.com")
    client, err := sts20150401.NewClient(config)
    if err != nil {
        fmt.Printf("Failed to create client: %v\n", err)
        return
    }

    // Use the AccessKey pair of the RAM user to request temporary credentials from STS.
    request := &sts20150401.AssumeRoleRequest{
        // Specify that the STS temporary credentials expire in 3,600 seconds.
        DurationSeconds: tea.Int64(3600),
        // Obtain the ARN of the RAM role created in Step 1.3 from an environment variable.
        RoleArn: tea.String(roleArn),
        // Specify a custom role session name. This example uses examplename.
        RoleSessionName: tea.String("examplename"),
    }
    response, err := client.AssumeRoleWithOptions(request, &util.RuntimeOptions{})
    if err != nil {
        fmt.Printf("Failed to assume role: %v\n", err)
        return
    }

    // Print the temporary AccessKey ID, AccessKey secret, security token, and expiration time returned by STS.
    credentials := response.Body.Credentials
    fmt.Println("AccessKeyId: " + tea.StringValue(credentials.AccessKeyId))
    fmt.Println("AccessKeySecret: " + tea.StringValue(credentials.AccessKeySecret))
    fmt.Println("SecurityToken: " + tea.StringValue(credentials.SecurityToken))
    fmt.Println("Expiration: " + tea.StringValue(credentials.Expiration))
}

PHP

<?php
require __DIR__ . '/vendor/autoload.php';

use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use AlibabaCloud\Sts\Sts;

// Obtain the AccessKey ID and AccessKey secret of the RAM user created in Step 1.1 from environment variables.
$accessKeyId = getenv("ACCESS_KEY_ID");
$accessKeySecret = getenv("ACCESS_KEY_SECRET");
// Obtain the ARN of the RAM role created in Step 1.3 from an environment variable.
$roleArn = getenv("RAM_ROLE_ARN");

// Initialize the Alibaba Cloud client.
AlibabaCloud::accessKeyClient($accessKeyId, $accessKeySecret)
    ->regionId('cn-hangzhou')
    ->asDefaultClient();

try {
    // Create an STS request.
    $result = Sts::v20150401()
        ->assumeRole()
        // Set the role ARN.
        ->withRoleArn($roleArn)
        // Specify a custom role session name to distinguish different tokens.
        ->withRoleSessionName('sessiontest')
        // Specify that the STS temporary credentials expire in 3,600 seconds.
        ->withDurationSeconds(3600)
        ->request();

    // Get the credential information from the response.
    $credentials = $result['Credentials'];

    // Print the temporary AccessKey ID, AccessKey secret, security token, and expiration time returned by STS.
    echo 'AccessKeyId: ' . $credentials['AccessKeyId'] . PHP_EOL;
    echo 'AccessKeySecret: ' . $credentials['AccessKeySecret'] . PHP_EOL;
    echo 'SecurityToken: ' . $credentials['SecurityToken'] . PHP_EOL;
    echo 'Expiration: ' . $credentials['Expiration'] . PHP_EOL;
} catch (ClientException $e) {
    // Handle client exceptions.
    echo $e->getErrorMessage() . PHP_EOL;
} catch (ServerException $e) {
    // Handle server exceptions.
    echo $e->getErrorMessage() . PHP_EOL;
}

Ruby

require 'sinatra'
require 'base64'
require 'open-uri'
require 'cgi'
require 'openssl'
require 'json'
require 'sinatra/reloader'
require 'sinatra/content_for'
require 'aliyunsdkcore'

# Set the path of the public folder to the templates folder in the current directory.
set :public_folder, File.dirname(__FILE__) + '/templates'

def get_sts_token_for_oss_upload()
  client = RPCClient.new(
    # Obtain the AccessKey ID and AccessKey secret of the RAM user created in Step 1.1 from environment variables.
    access_key_id: ENV['ACCESS_KEY_ID'],
    access_key_secret: ENV['ACCESS_KEY_SECRET'],
    endpoint: 'https://sts.cn-hangzhou.aliyuncs.com',
    api_version: '2015-04-01'
  )
  response = client.request(
    action: 'AssumeRole',
    params: {
      # Obtain the ARN of the RAM role created in Step 1.3 from an environment variable.
      "RoleArn": ENV['RAM_ROLE_ARN'],
      # Specify that the STS temporary credentials expire in 3,600 seconds.
      "DurationSeconds": 3600,
      # The sessionName parameter specifies a custom role session name to distinguish different tokens. Example: sessiontest.
      "RoleSessionName": "sessiontest"
    },
    opts: {
      method: 'POST',
      format_params: true
    }
  )
end

if ARGV.length == 1 
  $server_port = ARGV[0]
elsif ARGV.length == 2
  $server_ip = ARGV[0]
  $server_port = ARGV[1]
end

$server_ip = "127.0.0.1"  # If you need to listen on another address, such as 0.0.0.0, you must add an authentication mechanism on the server.
$server_port = 8000

puts "App server is running on: http://#{$server_ip}:#{$server_port}"

set :bind, $server_ip
set :port, $server_port

get '/get_sts_token_for_oss_upload' do
  token = get_sts_token_for_oss_upload()
  response = {
    "AccessKeyId" => token["Credentials"]["AccessKeyId"],
    "AccessKeySecret" => token["Credentials"]["AccessKeySecret"],
    "SecurityToken" => token["Credentials"]["SecurityToken"],
    "Expiration" => token["Credentials"]["Expiration"]
  }
  response.to_json
end

get '/*' do
  puts "********************* GET "
  send_file File.join(settings.public_folder, 'index.html')
end
  • Example of obtained STS temporary credentials:

    Note
    • The STS call rate for an Alibaba Cloud account, including all its RAM users and roles, is limited to 100 requests per second. In high-concurrency scenarios, reuse temporary credentials until they expire.

    • The expiration time of STS temporary credentials is in Coordinated Universal Time (UTC). For example, an expiration time of 2024-04-18T11:33:40Z corresponds to 19:33:40 on April 18, 2024, in the UTC+8 time zone.

    {
      "AccessKeyId": "STS.****************",
      "AccessKeySecret": "3dZn*******************************************",
      "SecurityToken": "CAIS*****************************************************************************************************************************************",
      "Expiration": "2024-**-*****:**:50Z"
    }
  • How to configure fine-grained temporary access permissions

    If you want to further restrict the permissions granted by the role, you can provide an inline policy when calling AssumeRole. The temporary credentials will then have permissions that are the intersection of the role's policies and the inline policy. For example, if a role has permission to upload files to examplebucket, you can use an inline policy to restrict the temporary credentials to allow uploads only to a specific directory within that bucket.

    // The following policy allows uploads only to the src directory in the examplebucket bucket.
    // The final permissions of the temporary credentials are the intersection of the role permissions set in Step 4 and the permissions set in this policy, which means that files can be uploaded only to the src directory in examplebucket.      
    String policy = "{\n" +
                    "    \"Version\": \"1\", \n" +
                    "    \"Statement\": [\n" +
                    "        {\n" +
                    "            \"Action\": [\n" +
                    "                \"oss:PutObject\"\n" +
                    "            ], \n" +
                    "            \"Resource\": [\n" +
                    "                \"acs:oss:*:*:examplebucket/src/*\" \n" +
                    "            ], \n" +
                    "            \"Effect\": \"Allow\"\n" +
                    "        }\n" +
                    "    ]\n" +
                    "}";

Step 2: Company B uploads a file to OSS using temporary credentials

The following examples show how to upload a file to OSS using temporary credentials before they expire. For SDK installation guides and code examples in various programming languages, see SDK Reference.

Java

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.CredentialsProvider;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;

import java.io.File;

public class Demo {

    public static void main(String[] args) throws Exception {
        // Enter the temporary AccessKey ID, AccessKey Secret, and security token generated in Step 1.5. Do not use the credentials of the RAM user.
        // Note that the AccessKey ID obtained from STS starts with "STS".
        String accessKeyId = "yourSTSAccessKeyID";
        String accessKeySecret = "yourSTSAccessKeySecret";
        // Enter the obtained STS security token.
        String stsToken= "yourSecurityToken";

        // Use the DefaultCredentialProvider method to directly set the AccessKey ID and AccessKey Secret.
        CredentialsProvider credentialsProvider = new DefaultCredentialProvider(accessKeyId, accessKeySecret, stsToken);
        // Use credentialsProvider to initialize the client.
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        // Explicitly declare the use of the V4 signature algorithm.
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        // Create an OSSClient instance.
        // When the OSSClient instance is no longer needed, call the shutdown method to release resources.
        OSS ossClient = OSSClientBuilder.create()
                 // Set the endpoint of the destination OSS. For example, for the China (Hangzhou) region: https://oss-cn-hangzhou.aliyuncs.com
                .endpoint("endpoint")
                .credentialsProvider(credentialsProvider)
                .clientConfiguration(clientBuilderConfiguration)
                // Set this to the region where the destination bucket is located. For example, for the China (Hangzhou) region: cn-hangzhou
                .region("region")
                .build();

        try {

            // Create a PutObjectRequest object to upload the local file exampletest.txt to examplebucket.
            PutObjectRequest putObjectRequest = new PutObjectRequest("examplebucket", "exampletest.txt", new File("D:\\localpath\\exampletest.txt"));

            // If you need to set the storage class and access permissions during the upload, see the following sample code.
            // ObjectMetadata metadata = new ObjectMetadata();
            // metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
            // metadata.setObjectAcl(CannedAccessControlList.Private);
            // putObjectRequest.setMetadata(metadata);

            // Upload the file.
            PutObjectResult result = ossClient.putObject(putObjectRequest);
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}

Python

The Python SDK is available in V2 and V1. V2 is a complete refactor of V1. It simplifies underlying operations such as identity authentication, request retries, and error handling. It also provides more flexible parameter configurations and new advanced interfaces. See the following examples as needed.

V2 example

import alibabacloud_oss_v2 as oss

def main():
    # Enter the temporary AccessKey ID, AccessKey Secret, and security token generated in Step 1.5. Do not use the credentials of the RAM user.
    # Note that the AccessKey ID obtained from STS starts with "STS".
    sts_access_key_id = 'yourSTSAccessKeyID'
    sts_access_key_secret = 'yourSTSAccessKeySecret'
    # Enter the obtained STS security token.
    sts_security_token = 'yourSecurityToken'
    
    # Create a static credentials provider and explicitly set the temporary AccessKey ID, AccessKey Secret, and STS security token.
    credentials_provider = oss.credentials.StaticCredentialsProvider(
        access_key_id=sts_access_key_id,
        access_key_secret=sts_access_key_secret,
        security_token=sts_security_token,
    )

    # Load the default SDK configuration and set the credentials provider.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider

    # Enter the region where the bucket is located. For example, for China (Hangzhou), set Region to cn-hangzhou.
    cfg.region = 'cn-hangzhou'

    # Create an OSS client with the specified configuration.
    client = oss.Client(cfg)

    # The path of the local file to upload. For example, D:\\localpath\\exampletest.txt.
    local_file_path = 'D:\\localpath\\exampletest.txt'
    with open(local_file_path, 'rb') as file:
        data = file.read()

    # Send a request to upload the object. This uploads the local file exampletest.txt to examplebucket. Specify the bucket name, object name, and the file to upload.
    result = client.put_object(oss.PutObjectRequest(
        # The bucket name.
        bucket='examplebucket',
        # The name of the object to be uploaded to the bucket.
        key='exampletest.txt',
        body=data,
    ))

     # Print the status code, request ID, content MD5, ETag, CRC64 checksum, and version ID of the request result to check whether the request was successful.
    print(f'status code: {result.status_code},'
          f' request id: {result.request_id},'
          f' content md5: {result.content_md5},'
          f' etag: {result.etag},'
          f' hash crc64: {result.hash_crc64},'
          f' version id: {result.version_id},'
    )


# Call the main function when this script is run directly.
if __name__ == "__main__":
    main()  # Script entry point. Calls the main function when the file is run directly.

V1 example

# -*- coding: utf-8 -*-
import oss2

# Set yourEndpoint to the endpoint of the region where the bucket is located. For example, for China (Hangzhou), set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
endpoint = 'https://oss-cn-hangzhou.aliyuncs.com'
# Enter the temporary AccessKey ID and AccessKey Secret generated in Step 1.5. Do not use the AccessKey ID and AccessKey Secret of an Alibaba Cloud account.
sts_access_key_id = 'yourAccessKeyId'
sts_access_key_secret = 'yourAccessKeySecret'
# Enter the bucket name.
bucket_name = 'examplebucket'
# Enter the full path of the object and the content string. The full path cannot contain the bucket name. 
object_name = 'examplebt.txt'
# Enter the STS security token generated in Step 1.5.
security_token = 'yourSecurityToken'
# Use the authentication information in the temporary credentials to initialize an StsAuth instance.
auth = oss2.StsAuth(sts_access_key_id,
                    sts_access_key_secret,
                    security_token)
# Use the StsAuth instance to initialize the bucket.
bucket = oss2.Bucket(auth, endpoint, bucket_name)
# Upload the object.
result = bucket.put_object(object_name, "hello world")
print(result.status)

Go

The Go SDK is available in V2 and V1. V2 is a complete refactor of V1. It simplifies underlying operations such as identity authentication, request retries, and error handling. It also provides more flexible parameter configurations and new advanced interfaces. See the following examples as needed.

V2 example

package main

import (
	"context"
	"log"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

func main() {
	// Enter the region where the bucket is located. For example, for China (Hangzhou), set Region to cn-hangzhou.
	region := "cn-hangzhou"

	// Enter the temporary AccessKey ID, AccessKey Secret, and security token generated in Step 1.5. Do not use the credentials of the RAM user.
        // Note that the AccessKey ID obtained from STS starts with "STS".
	accessKeyID := "yourSTSAccessKeyID"
	accessKeySecret := "yourSTSAccessKeySecret"
	// Enter the obtained STS security token.
	stsToken := "yourSecurityToken"

	// Use the NewStaticCredentialsProvider method to directly set the AccessKey ID, AccessKey Secret, and STS token.
	provider := credentials.NewStaticCredentialsProvider(accessKeyID, accessKeySecret, stsToken)

	// Load the default configuration and set the credentials provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(provider).
		WithRegion(region)

	// Create an OSS client.
	client := oss.NewClient(cfg)

	// Enter the path and name of the local file to upload, for example, D:\\localpath\\exampletest.txt.
	localFile := "D:\\localpath\\exampletest.txt"

	// Create a request to upload the object.
	putRequest := &oss.PutObjectRequest{
		Bucket:       oss.Ptr("examplebucket"),      // The bucket name.
		Key:          oss.Ptr("exampletest.txt"),    // The name of the object to be uploaded to the bucket.
		StorageClass: oss.StorageClassStandard, // Specify the storage class of the object as Standard.
		Acl:          oss.ObjectACLPrivate,     // Specify the access control list (ACL) of the object as private.
		Metadata: map[string]string{
			"yourMetadataKey1": "yourMetadataValue1", // Set the metadata of the object.
		},
	}

	// Send a request to upload the object. This uploads the local file exampletest.txt to examplebucket.
	result, err := client.PutObjectFromFile(context.TODO(), putRequest, localFile)
	if err != nil {
		log.Fatalf("failed to put object from file %v", err)
	}

	// Print the result of the object upload.
	log.Printf("put object from file result:%#v\n", result)
	
}

V1 example

package main

import (
    "fmt"
    "github.com/aliyun/aliyun-oss-go-sdk/oss"
    "os"
)

func main() {
    // Obtain the temporary credentials generated in Step 1.5 from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID, OSS_ACCESS_KEY_SECRET, and OSS_SESSION_TOKEN environment variables are set.
    provider, err := oss.NewEnvironmentVariableCredentialsProvider()
    if err != nil {
        fmt.Println("Error:", err)
        os.Exit(-1)
    }
    // Create an OSSClient instance.
    // Set yourEndpoint to the endpoint of the bucket. For example, for China (Hangzhou), set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, set the endpoint as needed.
    client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider))
    if err != nil {
        fmt.Println("Error:", err)
        os.Exit(-1)
    }
    // Enter the bucket name, for example, examplebucket.
    bucketName := "examplebucket"
    // Enter the full path of the object. The full path cannot contain the bucket name. For example, exampledir/exampleobject.txt.
    objectName := "exampledir/exampleobject.txt"
    // Enter the full path of the local file, for example, D:\\localpath\\examplefile.txt.
    filepath := "D:\\localpath\\examplefile.txt"
    bucket, err := client.Bucket(bucketName)
    if err != nil {
        fmt.Println("Error:", err)
        os.Exit(-1)
    }
    // Use STS to authorize a third party to upload a file.
    err = bucket.PutObjectFromFile(objectName, filepath)
    if err != nil {
        fmt.Println("Error:", err)
        os.Exit(-1)
    }
    fmt.Println("upload success")
}

Node.js

Note

The example in this step depends on axios. Download it before you run the code.

const axios = require("axios");
const OSS = require("ali-oss");

// On the client, use temporary credentials to initialize the OSS client for temporary authorized access to OSS resources.
const getToken = async () => {
  // Set the address from which the client requests access credentials.
  await axios.get("http://localhost:8000/sts").then((token) => {
    const client = new OSS({
       // Set yourRegion to the region where the bucket is located. For example, for China (Hangzhou), set yourRegion to oss-cn-hangzhou.
      region: 'oss-cn-hangzhou',
      // Enter the temporary AccessKey ID and AccessKey Secret generated in Step 1.5. Do not use the AccessKey ID and AccessKey Secret of an Alibaba Cloud account.
      accessKeyId: token.data.AccessKeyId,
      accessKeySecret: token.data.AccessKeySecret,
      // Enter the STS security token generated in Step 1.5.
      stsToken: token.data.SecurityToken,
      authorizationV4: true,
      // Enter the bucket name.
      bucket: "examplebucket",
      // Refresh the temporary credentials.
      refreshSTSToken: async () => {
        const refreshToken = await axios.get("http://localhost:8000/sts");
        return {
          accessKeyId: refreshToken.data.AccessKeyId,
          accessKeySecret: refreshToken.data.AccessKeySecret,
          stsToken: refreshToken.data.SecurityToken,
        };
      },
    });
    // Use temporary credentials to upload the file.
    // Enter the full path of the object, excluding the bucket name. For example, exampleobject.jpg.
    // Enter the full path of the local file, for example, D:\\example.jpg.
    client.put('exampleobject.jpg', 'D:\\example.jpg').then((res)=>{console.log(res)}).catch(e=>console.log(e))
  });
};
getToken()

php

<?php
if (is_file(__DIR__ . 'autoload.php')) {
    require_once __DIR__ . 'autoload.php';
}
if (is_file(__DIR__ . '/vendor/autoload.php')) {
    require_once __DIR__ . '/vendor/autoload.php';
}

use OSS\Credentials\StaticCredentialsProvider;
use OSS\OssClient;
use OSS\Core\OssException;

try {
    // Enter the temporary AccessKey ID, AccessKey Secret, and security token generated in Step 1.5. Do not use the credentials of the RAM user.
    // Note that the AccessKey ID obtained from STS starts with "STS".
    $accessKeyId = 'yourSTSAccessKeyID';
    $accessKeySecret = 'yourSTSAccessKeySecret';
    // Enter the obtained STS security token.
    $securityToken = 'yourSecurityToken';

    // Use the StaticCredentialsProvider class to create a credentials provider.
    $provider = new StaticCredentialsProvider($accessKeyId, $accessKeySecret, $securityToken);

    // Set Endpoint to the endpoint of the region where the bucket is located. For example, for China (Hangzhou), set Endpoint to https://oss-cn-hangzhou.aliyuncs.com.
    $endpoint = "https://oss-cn-hangzhou.aliyuncs.com";

    // Enter the bucket name, for example, examplebucket.
    $bucket= "examplebucket";
    // Enter the name of the object to be uploaded to the bucket.
    $object = "exampletest.txt";
    // Enter the path of the local file to upload, for example, D:\\localpath\\exampletest.txt.
    $localFilePath = "D:\\localpath\\exampletest.txt";

    // You can set headers for the upload, such as setting the access permission to private and specifying custom metadata.
    $options = array(
        OssClient::OSS_HEADERS => array(
            'x-oss-object-acl' => 'private',
            'x-oss-meta-info' => 'yourinfo'
        ),
    );

    $config = array(
        "provider" => $provider,
        "endpoint" => $endpoint,
        "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
        // Enter the region where the bucket is located. For example, for China (Hangzhou), set Region to cn-hangzhou.
        "region" => "cn-hangzhou"
    );
    
    // Create an OSS client with the specified configuration.
    $ossClient = new OssClient($config);
    
     // Send a request to upload the local file exampletest.txt to examplebucket.
    $ossClient->putObject($bucket, $object, $localFilePath, $options);
} catch (OssException $e) {
    printf($e->getMessage() . "\n");
    return;
}

Ruby

require 'aliyun/sts'
require 'aliyun/oss'

client = Aliyun::OSS::Client.new(
  # For example, for China (Hangzhou), set the endpoint. For other regions, set the endpoint as needed.
  endpoint: 'https://oss-cn-hangzhou.aliyuncs.com',
  # Enter the temporary AccessKey ID and AccessKey Secret generated in Step 1.5. Do not use the AccessKey ID and AccessKey Secret of an Alibaba Cloud account.
  access_key_id: 'token.access_key_id',
  access_key_secret: 'token.access_key_secret',
  # Enter the STS security token generated in Step 1.5.
  sts_token: 'token.security_token'
  )
# Enter the bucket name, for example, examplebucket.
bucket = client.get_bucket('examplebucket')
# Upload the file.
bucket.put_object('exampleobject.txt', :file => 'D:\test.txt')

FAQ

What do I do if I receive the error "You are not authorized to do this action. You should be authorized by RAM."?

When you assume a RAM role as a RAM user to obtain temporary credentials as described in Step 1.5, use the AccessKey pair (AccessKey ID and AccessKey Secret) of the RAM user. Do not use the AccessKey pair of an Alibaba Cloud account to send the request.

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

This error occurs because the validity period set for the temporary credentials is outside the allowed time range. Follow these principles to set the validity period:

  • If you do not customize the maximum session duration for the role, the default session duration is 3600 seconds. In this case, the minimum validity period that you can set for temporary credentials by using the durationSeconds parameter is 900 seconds, and the maximum is 3600 seconds.

  • If you customize the maximum session duration for the role, the minimum validity period that you can set for temporary credentials by using the durationSeconds parameter is 900 seconds. The maximum validity period is the same as the maximum session duration for the role. The maximum session duration for a role can be set to a value from 3600 seconds to 43200 seconds.

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

What do I do if I receive the error "The security token you provided is invalid."?

Make sure that you completely enter the SecurityToken obtained in Step 1.5.

What do I do if I receive the error "The OSS Access Key Id you provided does not exist in our records."?

The temporary credentials have expired and are automatically invalidated. Request new temporary credentials from the app server. For more information, see Step 1.5.

What do I do if I receive the error "AccessDenied : Anonymous access is forbidden for this operation."?

When you obtain temporary credentials as described in Step 1.5, use the AccessKey ID and AccessKey Secret of the RAM user that was created in Step 1.1. Do not use the AccessKey ID and AccessKey Secret of an Alibaba Cloud account.

What do I do if I receive the "NoSuchBucket" error?

This error occurs because the specified bucket does not exist. Check the bucket name and make sure it is correct.

What do I do if I receive the error "You have no right to access this object because of bucket acl." when I use temporary credentials to access OSS resources?

This error usually occurs because the policy is configured incorrectly. For information about how to configure the elements in a policy, see Overview of RAM policies. If you need to obtain temporary credentials that grant permissions for operations such as multipart upload and append upload, you must grant the corresponding permissions in the Action element of the policy. For more information about OSS Actions, see OSS Action categories.

What do I do if I receive the error "Access denied by authorizer's policy." when I use temporary credentials to access OSS resources?

This error usually occurs because you do not have the required permissions to perform the operation. Before you apply for temporary credentials, you must create a RAM role to obtain the credentials and grant permissions to the role (Step 1.4 in this topic). When you send a request to the STS server to assume this role and obtain temporary credentials, you can use the policy parameter to further restrict the permissions of the temporary credentials (Step 1.5 in this topic).

  • If you set the policy parameter, the final permissions of the temporary credentials are the intersection of the permissions in the RAM role's policy and the permissions in the policy parameter.

    • Example 1

      As shown in the following figure, A represents the permissions of the RAM role, B represents the permissions set by the policy parameter, and C represents the final permissions of the temporary credentials.

      1.jpg

    • Example 2

      As shown in the following figure, A represents the permissions of the RAM role, and B represents the permissions set by the policy parameter. The permissions set by the policy parameter are a subset of the RAM role's permissions. Therefore, B represents the final permissions of the temporary credentials.

      2.jpg

  • If you do not set the policy parameter, the temporary credentials have the same permissions as the RAM role.

What do I do if I receive the error "The bucket you are attempting to access must be addressed using the specified endpoint."?

This error occurs because the Endpoint parameter in Step 2 is incorrect. You must specify the endpoint that corresponds to the region where your bucket is located. For more information about the mappings between regions and endpoints, see Regions and endpoints.

Can I obtain multiple temporary credentials at the same time?

Yes. A single request returns only one set of temporary credentials. If you want to obtain multiple sets of temporary credentials, you must send multiple requests. You can use multiple sets of temporary credentials at the same time as long as they are within their validity periods.

What do I do if I receive an error about an incorrect time format?

If you receive an error about an incorrect time format when you make an API call, the error may be caused by an extra space in the Timestamp parameter. Check the parameter and correct it.

The timestamp of a request must be in the ISO 8601 standard format and in UTC. The format is YYYY-MM-DDThh:mm:ssZ. For example, 2014-05-26T12:00:00Z corresponds to 20:00:00 on May 26, 2014, in Beijing time (UTC+8).

What do I do if error code 0003-0000301 is returned?

The error code 0003-0000301 is returned because the temporary credentials do not have the permissions to perform OSS operations. For the solution, see 0003-0000301.

Related documents

  • To get STS temporary credentials from a server for client-side uploads with restrictions on file size, file type, or upload path, see direct client upload.

  • After you upload files to OSS using STS temporary credentials, you can use presigned URLs to share the files with third-party users for preview or download. For more information, see Use presigned URLs to download or preview files.