All Products
Search
Document Center

Object Storage Service:Configure access credentials (Node.js SDK)

Last Updated:Nov 29, 2025

To send OSS requests using the Node.js software development kit (SDK), you need to configure access credentials. Alibaba Cloud services use these credentials to verify your identity and access permissions. You can choose a method to provide credentials based on the authentication and authorization requirements of your scenario.

Prerequisites

Before you configure access credentials, you must install the OSS Node.js SDK. For more information, see Install the Node.js SDK.

Initialize a credential provider

Choose a credential provider

You can initialize a credential provider for OSS in several ways. Choose a method based on the authentication and authorization requirements of your scenario.

Credential provider initialization method

Scenarios

Requires a pre-existing AccessKey or Security Token Service token?

Underlying credential

Credential validity

Credential rotation or refresh method

Method 1: Use an AccessKey

For applications that run in a secure, stable environment and need long-term access to Alibaba Cloud services without frequent credential rotation.

Yes

AccessKey

Long-term

Manual rotation

Method 2: Use an STS token

For applications that run in an untrusted environment and require control over access validity and permissions.

Yes

Security Token Service (STS) token

Temporary

Manual refresh

Method 3: Use a RAMRoleARN

For applications that need authorized access to Alibaba Cloud services, such as cross-account access.

Yes

STS token

Temporary

Auto-refresh

Method 4: Obtain a RAM role from ECS instance metadata in standard mode

For applications that run on Alibaba Cloud ECS instances, ECI instances, or worker nodes of Container Service for Kubernetes.

No

STS token

Temporary

Auto-refresh

Method 5: Use an OIDCRoleArn

For untrusted applications that run on worker nodes of Container Service for Kubernetes on Alibaba Cloud.

No

STS token

Temporary

Auto-refresh

Method 6: Use a CredentialsURI

For applications that need to obtain access credentials from an external system.

No

STS token

Temporary

Auto-refresh

Method 1: Use an AccessKey

If your application runs in a secure environment, requires long-term access to OSS, and cannot frequently rotate credentials, you can use the AccessKey pair of an Alibaba Cloud account or a Resource Access Management (RAM) user to initialize the credential provider. An AccessKey pair consists of an AccessKey ID and an AccessKey secret. This method requires you to manually maintain an AccessKey pair, which increases security risks and maintenance complexity. For more information about how to obtain an AccessKey pair, see CreateAccessKey.

Warning

An Alibaba Cloud account has full permissions on all resources. A leaked AccessKey pair poses significant security risks to your system. Do not use the AccessKey pair of an Alibaba Cloud account. Instead, use the AccessKey pair of a RAM user with the minimum required permissions.

  1. Set the environment variables.

    Mac OS X/Linux/Unix

    export ALIBABA_CLOUD_ACCESS_KEY_ID=<ALIBABA_CLOUD_ACCESS_KEY_ID>
    export ALIBABA_CLOUD_ACCESS_KEY_SECRET=<ALIBABA_CLOUD_ACCESS_KEY_SECRET>

    Windows

    set ALIBABA_CLOUD_ACCESS_KEY_ID=<ALIBABA_CLOUD_ACCESS_KEY_ID>
    set ALIBABA_CLOUD_ACCESS_KEY_SECRET=<ALIBABA_CLOUD_ACCESS_KEY_SECRET>
  2. Use the AccessKey pair to initialize the client.

    const OSS = require("ali-oss");
    
    // Initialize OSS.
    const client = new OSS({
      // Obtain the AccessKey ID from an environment variable.
      accessKeyId: process.env.ALIBABA_CLOUD_ACCESS_KEY_ID,
      // Obtain the AccessKey secret from an environment variable.
      accessKeySecret: process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET
    });
    
    // listBuckets
    const buckets = await client.listBuckets();
    console.log(buckets);
    

Method 2: Use an STS token

As a RAM user, you can call the AssumeRole operation of the Security Token Service (STS) and set the maximum token expiration time to obtain a temporary credential, which is an STS token.

  1. Set the environment variables.

    Mac OS X/Linux/Unix

    export ALIBABA_CLOUD_ACCESS_KEY_ID=<ALIBABA_CLOUD_ACCESS_KEY_ID>
    export ALIBABA_CLOUD_ACCESS_KEY_SECRET=<ALIBABA_CLOUD_ACCESS_KEY_SECRET>
    export ALIBABA_CLOUD_SECURITY_TOKEN=<ALIBABA_CLOUD_SECURITY_TOKEN>

    Windows

    set ALIBABA_CLOUD_ACCESS_KEY_ID=<ALIBABA_CLOUD_ACCESS_KEY_ID>
    set ALIBABA_CLOUD_ACCESS_KEY_SECRET=<ALIBABA_CLOUD_ACCESS_KEY_SECRET>
    set ALIBABA_CLOUD_SECURITY_TOKEN=<ALIBABA_CLOUD_SECURITY_TOKEN>
  2. Use the temporary credential to initialize the client.

    const OSS = require("ali-oss");
    
    // Initialize OSS.
    const client = new OSS({
      // Obtain the AccessKey ID from an environment variable.
      accessKeyId: process.env.ALIBABA_CLOUD_ACCESS_KEY_ID,
      // Obtain the AccessKey secret from an environment variable.
      accessKeySecret: process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET,
      // Obtain the STS token from an environment variable.
      stsToken: process.env.ALIBABA_CLOUD_SECURITY_TOKEN
    });
    
    // listBuckets
    const buckets = await client.listBuckets();
    console.log(buckets);

Method 3: Use a RAMRoleARN

This method is based on STS tokens. By specifying the Alibaba Cloud Resource Name (ARN) of a RAM role, the Credentials tool obtains an STS token from STS. You can also assign a value to policy to further restrict the permissions of the RAM role.

Initialize the credential provider with an AccessKey pair and a RAMRoleARN to complete the client initialization.

const Credential = require("@alicloud/credentials");
const OSS = require("ali-oss");

// Initialize the Credentials client with a RamRoleArn.
const credentialsConfig = new Credential.Config({
  // The credential type.
  type: "ram_role_arn",
  // Obtain the AccessKey ID from an environment variable.
  accessKeyId: process.env.ALIBABA_CLOUD_ACCESS_KEY_ID,
  // Obtain the AccessKey secret from an environment variable.
  accessKeySecret: process.env.ALIBABA_CLOUD_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 role session name. You can set RoleSessionName using the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable.
  roleSessionName: '<RoleSessionName>',
  // An access policy that specifies a smaller set of permissions. 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 object 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);

Method 4: Obtain a RAM role from ECS instance metadata in standard mode

This method is based on STS tokens. The Credentials tool automatically obtains the RAM role that is attached to the ECS instance. It then calls the ECS Meta Data Server to retrieve an STS token and uses the token to initialize the client.

const Credential = require("@alicloud/credentials");
const OSS = require("ali-oss");

// Initialize the Credentials client.
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 object 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);

Method 5: Use an OIDCRoleArn

When you configure a RAM role for a worker node in Container Service for Kubernetes, applications in pods on that node can obtain the STS token of the associated role from the Meta Data Server, similar to applications deployed on ECS. However, this approach is not secure if you deploy untrusted applications on the container cluster, such as applications from customers whose source code is unavailable to you. You should prevent these applications from obtaining the STS token of the instance RAM role that is associated with the worker node. To address this, you can use the RAM Roles for Service Accounts (RRSA) feature. RRSA allows untrusted applications to securely obtain STS tokens with minimum permissions at the application level, which prevents security risks to your cloud resources. For each application pod, an Alibaba Cloud container cluster creates and mounts the corresponding service account OpenID Connect (OIDC) token file and injects configuration information into environment variables. The Credentials tool retrieves this configuration information and calls the STS AssumeRoleWithOIDC operation to obtain the STS token of the attached role. For more information, see Pod permission isolation based on RRSA.

Initialize the client by configuring 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 to the OIDC token file. You can set oidcTokenFilePath using the ALIBABA_CLOUD_OIDC_TOKEN_FILE environment variable.
  oidcTokenFilePath: '<OidcTokenFilePath>',
  // The role session name. You can set roleSessionName using the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable.
  roleSessionName: '<RoleSessionName>',
  // An access policy that specifies a smaller set of permissions. 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 object 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);

Method 6: Use a CredentialsURI

If your application needs to obtain Alibaba Cloud credentials from an external system for flexible credential management and keyless access, you can initialize the credential provider using a CredentialsURI. This method is based on STS tokens. The Credentials tool retrieves an STS token from the URI that you provide and initializes the credential client. This method does not require you to provide an AccessKey pair or an STS token, which eliminates the risks of manual maintenance. Note that the backend service that provides the CredentialsURI response must implement the logic for auto-refreshing STS tokens to ensure that your application can always obtain valid credentials.

  1. To ensure that the Credentials tool can correctly parse and use the STS token, the response from the URI must follow this protocol:

    • Response status code: 200

    • Response body structure:

      {
        "Code": "Success",
        "AccessKeySecret": "AccessKeySecret",
        "AccessKeyId": "AccessKeyId",
        "Expiration": "2021-09-26T03:46:38Z",
        "SecurityToken": "SecurityToken"
      }
  2. Initialize the client by configuring the CredentialsURI as the access credential.

    const OSS = require("ali-oss");
    const Credential = require("@alicloud/credentials");
    
    // Initialize the Credentials client using the credential URI.
    const credentialsConfig = new Credential.Config({
      // The credential type.
      type: "credentials_uri",
      // The URI from which to obtain the credential. 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 object 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);
    

What to do next

After you initialize the credential provider, you can create an OSSClient instance. For more information, see Initialization (Node.js SDK).