The OSS SDK for Node.js simplifies integrating Object Storage Service (OSS) into your Node.js applications. It supports core features, such as file uploads, downloads, and permission management, to help you quickly manage files in the cloud.
Quick integration
Follow these steps to quickly get started with the OSS SDK for Node.js.
Prepare the environment
Download and install the Node.js runtime environment. For optimal compatibility and performance, we recommend that you use Node.js 8.0 or later.
You can run the
node -vcommand to check the Node.js version.You can run the
npm -vcommand to check the npm version.
Install the SDK
Select an 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 --saveInstall version 4.x
npm install ali-oss@^4.x --saveAfter the installation is complete, you can run the npm list ali-oss command to verify that the SDK is installed. If the installation is successful, the command returns the SDK version.
Configure access credentials
Configure access credentials using the AccessKey pair of a RAM user.
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 add 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'" >> ~/.bashrcRun the following command to make the changes take effect.
source ~/.bashrcRun the following commands to verify that the environment variables are configured correctly.
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
macOS
Run the following command in the terminal to check the default shell type.
echo $SHELLFollow the steps for your default shell type.
Zsh
Run the following commands to add 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'" >> ~/.zshrcRun the following command to make the changes take effect.
source ~/.zshrcRun the following commands to verify that the environment variables are configured correctly.
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
Bash
Run the following commands to add 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_profileRun the following command to make the changes take effect.
source ~/.bash_profileRun the following commands to verify that the environment variables are configured correctly.
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 correctly.
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 correctly.
[Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User) [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
Initialize the client
Before you run the sample code, replace the<region-id>placeholder with an actual region and its corresponding endpoint, such ascn-hangzhou.
// 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({
// Specify the region where the bucket is located.
region: 'oss-<region-id>',
// 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 client 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 benefit from higher access speeds and improved security. To access OSS over an internal network, set the endpoint to an internal endpoint during client initialization.
Before you run the sample code, replace placeholders such as<region-id>with an actual region and its corresponding endpoint, such ascn-hangzhou.
const client = new OSS({
region: 'oss-<region-id>',
// 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.
endpoint: '<endpoint>',
});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 it 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.
Before you run the sample code, replace the<region-id>placeholder with an actual region and its corresponding endpoint, such ascn-hangzhou.
// 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({
region: 'oss-<region-id>',
// 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.
Before you run the sample code, replace the<region-id>placeholder with an actual region and its corresponding endpoint, such ascn-hangzhou.
// 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({
region: 'oss-<region-id>',
// 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 (OSS) Signature V1 is being 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 an example 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 demonstrates basic file operations, such as uploading, downloading, deleting, and listing files. These examples help you quickly learn the basics of the OSS SDK for Node.js. For more examples, see the GitHub examples or the SDK reference for information about specific features.
Upload a file
The following example shows how to upload a local file to an OSS bucket. It also demonstrates how to set file properties using custom request headers for fine-grained control over storage classes, access permissions, and tags.
Before you run the sample code, replace the<region-id>placeholder with an actual region and its corresponding endpoint, such ascn-hangzhou.
// 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({
region: 'oss-<region-id>',
// 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.
Before you run the sample code, replace the<region-id>placeholder with an actual region and its corresponding endpoint, such ascn-hangzhou.
// 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({
region: 'oss-<region-id>',
// 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.
Before you run the sample code, replace the<region-id>placeholder with an actual region and its corresponding endpoint, such ascn-hangzhou.
// 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({
region: 'oss-<region-id>',
// 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.
Before you run the sample code, replace the<region-id>placeholder with an actual region and its corresponding endpoint, such ascn-hangzhou.
// 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({
region: 'oss-<region-id>',
// 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 one 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 determine a solution. For more information about error codes, see HTTP status codes. If you encounter a problem, you can also contact online technical support for assistance 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 introduce security risks and increase maintenance complexity.
An Alibaba Cloud account has full permissions on all of its resources. If the AccessKey pair of an Alibaba Cloud account is leaked, your system is exposed 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 lose 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 add 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'" >> ~/.bashrcRun the following command to make the changes take effect.
source ~/.bashrcRun the following commands to verify that the environment variables are configured correctly.
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
macOS
Run the following command in the terminal to check the default shell type.
echo $SHELLFollow the steps for your default shell type.
Zsh
Run the following commands to add 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'" >> ~/.zshrcRun the following command to make the changes take effect.
source ~/.zshrcRun the following commands to verify that the environment variables are configured correctly.
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
Bash
Run the following commands to add 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_profileRun the following command to make the changes take effect.
source ~/.bash_profileRun the following commands to verify that the environment variables are configured correctly.
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 correctly.
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 correctly.
[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 your compilation and runtime environments, such as your IDE, command-line interface, or 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 Security Token Service (STS). This method requires you to manually maintain the STS token, which can introduce 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
ImportantUse 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
ImportantUse 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 for 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 of its resources. If the AccessKey pair of an Alibaba Cloud account is leaked, your system is exposed 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 lose 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/credentialsConfigure 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. By attaching an ECS RAM role to an ECS instance, an ECI instance, or a worker node of Container Service for Kubernetes, the STS token is automatically refreshed within the instance. This method eliminates the need to provide an AccessKey pair or an STS token, which reduces the risks that are 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/credentialsConfigure 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 that are 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 that is 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 granularity, 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 each application pod 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 obtain 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 that are 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/credentialsConfigure 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 client. This method eliminates the need to provide an AccessKey pair or an STS token, which reduces the risks that are 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 response from the URI must comply with the following 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/credentialsConfigure 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);