The OSS SDK for Node.js simplifies the integration of Object Storage Service (OSS) with your Node.js applications. It supports core features, such as file uploads, downloads, and permission management, to help you quickly implement cloud file storage and management.
Quick integration
Follow these steps to quickly integrate the OSS SDK for Node.js.
Prepare the environment
Download and install the Node.js runtime environment. For optimal compatibility and performance, we recommend using Node.js 8.0 or later.
-
Run the
node -vcommand to check the Node.js version. -
Run the
npm -vcommand to check the npm version.
Install the SDK
Select the SDK version based on your Node.js version.
-
Node.js 8.0 or later: Use the latest SDK 6.x version.
-
Node.js earlier than 8.0: Use the SDK 4.x version.
Install version 6.x (recommended)
npm install ali-oss@^6.x --save
Install version 4.x
npm install ali-oss@^4.x --save
After the installation is complete, you can run the npm list ali-oss command to verify the installation. If the installation is successful, the SDK version is displayed.
Configure access credentials
Configure access credentials with a RAM user's AccessKey pair.
-
In the RAM console, create a RAM user with a Permanent AccessKey Pair. Save the AccessKey pair and grant the
AliyunOSSFullAccesspermission to the user. -
Use the AccessKey pair of the RAM user to configure environment variables.
Linux
-
Run the following commands in the command-line interface to append the environment variable settings to the
~/.bashrcfile.echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bashrc echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bashrc -
Run the following command to apply the changes.
source ~/.bashrc -
Run the following commands to verify that the environment variables are configured.
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
macOS
-
Run the following command in the terminal to view the default shell type.
echo $SHELL -
Perform the following operations based on the default shell type.
Zsh
-
Run the following commands to append the environment variable settings to the
~/.zshrcfile.echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.zshrc echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.zshrc -
Run the following command to apply the changes.
source ~/.zshrc -
Run the following commands to verify that the environment variables are configured.
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
Bash
-
Run the following commands to append the environment variable settings to the
~/.bash_profilefile.echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bash_profile echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bash_profile -
Run the following command to apply the changes.
source ~/.bash_profile -
Run the following commands to verify that the environment variables are configured.
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
-
Windows
CMD
-
Run the following commands in CMD.
setx OSS_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID" setx OSS_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET" -
Run the following commands to verify that the environment variables are configured.
echo %OSS_ACCESS_KEY_ID% echo %OSS_ACCESS_KEY_SECRET%
PowerShell
-
Run the following commands in PowerShell.
[Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_ID", "YOUR_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User) [Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", "YOUR_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User) -
Run the following commands to verify that the environment variables are configured.
[Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User) [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
-
Initialize the client
The following sample code shows how to initialize a client using the public endpoint of the China (Hangzhou) region and verify the SDK configuration by listing the buckets in your account. For a complete list of regions and endpoints, see Regions and endpoints.
// Sample code for initializing an OSS client using the OSS SDK for Node.js
const OSS = require('ali-oss');
async function main() {
// Obtain access credentials from environment variables. You must set the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables.
const client = new OSS({
// Set the region to oss-cn-hangzhou, which is the China (Hangzhou) region.
region: 'oss-cn-hangzhou',
// Obtain access credentials from environment variables.
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
// Enable Signature V4.
authorizationV4: true,
});
try {
// List all buckets.
const result = await client.listBuckets();
// Print the list of buckets.
console.log(`Found ${result.buckets.length} buckets:`);
for (const bucket of result.buckets) {
console.log(bucket.name);
}
} catch (err) {
console.log('Failed to list buckets. Details:');
console.error(err);
return;
}
}
// Execute the main function.
main().catch(console.error);
Client configuration
The OSS client supports various configuration options to suit different network environments and performance requirements. You can optimize the client's access performance and stability by customizing parameters, such as the endpoint type, timeout period, and number of connections. For more information about the configuration options, see Client configuration items.
Use an internal endpoint
You can access OSS over an internal network to avoid data transfer costs and achieve higher access speeds and greater security. To access OSS over an internal network, set the endpoint to an internal endpoint during client initialization.
const client = new OSS({
// Set the region to oss-cn-hangzhou, which is the China (Hangzhou) region.
region: 'oss-cn-hangzhou',
// Obtain access credentials from environment variables.
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
// Enable Signature V4.
authorizationV4: true,
// Use an internal endpoint. This example uses the internal endpoint of the China (Hangzhou) region.
endpoint: 'https://oss-cn-hangzhou-internal.aliyuncs.com',
});
Use a custom domain name
To access OSS using a custom domain name, set the endpoint to the custom domain name and enable the CNAME option by setting the cname: true parameter during client initialization.
Before you use a custom domain name, make sure that the custom domain name is mapped to a bucket. For more information, see Access OSS using a custom domain name.
You cannot call the client.listBuckets() method when you use a custom domain name.
// Obtain access credentials from environment variables. You must set the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables.
const client = new OSS({
// Set the region to oss-cn-hangzhou, which is the China (Hangzhou) region.
region: 'oss-cn-hangzhou',
// Obtain access credentials from environment variables.
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
// Enable Signature V4.
authorizationV4: true,
// Use a custom domain name.
endpoint: 'http://example.com',
// Specify the bucket name. The bucket name must be mapped to the custom domain name.
bucket: 'example-bucket',
// Enable the CNAME option.
cname: true,
});
Use an acceleration endpoint
To accelerate access, set the endpoint to an acceleration endpoint when you initialize the OSS client.
// Obtain access credentials from environment variables. You must set the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables.
const client = new OSS({
// Set the region to oss-cn-hangzhou, which is the China (Hangzhou) region.
region: 'oss-cn-hangzhou',
// Obtain access credentials from environment variables.
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
// Enable Signature V4.
authorizationV4: true,
// Use an acceleration endpoint.
endpoint: 'https://oss-accelerate.aliyuncs.com',
// Specify the bucket name. Transfer acceleration must be enabled for the bucket.
bucket: 'example-bucket',
});
Signature version
Alibaba Cloud Object Storage Service Signature V1 will be phased out on the following schedule. We recommend that you upgrade to Signature V4 as soon as possible to prevent service disruptions.
-
Starting March 1, 2025, new users cannot use Signature V1.
-
Starting September 1, 2025, Signature V1 will no longer be updated or maintained, and new buckets cannot use Signature V1.
The following sample code shows how to initialize a client using Signature V1. For a sample of how to initialize a client using Signature V4, see Initialize the client.
// Sample code for initializing an OSS client using the OSS SDK for Node.js
const OSS = require('ali-oss');
async function main() {
// Obtain access credentials from environment variables. You must set the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables.
const client = new OSS({
// Obtain access credentials from environment variables.
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
});
try {
// List all buckets.
const result = await client.listBuckets();
// Print the list of buckets.
console.log(`Found ${result.buckets.length} buckets:`);
for (const bucket of result.buckets) {
console.log(bucket.name);
}
} catch (err) {
console.log('Failed to list buckets. Details:');
console.error(err);
return;
}
}
// Execute the main function.
main().catch(console.error);
Sample code
The following sample code shows how to perform basic file operations, such as uploading, downloading, deleting, and listing files. These examples help you quickly learn the basic usage of the OSS SDK for Node.js. For more examples, see the GitHub examples or the SDK reference for specific features.
Upload a file
The following example shows how to upload a local file to an OSS bucket. It also shows how to set file properties using custom request headers for fine-grained control over storage classes, access permissions, and tags.
// Sample code for uploading a file using the OSS SDK for Node.js
const OSS = require('ali-oss');
const path = require('path');
async function main() {
// Obtain access credentials from environment variables. You must set the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables.
const client = new OSS({
// Set the region to oss-cn-hangzhou, which is the China (Hangzhou) region.
region: 'oss-cn-hangzhou',
// Obtain access credentials from environment variables.
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
// Enable Signature V4.
authorizationV4: true,
// Specify the bucket name.
bucket: 'example-bucket',
});
// Custom request headers.
const headers = {
// Specify the storage class of the object.
'x-oss-storage-class': 'Standard',
// Specify the access control list (ACL) of the object.
'x-oss-object-acl': 'private',
// Specify that the file is downloaded as an attachment when accessed through a URL.
'Content-Disposition': 'attachment',
// Set tags for the object. You can set multiple tags.
'x-oss-tagging': 'Tag1=1&Tag2=2',
// Specify whether to overwrite an object that has the same name. In this example, this parameter is set to true, which indicates that an object with the same name is not overwritten.
'x-oss-forbid-overwrite': 'true',
};
try {
// Configure file information.
const key = 'dest.jpg'; // The path of the file in OSS.
const localFilePath = path.normalize('dest.jpg'); // The full path of the local file.
// Upload the local file to the specified path in OSS.
const result = await client.put(key, localFilePath, { headers });
console.log(`File uploaded: ${localFilePath} -> ${key}`);
console.log('Upload result:', result);
} catch (err) {
console.log('Upload failed. Details:');
console.error(err);
return;
}
}
// Execute the main function.
main().catch(console.error);
Download a file
The following example shows how to download a file from an OSS bucket to a specified local path.
// Sample code for downloading a file using the OSS SDK for Node.js
const OSS = require('ali-oss');
async function main() {
// Obtain access credentials from environment variables. You must set the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables.
const client = new OSS({
// Set the region to oss-cn-hangzhou, which is the China (Hangzhou) region.
region: 'oss-cn-hangzhou',
// Obtain access credentials from environment variables.
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
// Enable Signature V4.
authorizationV4: true,
// Specify the bucket name.
bucket: 'example-bucket',
});
try {
// Configure file information.
const key = 'dest.jpg'; // The path of the file in OSS.
const filePath = 'dest.jpg'; // The local path to save the file.
// Download the file from OSS to the specified local path.
const result = await client.get(key, filePath);
console.log(`File downloaded: ${key} -> ${filePath}`);
} catch (err) {
console.log('Download failed. Details:');
console.error(err);
return;
}
}
// Execute the main function.
main().catch(console.error);
Delete a file
The following example shows how to delete a specified file from an OSS bucket.
// Sample code for deleting a file using the OSS SDK for Node.js
const OSS = require('ali-oss');
async function main() {
// Obtain access credentials from environment variables. You must set the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables.
const client = new OSS({
// Set the region to oss-cn-hangzhou, which is the China (Hangzhou) region.
region: 'oss-cn-hangzhou',
// Obtain access credentials from environment variables.
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
// Enable Signature V4.
authorizationV4: true,
// Specify the bucket name.
bucket: 'example-bucket',
});
try {
// Configure file information.
const key = 'dest.jpg'; // The path of the file to delete in OSS.
// Delete the specified file from OSS.
const result = await client.delete(key);
console.log(`File deleted: ${key}`);
console.log('Delete result:', result);
} catch (err) {
console.log('Delete failed. Details:');
console.error(err);
return;
}
}
// Execute the main function.
main().catch(console.error);
List files
The following example shows how to list files in an OSS bucket. By default, details of up to 100 files are returned.
// Sample code for listing files using the OSS SDK for Node.js
const OSS = require('ali-oss');
async function main() {
// Obtain access credentials from environment variables. You must set the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables.
const client = new OSS({
// Set the region to oss-cn-hangzhou, which is the China (Hangzhou) region.
region: 'oss-cn-hangzhou',
// Obtain access credentials from environment variables.
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
// Enable Signature V4.
authorizationV4: true,
// Specify the bucket name.
bucket: 'example-bucket',
});
try {
// By default, a maximum of 100 files are returned if no parameters are specified.
const result = await client.list();
console.log(`Found ${result.objects ? result.objects.length : 0} files:`);
// Print the list of files.
if (result.objects && result.objects.length > 0) {
for (const object of result.objects) {
console.log(`File name: ${object.name}, Size: ${object.size} bytes, Last modified: ${object.lastModified}`);
}
} else {
console.log('No files found in the bucket.');
}
} catch (err) {
console.log('Failed to list files. Details:');
console.error(err);
return;
}
}
// Execute the main function.
main().catch(console.error);
Exception handling
If an error occurs when you use the OSS SDK for Node.js to access OSS, OSS returns an error response that contains details, such as the HTTP status code, error message, and request ID. For example, if you try to download an object that does not exist, an error message similar to the following is returned (some information is omitted):
Error [NoSuchKeyError]: Object not exists {
status: 404,
code: 'NoSuchKey',
requestId: '6904202CA7BABC37395E28AB'
}
You can use the error code to identify the cause of the error and find a solution. For more information about error codes, see HTTP status codes. If you encounter a problem, you can also seek help from online technical support by providing the request ID.
Access credential configuration
OSS supports multiple credential initialization methods. Select an appropriate method based on your authentication and authorization requirements.
Use the AccessKey pair of a RAM user
This method is suitable for applications that are deployed in a secure and stable environment, require long-term access to OSS, and do not require frequent credential rotation. You can initialize the credential provider using the AccessKey pair (AccessKey ID and AccessKey secret) of an Alibaba Cloud account or a RAM user. This method requires you to manually maintain the AccessKey pair, which can pose security risks and increase maintenance complexity.
-
An Alibaba Cloud account has full permissions on all resources. Leaking the AccessKey pair of an Alibaba Cloud account exposes your system to significant security risks. For security reasons, we do not recommend using the AccessKey pair of an Alibaba Cloud account. We recommend that you use the AccessKey pair of a RAM user with the minimum required permissions.
-
To create an AccessKey pair for a RAM user, see Create an AccessKey pair. The AccessKey ID and AccessKey secret of a RAM user are displayed only when the AccessKey pair is created. You must save them securely. If you forget the AccessKey pair, you must create a new one.
-
Use the AccessKey pair of a RAM user to configure environment variables.
Linux
-
Run the following commands in the command-line interface to append the environment variable settings to the
~/.bashrcfile.echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bashrc echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bashrc -
Run the following command to apply the changes.
source ~/.bashrc -
Run the following commands to verify that the environment variables are configured.
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
macOS
-
Run the following command in the terminal to view the default shell type.
echo $SHELL -
Perform the following operations based on the default shell type.
Zsh
-
Run the following commands to append the environment variable settings to the
~/.zshrcfile.echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.zshrc echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.zshrc -
Run the following command to apply the changes.
source ~/.zshrc -
Run the following commands to verify that the environment variables are configured.
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
Bash
-
Run the following commands to append the environment variable settings to the
~/.bash_profilefile.echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bash_profile echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bash_profile -
Run the following command to apply the changes.
source ~/.bash_profile -
Run the following commands to verify that the environment variables are configured.
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
-
Windows
CMD
-
Run the following commands in CMD.
setx OSS_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID" setx OSS_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET" -
Run the following commands to verify that the environment variables are configured.
echo %OSS_ACCESS_KEY_ID% echo %OSS_ACCESS_KEY_SECRET%
PowerShell
-
Run the following commands in PowerShell.
[Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_ID", "YOUR_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User) [Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", "YOUR_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User) -
Run the following commands to verify that the environment variables are configured.
[Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User) [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
-
-
After you modify the system environment variables, restart or refresh the compilation and runtime environment, such as the IDE, command-line interface, other desktop applications, and backend services, to ensure that the latest system environment variables are loaded.
-
Pass the credential information using environment variables.
const OSS = require("ali-oss"); // Initialize OSS. const client = new OSS({ // Obtain the value of AccessKey ID from an environment variable. accessKeyId: process.env.OSS_ACCESS_KEY_ID, // Obtain the value of AccessKey secret from an environment variable. accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET }); // listBuckets const buckets = await client.listBuckets(); console.log(buckets);
Use an STS token
This method is suitable for applications that require temporary access to OSS. You can initialize the credential provider using the temporary identity credentials (AccessKey ID, AccessKey secret, and security token) that you obtain from STS. This method requires you to manually maintain the STS token, which can pose security risks and increase maintenance complexity. To temporarily access OSS multiple times, you must manually refresh the STS token.
-
To quickly obtain an STS token using OpenAPI, see AssumeRole - Obtain temporary identity credentials of a RAM role.
-
To obtain an STS token using an SDK, see Use an STS token to access OSS.
-
When you generate an STS token, you must specify its time-to-live (TTL). The STS token automatically becomes invalid after it expires.
-
For a list of STS endpoints, see Endpoints.
-
Use temporary identity credentials to set environment variables.
macOS, Linux, and Unix
Important-
Use the temporary identity credentials (AccessKey ID, AccessKey secret, and security token) obtained from STS, not the AccessKey pair of a RAM user.
-
The AccessKey ID obtained from STS starts with "STS", for example, "STS.****************".
export OSS_ACCESS_KEY_ID=<STS_ACCESS_KEY_ID> export OSS_ACCESS_KEY_SECRET=<STS_ACCESS_KEY_SECRET> export OSS_SESSION_TOKEN=<STS_SECURITY_TOKEN>Windows
Important-
Use the temporary identity credentials (AccessKey ID, AccessKey secret, and security token) obtained from STS, not the AccessKey pair (AccessKey ID and AccessKey secret) of a RAM user.
-
The AccessKey ID obtained from STS starts with "STS", for example, "STS.****************".
set OSS_ACCESS_KEY_ID=<STS_ACCESS_KEY_ID> set OSS_ACCESS_KEY_SECRET=<STS_ACCESS_KEY_SECRET> set OSS_SESSION_TOKEN=<STS_SECURITY_TOKEN> -
-
Pass the credential information using environment variables.
const OSS = require("ali-oss"); // Initialize OSS. const client = new OSS({ // Obtain the value of AccessKey ID from an environment variable. accessKeyId: process.env.OSS_ACCESS_KEY_ID, // Obtain the value of AccessKey secret from an environment variable. accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET, // Obtain the value of the STS token from an environment variable. stsToken: process.env.OSS_SESSION_TOKEN }); // listBuckets const buckets = await client.listBuckets(); console.log(buckets);
Use a RAM role ARN
This method is suitable for applications that require authorized access to OSS, such as cross-account access. You can initialize the credential provider by specifying the Alibaba Cloud Resource Name (ARN) of a RAM role. This method is based on STS tokens. The credentials tool obtains an STS token from STS and calls the AssumeRole operation to request a new STS token before the current one expires. You can also assign a value to the policy parameter to further restrict the permissions of the RAM role.
-
An Alibaba Cloud account has full permissions on all resources. Leaking the AccessKey pair of an Alibaba Cloud account exposes your system to significant security risks. For security reasons, we do not recommend using the AccessKey pair of an Alibaba Cloud account. We recommend that you use the AccessKey pair of a RAM user with the minimum required permissions.
-
To create an AccessKey pair for a RAM user, see Create an AccessKey pair. The AccessKey ID and AccessKey secret of a RAM user are displayed only when the AccessKey pair is created. You must save them securely. If you forget the AccessKey pair, you must create a new one.
-
To obtain the ARN of a RAM role, see Create a RAM role for a trusted Alibaba Cloud account.
-
Add the credentials dependency.
npm install @alicloud/credentials -
Configure the AccessKey pair and the RAM role ARN as access credentials.
const Credential = require("@alicloud/credentials"); const OSS = require("ali-oss"); // Initialize the Credentials client using a RAM role ARN. const credentialsConfig = new Credential.Config({ // The credential type. type: "ram_role_arn", // Obtain the value of AccessKey ID from an environment variable. accessKeyId: process.env.OSS_ACCESS_KEY_ID, // Obtain the value of AccessKey secret from an environment variable. accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET, // The ARN of the RAM role to assume. Example: acs:ram::123456789012****:role/adminrole. You can set roleArn using the ALIBABA_CLOUD_ROLE_ARN environment variable. roleArn: '<RoleArn>', // The name of the role session. You can set RoleSessionName using the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable. roleSessionName: '<RoleSessionName>', // A more restrictive access policy. This parameter is optional. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"} // policy: '<Policy>', roleSessionExpiration: 3600 }); const credentialClient = new Credential.default(credentialsConfig); const credential = await credentialClient.getCredential(); // Initialize OSS. const client = new OSS({ accessKeyId:credential.accessKeyId, accessKeySecret: credential.accessKeySecret, stsToken: credential.securityToken, refreshSTSTokenInterval: 0, // The credential provider controls the update of accessKeyId, accessKeySecret, and stsToken. refreshSTSToken: async () => { const { accessKeyId, accessKeySecret, securityToken } = await credentialClient.getCredential(); return { accessKeyId, accessKeySecret, stsToken: securityToken, }; } }); // listBuckets const buckets = await client.listBuckets(); console.log( buckets);
Use an ECS RAM role
This method is suitable for applications that run on ECS instances, ECI instances, or worker nodes of Container Service for Kubernetes. We recommend that you initialize the credential provider using an ECS RAM role. This method is based on STS tokens. An ECS RAM role lets you attach a role to an ECS instance, an ECI instance, or a worker node of Container Service for Kubernetes to automatically refresh the STS token within the instance. This method eliminates the need to provide an AccessKey pair or an STS token, which reduces the risks associated with manual maintenance. To learn how to obtain an ECS RAM role, see Create a RAM role for a trusted Alibaba Cloud account. To learn how to attach a role to an ECS instance, see Attach an instance RAM role.
-
Add the credentials dependency.
npm install @alicloud/credentials -
Configure the ECS RAM role as the access credential.
const Credential = require("@alicloud/credentials"); const OSS = require("ali-oss"); // Initialize the Credentials client using a RAM role ARN. const credentialsConfig = new Credential.Config({ // The credential type. type: "ecs_ram_role", // Optional. The name of the ECS role. If you do not specify this parameter, the role name is automatically obtained. We recommend that you specify this parameter to reduce the number of requests. You can set roleName using the ALIBABA_CLOUD_ECS_METADATA environment variable. roleName: '<RoleName>' }); const credentialClient = new Credential.default(credentialsConfig); const { accessKeyId, accessKeySecret, securityToken } = await credentialClient.getCredential(); // Initialize the OSS client. const client = new OSS({ accessKeyId, accessKeySecret, stsToken: securityToken, refreshSTSTokenInterval: 0, // The credential provider controls the update of accessKeyId, accessKeySecret, and stsToken. refreshSTSToken: async () => { const { accessKeyId, accessKeySecret, securityToken } = await credentialClient.getCredential(); return { accessKeyId, accessKeySecret, stsToken: securityToken, }; } }); // listBuckets const buckets = await client.listBuckets(); console.log(buckets);
Use an OIDC role ARN
After you configure a RAM role for worker nodes in Container Service for Kubernetes, applications in pods on those nodes can obtain the STS token of the attached role through the global meta service. This process is similar to how applications deployed on ECS obtain credentials. However, if untrusted applications are deployed on the container cluster, such as applications from customers with closed-source code, you may not want them to obtain the STS token of the instance RAM role attached to the worker nodes. To ensure the security of your cloud resources while allowing these untrusted applications to securely obtain the required STS tokens and achieve application-level permission minimization, you can use the RAM Roles for Service Accounts (RRSA) feature. This method is based on STS tokens. The Alibaba Cloud container cluster creates and mounts the corresponding service account OIDC token file for different application pods and injects the relevant configuration information into environment variables. The credentials tool obtains the configuration information from the environment variables and calls the AssumeRoleWithOIDC operation of STS to exchange for the STS token of the bound role. This method eliminates the need to provide an AccessKey pair or an STS token, which reduces the risks associated with manual maintenance. For more information, see Configure the RAM permissions of a ServiceAccount using RRSA to achieve pod-level permission isolation.
-
Add the credentials dependency.
npm install @alicloud/credentials -
Configure the OIDC RAM role as the access credential.
const OSS = require("ali-oss"); const Credential = require("@alicloud/credentials"); const credentialsConfig = new Credential.Config({ // The credential type. type: "oidc_role_arn", // The ARN of the RAM role. You can set roleArn using the ALIBABA_CLOUD_ROLE_ARN environment variable. roleArn: '<RoleArn>', // The ARN of the OIDC provider. You can set oidcProviderArn using the ALIBABA_CLOUD_OIDC_PROVIDER_ARN environment variable. oidcProviderArn: '<OidcProviderArn>', // The path of the OIDC token file. You can set oidcTokenFilePath using the ALIBABA_CLOUD_OIDC_TOKEN_FILE environment variable. oidcTokenFilePath: '<OidcTokenFilePath>', // The name of the role session. You can set roleSessionName using the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable. roleSessionName: '<RoleSessionName>', // A more restrictive access policy. This parameter is optional. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"} // policy: "<Policy>", // Set the session expiration time. roleSessionExpiration: 3600 }); const credentialClient = new Credential.default(credentialsConfig); const { accessKeyId, accessKeySecret, securityToken } = await credentialClient.getCredential(); const client = new OSS({ accessKeyId, accessKeySecret, stsToken: securityToken, refreshSTSTokenInterval: 0, // The credential provider controls the update of accessKeyId, accessKeySecret, and stsToken. refreshSTSToken: async () => { const { accessKeyId, accessKeySecret, securityToken } = await credentialClient.getCredential(); return { accessKeyId, accessKeySecret, stsToken: securityToken, }; } }); const buckets = await client.listBuckets(); console.log(buckets);
Use a credentials URI
This method is suitable for applications that need to obtain Alibaba Cloud credentials from an external system for flexible credential management and keyless access. You can initialize the credential provider using a credentials URI. This method is based on STS tokens. The credentials tool obtains an STS token from the provided URI to initialize the credential client. This method eliminates the need to provide an AccessKey pair or an STS token, which reduces the risks associated with manual maintenance.
-
A credentials URI is the server address from which the STS token is retrieved.
-
The backend service that provides the credentials URI response must implement logic to automatically refresh the STS token. This ensures that the application can always obtain valid credentials.
-
For the credentials tool to correctly parse and use the STS token, the URI must comply with the following response protocol:
-
Response status code: 200
-
Response body structure:
{ "Code": "Success", "AccessKeySecret": "AccessKeySecret", "AccessKeyId": "AccessKeyId", "Expiration": "2021-09-26T03:46:38Z", "SecurityToken": "SecurityToken" }
-
-
Add the credentials dependency.
npm install @alicloud/credentials -
Configure the credentials URI as the access credential.
const OSS = require("ali-oss"); const Credential = require("@alicloud/credentials"); // Initialize the Credentials client using a credentials URI. const credentialsConfig = new Credential.Config({ // The credential type. type: "credentials_uri", // The URI from which to obtain the credentials. The format is http://local_or_remote_uri/. You can set credentialsUri using the ALIBABA_CLOUD_CREDENTIALS_URI environment variable. credentialsURI: '<CredentialsUri>' }); const credentialClient = new Credential.default(credentialsConfig); const credential = await credentialClient.getCredential(); // Initialize OSS. const client = new OSS({ accessKeyId: credential.accessKeyId, accessKeySecret: credential.accessKeySecret, stsToken: credential.securityToken, refreshSTSTokenInterval: 0, // The credential provider controls the update of accessKeyId, accessKeySecret, and stsToken. refreshSTSToken: async () => { const { accessKeyId, accessKeySecret, securityToken } = await credentialClient.getCredential(); return { accessKeyId, accessKeySecret, stsToken: securityToken, }; } }); // listBuckets const buckets = await client.listBuckets(); console.log(buckets);