This topic describes how to use temporary access credentials provided by Security Token Service (STS) or a signed URL to temporarily access Object Storage Service (OSS) resources.
Important A validity period must be specified for STS temporary access credentials and a signed URL. When you use temporary access credentials to generate a signed URL that is used to perform operations, such as object uploads and downloads, the minimum validity period takes precedence. For example, you can set the validity period of your temporary access credentials to 1,200 seconds and the validity period of the signed URL generated by using the credentials to 3,600 seconds. In this case, the signed URL cannot be used to upload objects after the STS temporary access credentials expire, even if the signed URL is within its validity period.
Use STS for temporary access authorization
You can use STS to authorize temporary access to OSS. STS is a web service that provides temporary access tokens for users. You can use STS to grant temporary access credentials that have a custom validity period and custom permissions to a third-party application or a RAM user that is managed by you. For more information about STS, see What is STS?.
STS provides the following benefits:
You need to only generate a temporary access token and send the access token to a third-party application. You do not need to provide your AccessKey pair to the third-party application. You can specify the access permissions and validity period of this token.
The token automatically expires after the validity period ends. Therefore, you do not need to manually revoke the access permissions of a token.
To access OSS by using temporary access credentials provided by STS, perform the following steps:
Step 1: Create a RAM user
Log on to the RAM console.
In the left-side navigation pane, choose > Users.
On the Users page, click Create User.
Configure the Logon Name and Display Name parameters.
In the Access Mode section, select OpenAPI Access. Then, click OK.
Complete security verification as prompted.
Copy the AccessKey pair (AccessKey ID and AccessKey secret).
Important You can obtain the AccessKey secret of a RAM user only when you create the RAM user. You must keep the AccessKey secret safely to prevent credential leaks.
Step 2: Grant the RAM user the AssumeRole permission
On the Users page, find the RAM user that you created and click Add Permissions in the Actions column.
In the Policy section of the Grant Permission panel, select the AliyunSTSAssumeRoleAccess policy.
Note The AliyunSTSAssumeRoleAccess policy allows a RAM user to call the AssumeRole operation. The permissions of the policy are independent of the permissions required for the RAM user to obtain temporary access credentials from STS and initiate requests to OSS.
Click Grant permissions.
Step 3: Create a role used to obtain temporary access credentials from STS
In the left-side navigation pane, choose Identities > Roles.
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.
In the Configure Role step of the Create Role wizard, set RAM Role Name to RamOssTest and Select Trusted Alibaba Cloud Account to Current Alibaba Cloud Account.
Click OK. After the role is created, click Close.
On the Roles page, enter RamOssTest in the search box, click the search icon, and click RamOssTest in the search result.
Click Copy on the right side of the RamOssTest page to save the Alibaba Cloud Resource Name (ARN) of the role.
Step 4: Grant the role the permissions to upload objects to and download objects from OSS
Allow the RAM role to download and upload objects by attaching a custom policy to the RAM role.
In the left-side navigation pane, choose > .
On the Policies page, click Create Policy.
On the Create Policy page, click JSON. Modify the script in the policy editor to grant the role the permissions to upload objects to and download objects from the bucket named examplebucket. The following sample code provides an example on how to grant the role the permissions.
{
"Version": "1",
"Statement": [
{
"Effect": "Allow",
"Action": [
"oss:PutObject",
"oss:GetObject"
],
"Resource": [
"acs:oss:*:*:examplebucket",
"acs:oss:*:*:examplebucket/*"
]
}
]
}
Click Next to edit policy information.
In the Basic Information section, set Name to RamTestPolicy and click OK.
Attach the custom policy to the RamOssTest role.
In the left-side navigation pane, choose .
On the Roles page, find the RamOssTest role.
Click Grant Permission in the Actions column.
In the Grant Permission panel, select Custom Policy from the drop-down list in the Policy section and select the RamTestPolicy policy.
Click Grant permissions.
Step 5: Generate temporary access credentials by using STS
Temporary access credentials contain a security token and a temporary AccessKey pair. An AccessKey pair consists of an AccessKey ID and an AccessKey secret. The validity period of temporary access credentials is in seconds. The minimum validity period of temporary access credentials is 900 seconds. The maximum validity period of temporary access credentials is the maximum session duration specified for the current role. For more information, see Specify the maximum session duration for a RAM role.
Important To use the express module, make sure that the module is installed. If the module has not been installed, run the npm install express --save command to install it.
const { STS } = require('ali-oss');
const express = require("express");
const app = express();
app.get('/sts', (req, res) => {
let sts = new STS({
// Specify the AccessKey pair of the RAM user that was created in Step 1.
accessKeyId: 'yourAccessKeyId',
accessKeySecret: 'yourAccessKeySecret'
});
// Specify the ARN of the RAM role that was obtained in Step 2. Example: acs:ram::175708322470****:role/ramtest.
// Specify a custom policy to limit the permissions of the temporary access credentials. If you do not specify a custom policy, the temporary access credentials have full permissions of the specified RAM role.
The permissions obtained by the temporary access credentials are the intersection of the role permissions configured in Step 4 and the permissions specified by the custom RAM policy.
// Specify the validity period of the temporary access credentials. Unit: seconds. The minimum validity period of the temporary access credentials is 900 seconds. The maximum validity period of the temporary access credentials is the maximum session duration specified for the current role. In this example, expiration is set to 3,000 seconds.
// Specify a custom role session name, which is used to distinguish different tokens. Example: sessiontest.
sts.assumeRole('acs:ram::175708322470****:role/ramtest', ``, '3000', '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")
})
Step 6: Use the temporary access credentials to upload objects to and download objects from OSS
Use the temporary access credentials to upload objects to OSS
Note In the following example, axioss is required. Download axioss before you run the following sample code.
const axios = require("axios");
const OSS = require("ali-oss");
// Use the temporary access credentials to initialize an OSSClient instance. The instance is used to authorize temporary access to OSS resources.
const getToken = async () => {
// Specify the address that is used by the client to obtain the temporary access credentials.
await axios.get("http://localhost:8000/sts").then((token) => {
const client = new OSS({
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to oss-cn-hangzhou.
region: 'oss-cn-hangzhou',
accessKeyId: token.data.AccessKeyId,
accessKeySecret: token.data.AccessKeySecret,
stsToken: token.data.SecurityToken,
authorizationV4: true,
// Specify the name of the bucket.
bucket: "examplebucket",
// Refresh the temporary access credentials.
refreshSTSToken: async () => {
const refreshToken = await axios.get("http://localhost:8000/sts");
return {
accessKeyId: refreshToken.AccessKeyId,
accessKeySecret: refreshToken.AccessKeySecret,
stsToken: refreshToken.SecurityToken,
};
},
});
// Use the temporary access credentials to upload objects to OSS.
// Specify the full path of the object. Do not include the bucket name in the full path. Example: exampleobject.jpg.
// Specify the full path of the local file. Example: D:\\example.jpg.
client.put('exampleobject.jpg', 'D:\\example.jpg').then((res)=>{console.log(res)}).catch(e=>console.log(e))
});
};
getToken()
Use the temporary access credentials to download objects from OSS
const axios = require("axios");
const OSS = require("ali-oss");
// Use the temporary access credentials to initialize an OSSClient instance. The instance is used to authorize temporary access to OSS resources.
const getToken = async () => {
// Specify the address that is used by the client to obtain the temporary access credentials.
await axios.get("http://localhost:8000/sts").then((token) => {
const client = new OSS({
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to oss-cn-hangzhou.
region: 'oss-cn-hangzhou',
accessKeyId: token.data.AccessKeyId,
accessKeySecret: token.data.AccessKeySecret,
stsToken: token.data.SecurityToken,
authorizationV4: true,
// Specify the name of the bucket.
bucket: "examplebucket",
// Refresh the temporary access credentials.
refreshSTSToken: async () => {
const refreshToken = await axios.get("http://localhost:8000/sts");
return {
accessKeyId: refreshToken.AccessKeyId,
accessKeySecret: refreshToken.AccessKeySecret,
stsToken: refreshToken.SecurityToken,
};
},
});
// Use the temporary access credentials to download objects from OSS.
// Specify the full path of the object. Do not include the bucket name in the full path. Example: exampleobject.jpg.
// Specify the full path of the local file. Example: D:\\example.jpg.
client.get('exampleobject.jpg', 'D:\\example.jpg').then((res)=>{console.log(res)}).catch(e=>console.log(e))
});
};
getToken()
Use a signed URL for temporary access authorization
Usage notes
When you use an OSS SDK to generate a signed URL, the OSS SDK uses a specific algorithm and the key information stored in the local computer to calculate a signature and adds the signature to a URL to ensure the validity and security of the URL. The operations performed to calculate the signature and construct the URL are completed on the client. You do not need to send requests to the server over the network. This way, you do not need to grant specific permissions to the caller when you generate the signed URL. However, to allow third-party users to perform relevant operations on the resources authorized by the signed URL, you must make sure that the principal that calls the API operations to generate the signed URL has the corresponding permissions.
For example, if a principal wants to upload an object by using a signed URL, you must grant the oss:PutObject permission to the principal. If a principal wants to download or preview an object by using a signed URL, you must grant the oss:GetObject permission to the principal.
You can generate a signed URL and provide the URL to a visitor for temporary access. When you generate a signed URL, you can specify the validity period of the URL to limit the period of time during which the visitor can access specific data.
The signed URL generated by using the following sample code may contain a plus sign (+
). In this case, replace the plus sign (+
) in the URL with %2B
. Otherwise, the signed URL may not be used to access the object as expected.
Generate a signed URL that includes IMG parameters
const OSS = require('ali-oss');
const store = new OSS({
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to oss-cn-hangzhou.
region: 'yourRegion',
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
// Specify the name of the bucket.
bucket: 'examplebucket'
})
// Obtain the signed URL that is used to process an image named exampleobject.png.
// Specify the full path of the object. Do not include the bucket name in the full path.
let url = store.signatureUrl('exampleobject.png', {
process: 'image/resize,w_200' // Configure IMG parameters used to process the image.
});
console.log(url);
// Obtain the signed URL used to process the exampleobject.png image and specify the validity period of the URL.
// Specify the full path of the object. Do not include the bucket name in the full path.
let url = store.signatureUrl('exampleobject.png', {
// Specify the validity period of the signed URL. By default, the validity period is 1,800 seconds.
expires: 3600,
// Configure IMG parameters used to process the image.
process: 'image/resize,w_200'
});
console.log(url);
Generate a signed URL that includes the versionId parameter
const OSS = require('ali-oss');
const client = new OSS({
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to oss-cn-hangzhou.
region: 'yourRegion',
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
// Specify the name of the bucket.
bucket: 'examplebucket'
})
// Generate a signed URL that includes the version ID parameter.
// Specify the full path of the object. Do not include the bucket name in the full path. Example: example.png.
console.log(
client.signatureUrl('example.jpg', {
subResource: {
// Specify the version ID of the object.
versionId: 'CAEQMBiBgIDW7duIqxgiIDA4OWRiYmFlZDUxMDQ3YzM4OWUyNjQzMzAzMDhj****',
},
})
)
Generate a signed URL and use the signed URL to upload a file
const OSS = require("ali-oss");
const { default: axios } = require("axios");
const fs = require("fs");
const client = new OSS({
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to oss-cn-hangzhou.
region: 'yourregion',
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
authorizationV4: true,
// Specify the name of the bucket.
bucket: 'examplebucket',
});
// Generate a signed URL for the object.
const url = client.signatureUrl("examplefile.txt", {
method: "PUT",
"Content-Type": "application/x-www-form-urlencoded",
});
// Specify the full path of the local file.
const file = fs.readFileSync("D:\\localpath\\examplefile.txt");
// Use the signed URL to upload the local file.
axios({
url,
method: "PUT",
data: file,
})
.then((r) => console.log(r))
.catch((e) => console.log(e));
Generate a signed URL and use the signed URL to download the object
const { default: axios } = require("axios");
const fs = require("fs");
const client = new OSS({
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to oss-cn-hangzhou.
region: 'yourRegion',
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
authorizationV4: true,
// Specify the name of the bucket.
bucket: 'examplebucket'
});
// Generate a signed URL for the object.
const url = client.signatureUrl("examplefile.txt");
// Use the signed URL to download the object to the specified full local path.
const file = "D:\\localpath\\examplefile.txt";
axios({
url,
method: "GET",
})
.then((r) => {
fs.writeFile(file, r.data, (err) => {
if (err) {
console.log(err);
}
});
})
.catch((e) => console.log(e));
FAQ
Can I use the POST method to generate a signed URL?
No, you cannot use the POST method to generate a signed URL. You can use only the PUT and GET methods to generate a signed URL. If you want to upload an object by using the POST method, you need to construct a POST request. For more information, see PostObject.