Tüm Ürünler
Search
Belge Merkezi

Alibaba Cloud SDK:Erişim kimlik bilgilerini yönetin

Son Güncelleme:Oct 07, 2026

Alibaba Cloud SDK, AccessKey ve STS belirteci gibi kimlik bilgilerini merkezi olarak yönetmek için Credentials aracını kullanır. Bu konuda desteklenen kimlik bilgisi türleri ve bunların yapılandırma yöntemleri açıklanmaktadır.

Arka Plan

Kimlik bilgileri, Alibaba Cloud hizmetlerine erişilirken bir kullanıcının kimliğini doğrular. Yaygın kimlik bilgisi türleri şunlardır:

  1. Bir AccessKey çifti, bir Alibaba Cloud hesabı veya RAM kullanıcısı için kalıcı kimlik bilgileri sağlar. Bir AccessKey ID ve bir AccessKey Secret içerir.

  2. Bir STS belirteci, yapılandırılabilir geçerlilik süresi ve izin kapsamına sahip bir RAM rolü için geçici kimlik bilgileri sağlar. STS Nedir.

  3. Bir bearer belirteci kimlik doğrulama ve yetkilendirme için kullanılır.

Önkoşullar

Credentials aracını yükleyin

Paketi yüklemek için aşağıdaki npm komutunu çalıştırın.

npm install @alicloud/credentials

Tüm kimlik bilgisi türlerinin desteklendiğinden emin olmak için en son sürümü kullanın. Releases · aliyun/credentials-nodejs · GitHub.

Kimlik bilgisi parametreleri

Kimlik bilgilerini @alicloud/credentials modülünün Config oluşturucusu aracılığıyla yapılandırın. type parametresi zorunludur ve hangi diğer parametrelerin geçerli olduğunu belirler. Aşağıdaki tabloda geçerli type değerleri ve bunlara ait parametreler listelenmiştir. √ = zorunlu, - = isteğe bağlı, × = desteklenmiyor.

Not

Yalnızca aşağıda listelenen kimlik bilgisi türleri ve parametreleri desteklenir.


type


access_key


sts


ram_role_arn


ecs_ram_role


oidc_role_arn


credentials_uri


bearer


accessKeyId: AccessKey ID.


√


√


√


×


×


×


×


accessKeySecret: AccessKey gizli anahtarı.


√


√


√


×


×


×


×


securityToken: Güvenlik Belirteci Hizmeti (STS) belirteci.


×


√


-


×


×


×


×


roleArn: RAM rolünün Alibaba Cloud Kaynak Adı (ARN).


×


×


√


×


√


×


×


roleSessionName: Oturum için özel bir ad. Varsayılan format credentials-nodejs-<timestamp> şeklindedir.


×


×


-


×


-


×


×


roleName: RAM rolünün adı.


×


×


×


-


×


×


×


disableIMDSv1: Güvenlik sıkılaştırma modunun (IMDSv2) zorunlu kılınıp kılınmayacağını belirtir. Varsayılan değer: false.


×


×


×


-


×


×


×


bearerToken: Bearer belirteci.


×


×


×


×


×


×


√


policy: Özel bir ilke.


×


×


-


×


-


×


×


roleSessionExpiration: Saniye cinsinden oturum sona erme süresi. Varsayılan değer: 3600.


×


×


-


×


-


×


×


oidcProviderArn: OpenID Connect (OIDC) kimlik sağlayıcısının ARN değeri.


×


×


×


×


√


×


×


oidcTokenFilePath: OpenID Connect (OIDC) belirteci dosyasının yolu.


×


×


×


×


√


×


×


externalId: Karışık vekil sorununu azaltmak için harici bir kimlik. Karışık vekil sorununu önlemek için harici kimlik kullanma.


×


×


-


×


×


×


×


credentialsURI: Kimlik bilgilerinin URI adresi.


×


×


×


×


×


√


×


STS uç noktası. Hem VPC hem de genel uç noktaları destekler. Mevcut uç noktalar: Uç Noktalar. Varsayılan: sts.aliyuncs.com.


×


×


-


×


-


×


×


timeout: HTTP istekleri için milisaniye cinsinden okuma zaman aşımı süresi. Varsayılan değer 5000'dir.


×


×


-


-


-


-


×


connectTimeout: HTTP istekleri için milisaniye cinsinden bağlantı zaman aşımı süresi. Varsayılan değer 10000'dir.


×


×


-


-


-


-


×

Kimlik bilgisi istemcisini başlatın

Önceki bölümde Credentials aracı tarafından desteklenen kimlik bilgisi türleri ve yapılandırma parametreleri açıklanmıştır. Aşağıdaki bölümlerde aracın nasıl kullanılacağını gösteren kod örnekleri sunulmaktadır. Senaryonuz için en uygun yöntemi seçin.

Önemli
  • AccessKey bilgisini proje kodunuzda düz metin olarak saklamayın. Açığa çıkan bir anahtar, hesap altındaki tüm kaynakları riske atar. Bunun yerine ortam değişkenlerinde veya yapılandırma dosyalarında saklayın.

  • credentials tool için singleton pattern uygulayın. Bu, yerleşik credential cache özelliğini etkinleştirerek aşırı API çağrılarından kaynaklanan rate limiting sorunlarını önler. Oturum kimlik bilgileri için kimlik bilgisi otomatik yenileme mekanizması.

Yöntem 1: Varsayılan kimlik bilgisi sağlayıcı zinciri

Parametre belirtmeden bir kimlik bilgisi istemcisini başlatmak, Varsayılan kimlik bilgisi sağlayıcı zincirini etkinleştirir.

const Credential = require('@alicloud/credentials');
// Use the default credential provider chain
const credentialClient = new Credential.default();
const credential = credentialClient.getCredential();
credential.then(credential => {
    console.log(credential);
});
import Credential from '@alicloud/credentials';
const credential = new Credential();
credential.getCredential().then(credential => {
    console.log(credential);
});

API çağrısı

Bu örnekte ECS'nin DescribeRegions işlemi çağrılmaktadır. Kodu çalıştırmak için ECS SDK öğesini yüklemeniz gerekir.

const Ecs20140526 = require('@alicloud/ecs20140526');
const OpenApi = require('@alicloud/openapi-client');
const Util = require('@alicloud/tea-util');
const Credential = require('@alicloud/credentials');
async function main() {
    // Initialize the credential client with default credentials.
    const credentialClient = new Credential.default();
    const ecsConfig = new OpenApi.Config({
        endpoint: 'ecs.cn-hangzhou.aliyuncs.com', // Configure the service endpoint.
        credential: credentialClient, // Specify the credential client.
    });
    const ecsClient = new Ecs20140526.default(ecsConfig);
    const describeRegionsRequest = new Ecs20140526.DescribeRegionsRequest();
    const runtime = new Util.RuntimeOptions();
    ecsClient.describeRegionsWithOptions(describeRegionsRequest, runtime).then((result) => {
        console.log(JSON.stringify(result.body));
    });
}
main().catch(console.error);
import Ecs20140526, * as $Ecs20140526 from '@alicloud/ecs20140526';
import OpenApi, * as $OpenApi from '@alicloud/openapi-client';
import Util, * as $Util from '@alicloud/tea-util';
import Credential from '@alicloud/credentials';
export default class Client {
    static async main(): Promise<$Ecs20140526.DescribeRegionsResponse> {
        // Initialize a credential instance with default credentials.
        let credential = new Credential();
        let config = new $OpenApi.Config({
            credential: credential, // Specify the credential instance.
            endpoint: 'ecs.cn-hangzhou.aliyuncs.com', // Configure the service endpoint.
        });
        let client = new Ecs20140526(config);
        let describeRegionsRequest = new $Ecs20140526.DescribeRegionsRequest({});
        let runtime = new $Util.RuntimeOptions({});
        return await client.describeRegionsWithOptions(describeRegionsRequest, runtime);
    }
}
const response = Client.main();
response.then(res => {
    console.log(res.body?.regions);
});

Yöntem 2: AccessKey kullanma

Credentials aracı, sağladığınız AccessKey bilgisini erişim kimlik bilgisi olarak kullanır.

Uyarı

Bir Alibaba Cloud hesabı (kök hesap) tüm kaynakları üzerinde tam izne sahiptir; bu nedenle açığa çıkan bir AK ciddi bir güvenlik riski oluşturur. Kök hesabın AK bilgisini kullanmayın.

En az ayrıcalık ilkesine sahip izinlere sahip bir RAM kullanıcısının AK bilgisini kullanın.

const Credential = require('@alicloud/credentials');
const credentialsConfig = new Credential.Config({
    // The credential type.
    type: 'access_key',
    // Your AccessKey ID, retrieved from an environment variable.
    accessKeyId: process.env.ALIBABA_CLOUD_ACCESS_KEY_ID,
    // Your AccessKey Secret, retrieved from an environment variable.
    accessKeySecret: process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET,
});
const credentialClient = new Credential.default(credentialsConfig);
import Credential, { Config } from '@alicloud/credentials';
const credentialsConfig  = new Config({
    // The credential type.
    type: 'access_key',
    // Your AccessKey ID, retrieved from an environment variable.
    accessKeyId: process.env.ALIBABA_CLOUD_ACCESS_KEY_ID,
    // Your AccessKey Secret, retrieved from an environment variable.
    accessKeySecret: process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET,
});
const credentialClient = new Credential(credentialsConfig);

API çağrısı

Bu örnekte ECS'nin DescribeRegions işlemi çağrılmaktadır. Kodu çalıştırmak için ECS SDK öğesini yüklemeniz gerekir.

const Ecs20140526 = require('@alicloud/ecs20140526');
const OpenApi = require('@alicloud/openapi-client');
const Util = require('@alicloud/tea-util');
const Credential = require('@alicloud/credentials');
async function main() {
    const credentialsConfig = new Credential.Config({
        // The credential type.
        type: 'access_key',
        // The AccessKey ID, read from an environment variable.
        accessKeyId: process.env.ALIBABA_CLOUD_ACCESS_KEY_ID,
        // The AccessKey secret, read from an environment variable.
        accessKeySecret: process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET,
    });
    const credentialClient = new Credential.default(credentialsConfig);
    const ecsConfig = new OpenApi.Config();
    ecsConfig.endpoint = 'ecs.cn-hangzhou.aliyuncs.com'; // The service endpoint.
    ecsConfig.credential = credentialClient; // The credential client for authentication.
    const ecsClient = new Ecs20140526.default(ecsConfig);
    const describeRegionsRequest = new Ecs20140526.DescribeRegionsRequest();
    const runtime = new Util.RuntimeOptions();
    ecsClient.describeRegionsWithOptions(describeRegionsRequest, runtime).then((response) => {
        console.log(response.body.regions);
    });
}
main().catch(console.error);
import Ecs20140526, * as $Ecs20140526 from '@alicloud/ecs20140526';
import Credential, { Config } from '@alicloud/credentials';
import OpenApi, * as $OpenApi from '@alicloud/openapi-client';
import Util, * as $Util from '@alicloud/tea-util';
export default class Client {
    static async main(): Promise<$Ecs20140526.DescribeRegionsResponse> {
        const credentialsConfig = new Config({
            // The credential type.
            type: 'access_key',
            // The AccessKey ID, read from an environment variable.
            accessKeyId: process.env.ALIBABA_CLOUD_ACCESS_KEY_ID,
            // The AccessKey secret, read from an environment variable.
            accessKeySecret: process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET,
        });
        const credentialClient = new Credential(credentialsConfig);
        let config = new $OpenApi.Config({
            credential: credentialClient, // The credential client for authentication.
            endpoint: 'ecs.cn-hangzhou.aliyuncs.com', // The service endpoint.
        });
        let client = new Ecs20140526(config);
        let describeRegionsRequest = new $Ecs20140526.DescribeRegionsRequest({});
        let runtime = new $Util.RuntimeOptions({});
        return await client.describeRegionsWithOptions(describeRegionsRequest, runtime);
    }
}
const response = Client.main();
response.then(res => {
    console.log(res.body?.regions);
});

Yöntem 3: STS belirteci kullanma

Credentials aracı, sağladığınız statik STS belirtecini erişim kimlik bilgisi olarak kullanır.

const Credential = require('@alicloud/credentials');
const credentialsConfig = new Credential.Config({
    type: 'sts',
    // Your AccessKey ID, retrieved from an environment variable.
    accessKeyId: process.env.ALIBABA_CLOUD_ACCESS_KEY_ID,
    // Your AccessKey Secret, retrieved from an environment variable.
    accessKeySecret: process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET,
    // Your security token, retrieved from an environment variable.
    securityToken: process.env.ALIBABA_CLOUD_SECURITY_TOKEN,
});
const cred = new Credential.default(credentialsConfig);
import Credential, { Config } from '@alicloud/credentials';
const credentialsConfig = new Config({
    // The credential type.
    type: 'access_key',
    // Your AccessKey ID, retrieved from an environment variable.
    accessKeyId: process.env.ALIBABA_CLOUD_ACCESS_KEY_ID,
    // Your AccessKey Secret, retrieved from an environment variable.
    accessKeySecret: process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET,
    // Your security token, retrieved from an environment variable.
    securityToken: process.env.ALIBABA_CLOUD_SECURITY_TOKEN,
});
const credentialClient = new Credential(credentialsConfig);

API çağrısı

Bu örnekte ECS'nin DescribeRegions işlemi çağrılmaktadır. Bu kodu çalıştırmak için ECS SDK ve Security Token Service SDK öğelerini yüklemeniz gerekir.

const Ecs20140526 = require('@alicloud/ecs20140526');
const Sts20150401 = require('@alicloud/sts20150401');
const OpenApi = require('@alicloud/openapi-client');
const Util = require('@alicloud/tea-util');
const Credential = require('@alicloud/credentials');
async function assumeRole() {
    // Create an STS client to get an STS token.
    const stsConfig = new OpenApi.Config({
        endpoint: 'sts.cn-hangzhou.aliyuncs.com', // The endpoint for Security Token Service (STS).
        accessKeyId: process.env.ALIBABA_CLOUD_ACCESS_KEY_ID, // Get the AccessKey ID from an environment variable.
        accessKeySecret: process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET, // Get the AccessKey secret from an environment variable.
    });
    const stsClient = new Sts20150401.default(stsConfig);
    const assumeRoleRequest = new Sts20150401.AssumeRoleRequest({
        durationSeconds: 3600, // The validity period of the STS token.
        roleArn: '<RoleArn>', // The ARN of the RAM role to assume. Example: acs:ram::123456789012****:role/adminrole. This can be set with the ALIBABA_CLOUD_ROLE_ARN environment variable. 
        roleSessionName: '<RoleSessionName>', // A custom name for the role session. This can be set with the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable. 
        policy: '', // Optional. A RAM policy. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}
    });
    try {
        const assumeRoleResponsePromise = await stsClient.assumeRole(assumeRoleRequest);
        const assumeRoleResponseBodyCredentials = assumeRoleResponsePromise.body.credentials;
        return {
            accessKeyId: assumeRoleResponseBodyCredentials.accessKeyId,
            accessKeySecret: assumeRoleResponseBodyCredentials.accessKeySecret,
            securityToken: assumeRoleResponseBodyCredentials.securityToken,
        };
    } catch (error) {
        console.error('The AssumeRole request failed:', error);
        throw error;
    }
}
async function main() {
    const stsToken = await assumeRole()
    const credentialsConfig = new Credential.Config({
        // The type of credential.
        type: 'sts',
        accessKeyId: stsToken.accessKeyId,
        accessKeySecret: stsToken.accessKeySecret,
        securityToken: stsToken.securityToken,
    });
    const credentialClient = new Credential.default(credentialsConfig);
    const ecsConfig = new OpenApi.Config({
        endpoint: 'ecs.cn-hangzhou.aliyuncs.com', // The endpoint of the cloud service.
        credential: credentialClient, // The authentication credential.
    })
    const ecsClient = new Ecs20140526.default(ecsConfig);
    const describeRegionsRequest = new Ecs20140526.DescribeRegionsRequest();
    const runtime = new Util.RuntimeOptions();
    // Call the DescribeRegions operation.
    ecsClient.describeRegionsWithOptions(describeRegionsRequest, runtime).then((response) => {
        console.log(response.body.regions);
    });
}
main().catch(console.error);
import Ecs20140526, * as $Ecs20140526 from '@alicloud/ecs20140526';
import Sts20150401, * as $Sts20150401 from '@alicloud/sts20150401';
import OpenApi, { Config } from '@alicloud/openapi-client';
import Util, * as $Util from '@alicloud/tea-util';
import Credential, { Config as CredentialConfig } from '@alicloud/credentials';
async function assumeRole() {
    // Create an STS client to get an STS token.
    const stsConfig = new Config({
        endpoint: 'sts.cn-hangzhou.aliyuncs.com', // The endpoint for Security Token Service (STS).
        accessKeyId: process.env.ALIBABA_CLOUD_ACCESS_KEY_ID, // Get the AccessKey ID from an environment variable.
        accessKeySecret: process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET, // Get the AccessKey secret from an environment variable.
    });
    const stsClient = new Sts20150401(stsConfig);
    const assumeRoleRequest = new $Sts20150401.AssumeRoleRequest({
        durationSeconds: 3600, // The validity period of the STS token.
        roleArn: '<RoleArn>', // The ARN of the RAM role to assume. Example: acs:ram::123456789012****:role/adminrole. This can be set with the ALIBABA_CLOUD_ROLE_ARN environment variable.  
        roleSessionName: '<RoleSessionName>', // A custom name for the role session. This can be set with the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable. 
        policy: '', // Optional. A RAM policy. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}
    });
    try {
        const assumeRoleResponsePromise = await stsClient.assumeRole(assumeRoleRequest);
        const assumeRoleResponseBodyCredentials = assumeRoleResponsePromise.body?.credentials;
        return {
            accessKeyId: assumeRoleResponseBodyCredentials?.accessKeyId,
            accessKeySecret: assumeRoleResponseBodyCredentials?.accessKeySecret,
            securityToken: assumeRoleResponseBodyCredentials?.securityToken,
        };
    } catch (error) {
        console.error('The AssumeRole request failed:', error);
        throw error;
    }
}
async function main() {
    const stsToken = await assumeRole()
    const credentialsConfig = new CredentialConfig({
        // The type of credential.
        type: 'sts',
        accessKeyId: stsToken.accessKeyId,
        accessKeySecret: stsToken.accessKeySecret,
        securityToken: stsToken.securityToken,
    });
    const credentialClient = new Credential(credentialsConfig);
    const ecsConfig = new Config({
        endpoint: 'ecs.cn-hangzhou.aliyuncs.com', // The endpoint of the cloud service.
        credential: credentialClient, // The authentication credential.
    })
    const ecsClient = new Ecs20140526(ecsConfig);
    const describeRegionsRequest = new $Ecs20140526.DescribeRegionsRequest();
    const runtime = new $Util.RuntimeOptions();
    // Call the DescribeRegions operation.
    ecsClient.describeRegionsWithOptions(describeRegionsRequest, runtime).then((response) => {
        console.log(response.body?.regions);
    });
}
main().catch(console.error);

Yöntem 4: AccessKey ve RAM Rolü ARN

Bu yöntem dahili olarak STS kullanır. Bir RAM rolü ARN belirttiğinizde, Credentials aracı STS'den bir STS belirteci alır. Rolün izinlerini daha da kısıtlamak için policy parametresini kullanabilirsiniz.

const Credential = require('@alicloud/credentials');
const credentialsConfig = new Credential.Config({
    type: 'ram_role_arn',
    accessKeyId: process.env.ALIBABA_CLOUD_ACCESS_KEY_ID,
    accessKeySecret: process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET,
    // The RAM role ARN to assume. Example: acs:ram::123456789012****:role/adminrole. This can also be set using the `ALIBABA_CLOUD_ROLE_ARN` environment variable.
    roleArn: '<RoleArn>',
    // A custom role session name. This can also be set using the `ALIBABA_CLOUD_ROLE_SESSION_NAME` environment variable.
    roleSessionName: '<RoleSessionName>',
    // Optional. An inline policy to limit the permissions of the RAM role. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}
    policy: '<Policy>',
    roleSessionExpiration: 3600,
});
const cred = new Credential.default(credentialsConfig);
import Credential, { Config } from '@alicloud/credentials';
const credentialsConfig = new Config({
    type: 'ram_role_arn',
    accessKeyId: process.env.ALIBABA_CLOUD_ACCESS_KEY_ID,
    accessKeySecret: process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET,
    // The RAM role ARN to assume. Example: acs:ram::123456789012****:role/adminrole. This can also be set using the `ALIBABA_CLOUD_ROLE_ARN` environment variable.
    roleArn: '<RoleArn>',
    // A custom role session name. This can also be set using the `ALIBABA_CLOUD_ROLE_SESSION_NAME` environment variable.
    roleSessionName: '<RoleSessionName>',
    // Optional. An inline policy to limit the permissions of the RAM role. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}
    policy: '<Policy>',
    roleSessionExpiration: 3600,
});
const credentialClient = new Credential(credentialsConfig);

API çağrı yöntemi

Bu örnekte ECS'nin DescribeRegions işlemi nasıl çağrılacağı gösterilmektedir. Kodu çalıştırmak için ECS SDK öğesini yüklemeniz gerekir.

const Ecs20140526 = require('@alicloud/ecs20140526');
const OpenApi = require('@alicloud/openapi-client');
const Util = require('@alicloud/tea-util');
const Credential = require('@alicloud/credentials');
async function main() {
    const credentialsConfig = new Credential.Config({
        // Specifies the credential type.
        type: 'ram_role_arn',
        // Your AccessKey ID.
        accessKeyId: process.env.ALIBABA_CLOUD_ACCESS_KEY_ID,
        // Your AccessKey Secret.
        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 this by using the ALIBABA_CLOUD_ROLE_ARN environment variable.
        roleArn: '<RoleArn>',
        // A custom name for the role session. You can set this by using the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable.
        roleSessionName: '<RoleSessionName>',
        // Optional. An inline policy that limits the permissions for the RAM role. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}
        policy: '<Policy>',
        roleSessionExpiration: 3600,
    });
    const credentialClient = new Credential.default(credentialsConfig);
    const ecsConfig = new OpenApi.Config({
        endpoint: 'ecs.cn-hangzhou.aliyuncs.com', // The service endpoint.
        credential: credentialClient, // Specifies the credential to use.
    });
    const ecsClient = new Ecs20140526.default(ecsConfig);
    const describeRegionsRequest = new Ecs20140526.DescribeRegionsRequest();
    const runtime = new Util.RuntimeOptions();
    // Call the DescribeRegions operation.
    const response = ecsClient.describeRegionsWithOptions(describeRegionsRequest, runtime);
    console.log((await response).body.regions);
}
main().catch(console.error);
import Ecs20140526, * as $Ecs20140526 from '@alicloud/ecs20140526';
import Credential, { Config } from '@alicloud/credentials';
import OpenApi, * as $OpenApi from '@alicloud/openapi-client';
import Util, * as $Util from '@alicloud/tea-util';
export default class Client {
    static async main(): Promise<$Ecs20140526.DescribeRegionsResponse> {
        const credentialsConfig = new Config({
            type: 'ram_role_arn',
            accessKeyId: process.env.ALIBABA_CLOUD_ACCESS_KEY_ID,
            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 this by using the ALIBABA_CLOUD_ROLE_ARN environment variable.
            roleArn: '<RoleArn>',
            // A custom name for the role session. You can set this by using the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable.
            roleSessionName: '<RoleSessionName>',
            // Optional. An inline policy that limits the permissions for the RAM role. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}
            policy: '<Policy>',
            roleSessionExpiration: 3600,
        });
        const credentialClient = new Credential(credentialsConfig);
        let config = new $OpenApi.Config({
            credential: credentialClient, // Specifies the credential to use.
            endpoint: 'ecs.cn-hangzhou.aliyuncs.com', // The service endpoint.
        });
        let client = new Ecs20140526(config);
        let describeRegionsRequest = new $Ecs20140526.DescribeRegionsRequest({});
        let runtime = new $Util.RuntimeOptions({});
        return await client.describeRegionsWithOptions(describeRegionsRequest, runtime);
    }
}
const response = Client.main();
response.then(res => {
    console.log(res.body?.regions);
});

Yöntem 5: ECS örneği RAM rolü

Bir ECS örneğine veya esnek konteyner örneğine bir örnek RAM rolü ekleyin. Örnek üzerindeki uygulamalar daha sonra Credentials aracını kullanarak rol için otomatik olarak bir STS belirteci alabilir.

Varsayılan olarak, Credentials aracı ECS meta veri sunucusuna güvenlik sıkılaştırma modunda (IMDSv2) erişir. Bir hata oluşursa normal moda geri döner. Bu davranışı disableIMDSv1 parametresi veya ALIBABA_CLOUD_IMDSV1_DISABLE ortam değişkeni ile kontrol edin:

  • false (varsayılan): Başarısızlık durumunda normal moda geri döner.

  • true: Yalnızca güvenlik sıkılaştırma modunu kullanır ve başarısızlık durumunda bir özel durum oluşturur.

IMDSv2 desteği sunucunuzun yapılandırmasına bağlıdır.

Ortam değişkenini ALIBABA_CLOUD_ECS_METADATA_DISABLED=true olarak ayarlayarak ECS meta verileri üzerinden kimlik bilgisi erişimini de devre dışı bırakabilirsiniz.

Not
const Credential = require('@alicloud/credentials');
const credentialsConfig = new Credential.Config({
    type: 'ecs_ram_role',
    // Optional. The name of the ECS RAM role. If unspecified, the system retrieves it automatically. Specifying a name is recommended to reduce requests. This can also be set via the ALIBABA_CLOUD_ECS_METADATA environment variable.
    roleName: '<RoleName>',
    // Optional. Default: false. If true, enforces security hardening mode. If false, the system tries security hardening mode first, falling back to normal mode (IMDSv1) on failure.
    // disableIMDSv1: true,
});
const cred = new Credential.default(credentialsConfig);
import Credential, { Config } from '@alicloud/credentials';
const credentialsConfig = new Config({
    type: 'ecs_ram_role',
    // Optional. The name of the ECS RAM role. If unspecified, the system retrieves it automatically. Specifying a name is recommended to reduce requests. This can also be set via the ALIBABA_CLOUD_ECS_METADATA environment variable.
    roleName: '<RoleName>',
    // Optional. Default: false. If true, enforces security hardening mode. If false, the system tries security hardening mode first, falling back to normal mode (IMDSv1) on failure.
    // disableIMDSv1: true,
});
const credentialClient = new Credential(credentialsConfig);

API çağrısı

Bu örnekte ECS'nin DescribeRegions işlemi çağrılmaktadır. Kodu çalıştırmak için öncelikle ECS SDK öğesini yükleyin.

const Ecs20140526 = require('@alicloud/ecs20140526');
const OpenApi = require('@alicloud/openapi-client');
const Util = require('@alicloud/tea-util');
const Credential = require('@alicloud/credentials');
async function main() {
    const credentialsConfig = new Credential.Config({
        // The credential type.
        type: 'ecs_ram_role',
        // Optional. The name of the ECS RAM role. We recommend specifying this to reduce requests. If omitted, the system retrieves it automatically. You can also set the roleName parameter by using the ALIBABA_CLOUD_ECS_METADATA environment variable.
        roleName: '<RoleName>',
    });
    const credentialClient = new Credential.default(credentialsConfig);
    const ecsConfig = new OpenApi.Config({
        endpoint: 'ecs.cn-hangzhou.aliyuncs.com', // The service endpoint.
        credential: credentialClient, // The credential to use for authentication.
    });
    const ecsClient = new Ecs20140526.default(ecsConfig);
    const describeRegionsRequest = new Ecs20140526.DescribeRegionsRequest();
    const runtime = new Util.RuntimeOptions();
    // Call the DescribeRegions operation and obtain the response.
    const response = ecsClient.describeRegionsWithOptions(describeRegionsRequest, runtime);
    console.log((await response).body.regions);
}
main().catch(console.error);
import Ecs20140526, * as $Ecs20140526 from '@alicloud/ecs20140526';
import Credential, { Config } from '@alicloud/credentials';
import OpenApi, * as $OpenApi from '@alicloud/openapi-client';
import Util, * as $Util from '@alicloud/tea-util';
export default class Client {
    static async main(): Promise<$Ecs20140526.DescribeRegionsResponse> {
        const credentialsConfig = new Config({
            type: 'ecs_ram_role',
            // Optional. The name of the ECS RAM role. We recommend specifying this to reduce requests. If omitted, the system retrieves it automatically. You can also set the roleName parameter by using the ALIBABA_CLOUD_ECS_METADATA environment variable.
            roleName: '<RoleName>',
            // Optional. Defaults to `false`. Setting this to `true` enforces security hardening mode. If this parameter is set to false, the system first attempts to get credentials in security hardening mode and falls back to normal mode (IMDSv1) if the attempt fails.
            // disableIMDSv1: true,
        });
        const credentialClient = new Credential(credentialsConfig);
        let config = new $OpenApi.Config({
            credential: credentialClient, // The credential to use for authentication.
            endpoint: 'ecs.cn-hangzhou.aliyuncs.com', // The service endpoint.
        });
        let client = new Ecs20140526(config);
        let describeRegionsRequest = new $Ecs20140526.DescribeRegionsRequest({});
        let runtime = new $Util.RuntimeOptions({});
        return await client.describeRegionsWithOptions(describeRegionsRequest, runtime);
    }
}
const response = Client.main();
response.then(res => {
    console.log(res.body?.regions);
});

Yöntem 6: OIDCRoleArn kullanma

OIDC kullanıyorsanız ve bir OIDC sağlayıcısı için RAM rolü oluşturduysanız, Credentials SDK'sına bir OIDC sağlayıcı ARN, bir OIDC belirteci ve bir RAM rolü ARN iletin. SDK, bir STS belirteci almak için AssumeRoleWithOIDC işlemini çağırır. Bu kimlik bilgileri otomatik yenilemeyi destekler. Oturum kimlik bilgileri için otomatik yenileme mekanizması. Örneğin, RRSA özelliği etkinleştirilmiş bir ACK kümesinde SDK, OIDC yapılandırmasını Pod ortam değişkenlerinden okur ve Alibaba Cloud hizmetlerine erişmek için bir STS belirteci alır.

const Credential = require('@alicloud/credentials');
const credentialsConfig = new Credential.Config({
    type: 'oidc_role_arn',
    // The RAM role ARN to assume. You can also set this using the ALIBABA_CLOUD_ROLE_ARN environment variable.
    roleArn: '<RoleArn>',
    // The OIDC IdP ARN. You can also set this using the ALIBABA_CLOUD_OIDC_PROVIDER_ARN environment variable.
    oidcProviderArn: '<OidcProviderArn>',
    // The OIDC token file path. You can also set this using the ALIBABA_CLOUD_OIDC_TOKEN_FILE environment variable.
    oidcTokenFilePath: '<OidcTokenFilePath>',
    // A custom role session name. You can also set this using the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable.
    roleSessionName: '<RoleSessionName>',
    // Optional. A policy to scope down the permissions for the session. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}
    policy: '<Policy>',
    // The session duration in seconds.
    roleSessionExpiration: 3600,
});
const credentialClient = new Credential.default(credentialsConfig);
import Credential, { Config } from '@alicloud/credentials';
const credentialsConfig = new Config({
    type: 'oidc_role_arn',
    // The RAM role ARN to assume. You can also set this using the ALIBABA_CLOUD_ROLE_ARN environment variable.
    roleArn: '<RoleArn>',
    // The OIDC IdP ARN. You can also set this using the ALIBABA_CLOUD_OIDC_PROVIDER_ARN environment variable.
    oidcProviderArn: '<OidcProviderArn>',
    // The OIDC token file path. You can also set this using the ALIBABA_CLOUD_OIDC_TOKEN_FILE environment variable.
    oidcTokenFilePath: '<OidcTokenFilePath>',
    // A custom role session name. You can also set this using the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable.
    roleSessionName: '<RoleSessionName>',
    // Optional. A policy to scope down the permissions for the session. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}
    policy: '<Policy>',
    // The session duration in seconds.
    roleSessionExpiration: 3600,
});
const credentialClient = new Credential(credentialsConfig);

API çağrısı

Bu örnekte ECS'nin DescribeRegions işlemi nasıl çağrılacağı gösterilmektedir. Kodu çalıştırmak için ECS SDK öğesini yükleyin.

const Ecs20140526 = require('@alicloud/ecs20140526');
const OpenApi = require('@alicloud/openapi-client');
const Util = require('@alicloud/tea-util');
const Credential = require('@alicloud/credentials');
async function main() {
    const credentialsConfig = new Credential.Config({
        // The credential type.
        type: 'oidc_role_arn',
        // The ARN of the RAM role to assume. You can also set this using the ALIBABA_CLOUD_ROLE_ARN environment variable.
        roleArn: '<RoleArn>',
        // The ARN of the OIDC provider. You can also set this using the ALIBABA_CLOUD_OIDC_PROVIDER_ARN environment variable.
        oidcProviderArn: '<OidcProviderArn>',
        // The OIDC token file path. You can also set this using the ALIBABA_CLOUD_OIDC_TOKEN_FILE environment variable.
        oidcTokenFilePath: '<OidcTokenFilePath>',
        // A custom role session name. You can also set this using the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable.
        roleSessionName: '<RoleSessionName>',
        // Optional. A policy that limits the permissions for the session. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}
        policy: '<Policy>',
        // The session expiration in seconds.
        roleSessionExpiration: 3600,
    });
    const credentialClient = new Credential.default(credentialsConfig);
    const ecsConfig = new OpenApi.Config({
        endpoint: 'ecs.cn-hangzhou.aliyuncs.com', // The service endpoint.
        credential: credentialClient, // The authentication credential.
    });
    const ecsClient = new Ecs20140526.default(ecsConfig);
    const describeRegionsRequest = new Ecs20140526.DescribeRegionsRequest();
    const runtime = new Util.RuntimeOptions();
    // Call the DescribeRegions operation.
    const response = ecsClient.describeRegionsWithOptions(describeRegionsRequest, runtime);
    console.log((await response).body.regions);
}
main().catch(console.error);
import Ecs20140526, * as $Ecs20140526 from '@alicloud/ecs20140526';
import Credential, { Config } from '@alicloud/credentials';
import OpenApi, * as $OpenApi from '@alicloud/openapi-client';
import Util, * as $Util from '@alicloud/tea-util';
export default class Client {
    static async main(): Promise<$Ecs20140526.DescribeRegionsResponse> {
        const credentialsConfig = new Config({
            type: 'oidc_role_arn',
            // The ARN of the RAM role to assume. You can also set this using the ALIBABA_CLOUD_ROLE_ARN environment variable.
            roleArn: '<RoleArn>',
            // The ARN of the OIDC provider. You can also set this using the ALIBABA_CLOUD_OIDC_PROVIDER_ARN environment variable.
            oidcProviderArn: '<OidcProviderArn>',
            // The OIDC token file path. You can also set this using the ALIBABA_CLOUD_OIDC_TOKEN_FILE environment variable.
            oidcTokenFilePath: '<OidcTokenFilePath>',
            // A custom role session name. You can also set this using the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable.
            roleSessionName: '<RoleSessionName>',
            // Optional. A policy that limits the permissions for the session. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}
            policy: '<Policy>',
            // The session expiration in seconds.
            roleSessionExpiration: 3600,
        });
        const credentialClient = new Credential(credentialsConfig);
        let config = new $OpenApi.Config({
            credential: credentialClient, // The authentication credential.
            endpoint: 'ecs.cn-hangzhou.aliyuncs.com', // The service endpoint.
        });
        let client = new Ecs20140526(config);
        let describeRegionsRequest = new $Ecs20140526.DescribeRegionsRequest({});
        let runtime = new $Util.RuntimeOptions({});
        return await client.describeRegionsWithOptions(describeRegionsRequest, runtime);
    }
}
const response = Client.main();
response.then(res => {
    console.log(res.body?.regions);
});

Yöntem 7: URI kimlik bilgisi

STS hizmetini bir URI aracılığıyla dışa aktararak harici hizmetlerin AccessKey çiftleriyle doğrudan uğraşmadan bir STS belirteci almasını sağlayın. Credentials aracı, belirtilen URI'den bir STS belirteci alır ve bunu otomatik yenileme desteğiyle birlikte bir erişim kimlik bilgisi olarak kullanır. Oturum tipi kimlik bilgileri için otomatik yenileme mekanizması.

const Credential = require('@alicloud/credentials');
const config = new Credential.Config({
    type: 'credentials_uri',
    // The endpoint to retrieve credentials, for example, http://local_or_remote_uri/. This can also be set with the ALIBABA_CLOUD_CREDENTIALS_URI environment variable.
    credentialsURI: '<CredentialsUri>',
});
const credentialClient = new Credential(config);
import Credential, { Config } from '@alicloud/credentials';
const credentialsConfig = new Config({
    type: 'credentials_uri',
    // The endpoint to retrieve credentials, for example, http://local_or_remote_uri/. This can also be set with the ALIBABA_CLOUD_CREDENTIALS_URI environment variable.
    credentialsURI: '<CredentialsUri>',
});
const credentialClient = new Credential(credentialsConfig);

URI yanıtı şu gereksinimleri karşılamalıdır:

  • Durum kodu 200'dür.

  • Yanıt gövdesi formatı:

    {
      "Code": "Success",
      "AccessKeySecret": "AccessKeySecret",
      "AccessKeyId": "AccessKeyId",
      "Expiration": "2021-09-26T03:46:38Z",
      "SecurityToken": "SecurityToken"
    }

API çağrısı

Bu örnekte ECS'nin DescribeRegions işlemi nasıl çağrılacağı gösterilmektedir. Kodu çalıştırmadan önce ECS SDK öğesini yükleyin.

const Ecs20140526 = require('@alicloud/ecs20140526');
const OpenApi = require('@alicloud/openapi-client');
const Util = require('@alicloud/tea-util');
const Credential = require('@alicloud/credentials');
async function main() {
    const credentialsConfig = new Credential.Config({
        // The credential type.
        type: 'credentials_uri',
        // The URI for obtaining the credential, formatted as http://local_or_remote_uri/. Alternatively, set the ALIBABA_CLOUD_CREDENTIALS_URI environment variable.
        credentialsURI: '<CredentialsUri>',
    });
    const credentialClient = new Credential.default(credentialsConfig);
    const ecsConfig = new OpenApi.Config({
        endpoint: 'ecs.cn-hangzhou.aliyuncs.com', // The service endpoint.
        credential: credentialClient, // The credential client for authentication.
    });
    const ecsClient = new Ecs20140526.default(ecsConfig);
    const describeRegionsRequest = new Ecs20140526.DescribeRegionsRequest();
    const runtime = new Util.RuntimeOptions();
    // Calls the DescribeRegions operation.
    const response = ecsClient.describeRegionsWithOptions(describeRegionsRequest, runtime);
    console.log((await response).body.regions);
}
main().catch(console.error);
import Ecs20140526, * as $Ecs20140526 from '@alicloud/ecs20140526';
import Credential, { Config } from '@alicloud/credentials';
import OpenApi, * as $OpenApi from '@alicloud/openapi-client';
import Util, * as $Util from '@alicloud/tea-util';
export default class Client {
    static async main(): Promise<$Ecs20140526.DescribeRegionsResponse> {
        let credentialsConfig = new Config({
            type: 'credentials_uri',
            // The URI for obtaining the credential, formatted as http://local_or_remote_uri/. Alternatively, set the ALIBABA_CLOUD_CREDENTIALS_URI environment variable.
            credentialsURI: '<CredentialsUri>',
        });
        let credentialClient = new Credential(credentialsConfig);
        let config = new $OpenApi.Config({
            credential: credentialClient, // The credential client for authentication.
            endpoint: 'ecs.cn-hangzhou.aliyuncs.com', // The service endpoint.
        });
        let client = new Ecs20140526(config);
        let describeRegionsRequest = new $Ecs20140526.DescribeRegionsRequest({});
        let runtime = new $Util.RuntimeOptions({});
        return await client.describeRegionsWithOptions(describeRegionsRequest, runtime);
    }
}
const response = Client.main();
response.then(res => {
    console.log(res.body?.regions);
});

Yöntem 8: Bearer belirteci kullanma

Şu anda yalnızca Alibaba Cloud Call Center (CCC) bearer belirteci kimlik doğrulamasını desteklemektedir.

const Credential = require('@alicloud/credentials');
const config = new Credential.Config({
    type: 'bearer',
    // Replace with your bearer token.
    bearerToken: '<BearerToken>',
});
const credentialClient = new Credential(config);
import Credential, { Config } from '@alicloud/credentials';
const credentialsConfig = new Config({
    type: 'bearer',
    // Replace with your bearer token.
    bearerToken: '<BearerToken>',
});
const credentialClient = new Credential(credentialsConfig);

API çağrısı

Bu örnekte Cloud Call Center (CCC) hizmetinin GetInstance işlemi nasıl çağrılacağı gösterilmektedir. Kodu çalıştırmak için Cloud Call Center SDK öğesini yükleyin.

const CCC20200701 = require('@alicloud/ccc20200701');
const OpenApi = require('@alicloud/openapi-client');
const Util = require('@alicloud/tea-util');
const Credential = require('@alicloud/credentials');
async function main() {
    let credentialsConfig = new Credential.Config({
        // The credential type.
        type: 'bearer',
        // Specify your bearer token.
        bearerToken: '<BearerToken>',
    });
    let credentialClient = new Credential.default(credentialsConfig);
    let config = new OpenApi.Config({
        endpoint: 'ccc.cn-shanghai.aliyuncs.com',
        credential: credentialClient
    });
    let client = new CCC20200701.default(config);
    let getInstanceRequest = new CCC20200701.GetInstanceRequest({
        instanceId: 'ccc-test',
    });
    let runtime = new Util.RuntimeOptions({});
    let response = client.getInstanceWithOptions(getInstanceRequest, runtime);
    console.log((await response).body);
}
main().catch(console.error);
import ccc20200701, * as $ccc20200701 from '@alicloud/ccc20200701';
import Credential, { Config } from '@alicloud/credentials';
import OpenApi, * as $OpenApi from '@alicloud/openapi-client';
import Util, * as $Util from '@alicloud/tea-util';
export default class Client {
    static async main(): Promise<$ccc20200701.GetInstanceResponse> {
        let credentialsConfig = new Config({
            type: 'bearer',
            // Specify your bearer token.
            bearerToken: '<BearerToken>',
        });
        let credentialClient = new Credential(credentialsConfig);
        let config = new $OpenApi.Config({
            credential: credentialClient, // Specify the credential.
            endpoint: 'ccc.cn-shanghai.aliyuncs.com', // Specify the endpoint.
        });
        let client = new ccc20200701(config);
        let GetInstanceRequest = new $ccc20200701.GetInstanceRequest({
            instanceId: 'ccc-test',
        });
        let runtime = new $Util.RuntimeOptions({});
        return await client.getInstanceWithOptions(GetInstanceRequest, runtime);
    }
}
let response = Client.main();
response.then(res => {
    console.log(res.body?.regions);
});

Varsayılan kimlik bilgisi sağlayıcı zinciri

Varsayılan kimlik bilgisi sağlayıcı zinciri, aynı kodu farklı ortamlarda kullanmanıza ve kimlik bilgisi alımını harici yapılandırma yoluyla kontrol etmenize olanak tanır. Parametre belirtmeden new Credential() çağırdığınızda SDK kimlik bilgilerini aşağıdaki sırayla arar.

1. Ortam değişkenlerini kullanma

Sistem özelliklerinde kimlik bilgisi bulunamazsa sağlayıcı zinciri ortam değişkenlerini kontrol eder.

  • Hem ALIBABA_CLOUD_ACCESS_KEY_ID hem de ALIBABA_CLOUD_ACCESS_KEY_SECRET mevcut ve boş değilse sağlayıcı zinciri bunları varsayılan kimlik bilgisi olarak kullanır.

  • ALIBABA_CLOUD_ACCESS_KEY_ID, ALIBABA_CLOUD_ACCESS_KEY_SECRET ve ALIBABA_CLOUD_SECURITY_TOKEN da ayarlanmışsa sağlayıcı zinciri bir STS belirtecini varsayılan kimlik bilgisi olarak kullanır.

2. OIDC RAM rolleri

Kimlik bilgisi bulunamadıysa sağlayıcı zinciri, bir OIDC RAM rolüyle ilgili aşağıdaki ortam değişkenlerini kontrol eder:

  • ALIBABA_CLOUD_ROLE_ARN: RAM rolünün ARN değeri.

  • ALIBABA_CLOUD_OIDC_PROVIDER_ARN: OIDC sağlayıcısının ARN değeri.

  • ALIBABA_CLOUD_OIDC_TOKEN_FILE: OIDC belirtecinin dosya yolu.

Üç ortam değişkeninin tamamı mevcut ve boş değilse sağlayıcı zinciri bu değerleri kullanarak Güvenlik Belirteci Hizmeti'nin (STS) AssumeRoleWithOIDC API'sini çağırır ve bir STS belirteci alır.

3. Config.json

Kimlik bilgisi bulunamadıysa sağlayıcı zinciri, varsayılan konumundan paylaşılan kimlik bilgileri dosyası config.json dosyasını yüklemeye çalışır ve dosyada belirtilen kimlik bilgisini kullanır.

  • Linux/macOS: ~/.aliyun/config.json

  • Windows: C:\Users\USER_NAME\.aliyun\config.json

Bu şekilde bir kimlik bilgisi yapılandırmak için Alibaba Cloud CLI aracını kullanabilir veya uygun yolda manuel olarak bir config.json dosyası oluşturabilirsiniz. Aşağıdaki örnek içerik formatını göstermektedir:

{
  "current": "<PROFILE_NAME>",
  "profiles": [
    {
      "name": "<PROFILE_NAME>",
      "mode": "AK",
      "access_key_id": "<ALIBABA_CLOUD_ACCESS_KEY_ID>",
      "access_key_secret": "<ALIBABA_CLOUD_ACCESS_KEY_SECRET>"
    },
    {
      "name": "<PROFILE_NAME1>",
      "mode": "StsToken",
      "access_key_id": "<ALIBABA_CLOUD_ACCESS_KEY_ID>",
      "access_key_secret": "<ALIBABA_CLOUD_ACCESS_KEY_SECRET>",
      "sts_token": "<SECURITY_TOKEN>"
    },
    {
      "name":"<PROFILE_NAME2>",
      "mode":"RamRoleArn",
      "access_key_id":"<ALIBABA_CLOUD_ACCESS_KEY_ID>",
      "access_key_secret":"<ALIBABA_CLOUD_ACCESS_KEY_SECRET>",
      "ram_role_arn":"<ROLE_ARN>",
      "ram_session_name":"<ROLE_SESSION_NAME>",
      "expired_seconds":3600
    },
    {
      "name":"<PROFILE_NAME3>",
      "mode":"EcsRamRole",
      "ram_role_name":"<RAM_ROLE_ARN>"
    },
    {
      "name":"<PROFILE_NAME4>",
      "mode":"OIDC",
      "oidc_provider_arn":"<OIDC_PROVIDER_ARN>",
      "oidc_token_file":"<OIDC_TOKEN_FILE>",
      "ram_role_arn":"<ROLE_ARN>",
      "ram_session_name":"<ROLE_SESSION_NAME>",
      "expired_seconds":3600
    },
    {
      "name":"<PROFILE_NAME5>",
      "mode":"ChainableRamRoleArn",
      "source_profile":"<PROFILE_NAME>",
      "ram_role_arn":"<ROLE_ARN>",
      "ram_session_name":"<ROLE_SESSION_NAME>",
      "expired_seconds":3600
    }
  ]
}

Parametre

Açıklama

current

İlgili kimlik bilgisi yapılandırmasını almak için kimlik bilgisi adını belirtin. Kimlik bilgisi adı, name parametresinin profiles içindeki değeridir. Varsayılan olarak sistem, ALIBABA_CLOUD_PROFILE ortam değişkeni tarafından belirtilen kimlik bilgisi adına öncelik verir. Bu ortam değişkeni yapılandırılmamışsa sistem current tarafından belirtilen kimlik bilgisi adını kullanır.

profiles

Kimlik bilgisi yapılandırmalarının bir koleksiyonunu içerir. mode parametresi kimlik bilgisi türünü belirtir:

  • AK: Bir RAM kullanıcısının AccessKey bilgisini kimlik bilgisi olarak kullanır.

  • StsToken: Bir STS belirtecini kimlik bilgisi olarak kullanır.

  • RamRoleArn: Geçici bir kimlik bilgisi elde etmek için bir RAM kullanıcısının kimlik bilgilerini kullanarak bir RAM rolünü üstlenir.

  • EcsRamRole: Örnek meta verilerinden bir kimlik bilgisi alır.

  • OIDC: Bir OIDC sağlayıcı ARN, bir OIDC belirteci ve bir RAM rolü ARN kullanarak bir kimlik bilgisi alır.

  • ChainableRamRoleArn: profiles içindeki ve source_profile parametresiyle belirtilen başlangıç kimlik bilgisini kullanarak rol zincirleme yoluyla yeni bir kimlik bilgisi elde eder.

4. ECS örneği RAM rolü

Daha yüksek önceliğe sahip kimlik bilgileri bulunamazsa SDK kimlik bilgilerini ECS örneği RAM rolünden alır. Bir STS belirteci almak için geliştirilmiş modda (IMDSv2) örnek meta veri hizmetine erişir. Bu işlem iki istek gerektirir: biri rol adı için, diğeri kimlik bilgileri için. İsteği tek bir isteme indirmek için rol adını ALIBABA_CLOUD_ECS_METADATA ortam değişkeninde ayarlayın. Geliştirilmiş mod başarısız olursa süreç normal moda geri döner. Bunu ALIBABA_CLOUD_IMDSV1_DISABLE ile kontrol edin:

  1. false: Başarısızlık durumunda normal moda geri döner.

  2. true: Yalnızca geliştirilmiş modu kullanır ve başarısızlık durumunda bir özel durum oluşturur.

IMDSv2 desteği örnek meta veri hizmeti yapılandırmanıza bağlıdır.

ECS örneği meta verilerinden kimlik bilgisi alımını devre dışı bırakmak için ALIBABA_CLOUD_ECS_METADATA_DISABLED=true ayarlayın.

Not

5. Kimlik Bilgisi URI

Kimlik bilgisi bulunamadıysa sağlayıcı zinciri ALIBABA_CLOUD_CREDENTIALS_URI ortam değişkenini kontrol eder. Bu değişken ayarlanmışsa ve geçerli bir URI'yi işaret ediyorsa zincir bir STS belirteci almak için URI'ye erişir.

Oturum kimlik bilgileri için otomatik yenileme

Oturum kimlik bilgileri (ram_role_arn, ecs_ram_role, oidc_role_arn ve credentials_uri) yerleşik otomatik yenileme özelliği içerir. İlk alım sırasında kimlik bilgileri aracı kimlik bilgisini önbelleğe alır. Sonraki istekler, kimlik bilgisi sona erene kadar önbelleğe alınmış değeri döndürür; bu noktada yeni bir kimlik bilgisi otomatik olarak alınır.

Not

ecs_ram_role kimlik bilgileri için kimlik bilgileri aracı, sona ermelerinden 15 dakika önce proaktif olarak yeniler.

Aşağıdaki örnek, otomatik yenilemeyi doğrulamak için farklı aralıklarla kimlik bilgilerini alan ve geçerliliğini bir OpenAPI çağrısı aracılığıyla teyit eden singleton desenini kullanarak bir kimlik bilgisi istemcisi oluşturur.

const Credential = require('@alicloud/credentials');
const Ecs20140526 = require('@alicloud/ecs20140526');
const { Config } = require('@alicloud/openapi-client');
const { RuntimeOptions } = require('@alicloud/tea-util');
// Obtain environment variables.
const accessKeyId = process.env.ALIBABA_CLOUD_ACCESS_KEY_ID;
const accessKeySecret = process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET;
const roleArn = process.env.ALIBABA_CLOUD_ROLE_ARN;
/**
 * The Credential singleton class manages Alibaba Cloud credential instances.
 */
class CredentialClient {
    constructor() {
        if (!CredentialClient.instance) {
            var credentialsConfig = new Credential.Config({
                type: 'ram_role_arn',
                accessKeyId: accessKeyId,
                accessKeySecret: accessKeySecret,
                roleArn: roleArn,
                roleSessionName: 'RoleSessionNameTest',
                roleSessionExpiration: 3600,
            });
            this.credentialsClient = new Credential.default(credentialsConfig);
            CredentialClient.instance = this;
        }
        return CredentialClient.instance;
    }
    static getInstance() {
        return new CredentialClient().credentialsClient;
    }
}
/**
 * The ECS Client singleton class manages ECS client instances.
 */
class EcsClient {
    constructor(credentialClient) {
        if (!EcsClient.instance) {
            const config = new Config({
                endpoint: 'ecs.cn-hangzhou.aliyuncs.com',
                credential: credentialClient
            });
            this.ecsClient = new Ecs20140526.default(config);
            EcsClient.instance = this;
        }
        return EcsClient.instance;
    }
    static getInstance(credentialClient) {
        return new EcsClient(credentialClient).ecsClient;
    }
}
/**
 * Execute the task logic.
 */
async function executeTask() {
    try {
        const credentialClient = CredentialClient.getInstance();
        const credential = await credentialClient.getCredential();
        console.log(new Date());
        console.log(`AK ID: ${credential.accessKeyId}`);
        console.log(`AK Secret: ${credential.accessKeySecret}`);
        console.log(`STS Token: ${credential.securityToken}`);
        // This example calls an ECS API operation to verify the credential's validity. Modify this as needed.
        const ecsClient = EcsClient.getInstance(credentialClient);
        const request = new Ecs20140526.DescribeRegionsRequest();
        const runtime = new RuntimeOptions({});
        const response = await ecsClient.describeRegionsWithOptions(request, runtime);
        console.log(`Invoke result: ${response.statusCode}`);
    } catch (error) {
        throw new Error(`ECS client execution failed: ${error.message}`, { cause: error });
    }
}
/**
 * Schedule task execution by using a timer.
 */
function scheduleTasks() {
    // Immediately run the task once.
    executeTask();
    // Set a delay for subsequent tasks.
    setTimeout(executeTask, 600 * 1000); // Second run: after 600 seconds.
    setTimeout(executeTask, 4200 * 1000); // Third run: after 4,200 seconds.
    setTimeout(executeTask, 4300 * 1000); // Fourth run: after 4,300 seconds.
}
// Start task scheduling.
scheduleTasks();
import Credential, { Config as CredentialsConfig }  from '@alicloud/credentials';
import Ecs20140526, * as $Ecs20140526 from '@alicloud/ecs20140526';
import { Config } from '@alicloud/openapi-client';
import { RuntimeOptions } from '@alicloud/tea-util';
// Obtain environment variables.
const accessKeyId: string | undefined = process.env.ALIBABA_CLOUD_ACCESS_KEY_ID;
const accessKeySecret: string | undefined = process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET;
const roleArn: string | undefined = process.env.ALIBABA_CLOUD_ROLE_ARN;
if (!accessKeyId || !accessKeySecret || !roleArn) {
    throw new Error('Missing required environment variables.');
}
/**
 * The Credential singleton class manages Alibaba Cloud credential instances.
 */
class CredentialClient {
    private static instance: CredentialClient;
    private readonly credentialsClient: InstanceType<typeof Credential>;
    private constructor() {
        const credentialsConfig = new CredentialsConfig({
            type: 'ram_role_arn',
            accessKeyId,
            accessKeySecret,
            roleArn,
            roleSessionName: 'RoleSessionNameTest',
            roleSessionExpiration: 3600,
        });
        this.credentialsClient = new Credential(credentialsConfig);
    }
    static getInstance(): InstanceType<typeof Credential> {
        if (!CredentialClient.instance) {
            CredentialClient.instance = new CredentialClient();
        }
        return CredentialClient.instance.credentialsClient;
    }
}
/**
 * The ECS Client singleton class manages ECS client instances.
 */
class EcsClient {
    private static instance: EcsClient;
    private readonly ecsClient: InstanceType<typeof Ecs20140526>;
    private constructor(credentialClient: InstanceType<typeof Credential>) {
        const config = new Config({
            endpoint: 'ecs.cn-hangzhou.aliyuncs.com',
            credential: credentialClient
        });
        this.ecsClient = new Ecs20140526(config);
    }
    static getInstance(credentialClient: InstanceType<typeof Credential>): InstanceType<typeof Ecs20140526> {
        if (!EcsClient.instance) {
            EcsClient.instance = new EcsClient(credentialClient);
        }
        return EcsClient.instance.ecsClient;
    }
}
/**
 * Execute the task logic.
 */
async function executeTask(): Promise<void> {
    try {
        const credentialClient = CredentialClient.getInstance();
        const credential = await credentialClient.getCredential();
        console.log(new Date());
        console.log(`AK ID: ${credential.accessKeyId}`);
        console.log(`AK Secret: ${credential.accessKeySecret}`);
        console.log(`STS Token: ${credential.securityToken}`);
        // This example calls an ECS API operation to verify the credential's validity. Modify this as needed.
        const ecsClient = EcsClient.getInstance(credentialClient);
        const request = new $Ecs20140526.DescribeRegionsRequest();
        const runtime = new RuntimeOptions({});
        const response = await ecsClient.describeRegionsWithOptions(request, runtime);
        console.log(`Invoke result: ${response.statusCode}`);
    } catch (error) {
        throw new Error(`ECS client execution failed: ${error}`);
    }
}
/**
 * Schedule task execution by using a timer.
 */
function scheduleTasks(): void {
    // Immediately run the task once.
    executeTask();
    // Set a delay for subsequent tasks.
    setTimeout(executeTask, 600 * 1000); // Second run: after 600 seconds.
    setTimeout(executeTask, 4200 * 1000); // Third run: after 4,200 seconds.
    setTimeout(executeTask, 4300 * 1000); // Fourth run: after 4,300 seconds.
}
// Start task scheduling.
scheduleTasks();
2025-05-28T09:22:29.584Z
AK ID: STS.NVS9xxx7DRbao
AK Secret: 9SoQxxxmVjVsED9ad47rcgMaw5XyQyXx
STS Token:
CAISyQJ1q6Ft5B2yfSjIr5Xmcu/irrxq0pWvU0PZhvVtS7hovafKjTz2IHhMeXZoA+4YsPw2mmFW6/sdlrpJTJtIfkHfdsp36LJe9A6dbpHd4xc1LGed0s/LI3OaLjKm9u2wCryLYbGwU/OpbE++5U0X6LDmdDKkckW40JmS8/BOZcgWWQ/KB1gvRq
0hRG1YpdQdKGHa0xxxWg0/ks0aH1war1bBL+tqofMP9MfMBZskvD42Hu8VtbbfE3SJq7BxHybx71qQs+02c5onAXAELvUvYa7OKo4MyCVBjBKEhALNBoeL7kfBobmFAAkgwYnynVMMisES3LOiIqKOsk1MdI9Cywly2y
vfiZZ1prmk1pV68xxxczc4yvhD2nuNe7rmc9Z3/JHusVmo7LiTxqAARdkoKCeYBvLk0ZFWccCiM0ZvdnRtv0VDOUfD1zQELQGL+xB5NrBmdzq2ePjFJbrkBGmy5EXD714jknyzM4lFic2dUQMi14NCHMVDVjGAf0qUs
F+PQW58jGb32fmFxxxTXOx82sdRQqW0/vTd2KQmIAA=
Invoke result: 200
2025-05-28T09:32:28.137Z
AK ID: STS.NVS9xxx7DRbao
AK Secret: 9SoQxxxmVjVsED9ad47rcgMaw5XyQyXx
STS Token:
CAISyQJ1q6Ft5B2yfSjIr5Xmcu/irrxq0pWvU0PZhvVtS7hovafKjTz2IHhMeXZoA+4YsPw2mmFW6/sdlrpJTJtIfkHfdsp36LJe9A6dbpHd4xc1LGed0s/LI3OaLjKm9u2wCryLYbGwU/OpbE++5U0X6LDmdDKkckW40JmS8/BOZcgWWQ/KB1gvRq
0hRG1YpdQdKGHa0xxxWg0/ks0aH1war1bBL+tqofMP9MfMBZskvD42Hu8VtbbfE3SJq7BxHybx71qQs+02c5onAXAELvUvYa7OKo4MyCVBjBKEhALNBoeL7kfBobmFAAkgwYnynVMMisES3LOiIqKOsk1MdI9Cywly2y
vfiZZ1prmk1pV68xxxczc4yvhD2nuNe7rmc9Z3/JHusVmo7LiTxqAARdkoKCeYBvLk0ZFWccCiM0ZvdnRtv0VDOUfD1zQELQGL+xB5NrBmdzq2ePjFJbrkBGmy5EXD714jknyzM4lFic2dUQMi14NCHMVDVjGAf0qUs
F+PQW58jGb32fmFxxxTXOx82sdRQqW0/vTd2KQmIAA=
Invoke result: 200
2025-05-28T10:32:29.771Z
AK ID: STS.NVuaxxxLFiPw8
AK Secret: 5dsoxxxpA5pCzfrek4KforS8MnJ6qHR9
STS Token:
CAISyQJ1q6Ft5B2yfSjIr5XAKsjd241w4PqgY1P2gDUvb8NqhpXc2jz2IHhMeXZoA+4YsPw2mmFW6/sdlrpJTJtIfkHfdsp36LJe9A6dbpHd4yVKL2Gd0s/LI3OaLjKm9u2wCryLYbGwU/OpbE++5U0X6LDmdDKkckW40JmS8/BOZcgWWQ/KB1gvRq
0hRG1YpdQdKGHa0xxxWg0/ks0aH1war1bBL+tqofMP9MfMBZskvD42Hu8VtbbfE3SJq7BxHybx71qQs+02c5onAXAELvUvYa7OKo4MyCVBjBKEhALNBoeL7kfBobmFAAkgwYnynVMMisES3LOjIqKOsk+Mdk9CiWv2y
vfiZZ1prmk1pV68xxxczc4yvhD2nuNe7rmc9Z3/KpUoQEo7LiTxqAAUyV7F+kpLHRG/yHw3JaVz14hqSj2hmxxkwgczUWIkpBLKHLeW0iI3sp2LNQO6iEAImLpSE0nRVBbcutIqxEuFzAs607jgOjHakTF7UZNoKVV
wb42xR4s4ThGd2PxxxqoUsrKfCq5lHiUiDq6L1VIAA=
Invoke result: 200
2025-05-28T10:34:08.130Z
AK ID: STS.NVuaxxxLFiPw8
AK Secret: 5dsoxxxpA5pCzfrek4KforS8MnJ6qHR9
STS Token:
CAISyQJ1q6Ft5B2yfSjIr5XAKsjd241w4PqgY1P2gDUvb8NqhpXc2jz2IHhMeXZoA+4YsPw2mmFW6/sdlrpJTJtIfkHfdsp36LJe9A6dbpHd4yVKL2Gd0s/LI3OaLjKm9u2wCryLYbGwU/OpbE++5U0X6LDmdDKkckW40JmS8/BOZcgWWQ/KB1gvRq
0hRG1YpdQdKGHa0xxxWg0/ks0aH1war1bBL+tqofMP9MfMBZskvD42Hu8VtbbfE3SJq7BxHybx71qQs+02c5onAXAELvUvYa7OKo4MyCVBjBKEhALNBoeL7kfBobmFAAkgwYnynVMMisES3LOjIqKOsk+Mdk9CiWv2y
vfiZZ1prmk1pV68xxxczc4yvhD2nuNe7rmc9Z3/KpUoQEo7LiTxqAAUyV7F+kpLHRG/yHw3JaVz14hqSj2hmxxkwgczUWIkpBLKHLeW0iI3sp2LNQO6iEAImLpSE0nRVBbcutIqxEuFzAs607jgOjHakTF7UZNoKVV
wb42xR4s4ThGd2PxxxqoUsrKfCq5lHiUiDq6L1VIAA=
Invoke result: 200

Günlük çıktısına dayalı analiz:

  • İlk çağrıda önbellek boştur. Sistem yapılandırmanıza göre bir kimlik bilgisi alır ve ardından bunu önbelleğe kaydeder.

  • İkinci çağrı, ilk çağrıyla aynı kimlik bilgisini kullanır; bu, bilginin önbellekten alındığını gösterir.

  • Üçüncü çağrıda önbelleğe alınan kimlik bilgisi süresi dolmuştur. Süre sonu (RoleSessionExpiration) 3.600 saniyedir ancak bu çağrı ilk çağrıdan 4.200 saniye sonra yapılır. Sonuç olarak, SDK'nın otomatik yenileme mekanizması yeni bir kimlik bilgisi alır ve önbelleği günceller.

  • Dördüncü çağrı, üçüncü çağrıyla aynı kimlik bilgisini kullanır; bu, önbelleğin güncellendiğini doğrular.

İlgili belgeler