Code integration
This topic describes how to integrate the IDaaS TypeScript SDK into a Node.js application to obtain M2M client tokens.
Scope
You have completed Environment preparation and have the configuration file, the credential source, and the authorization for the target scope ready. JavaScript applications use the same API.
Install the SDK
Install the Core SDK in your project directory. The following example uses 0.1.0-beta.2:
npm install --save-exact --registry=https://registry.npmjs.org/ @cloud-idaas/core-sdk@0.1.0-beta.2
SDK initialization
init() automatically reads and validates the configuration, and then obtains the initial credentials for the default scope. Without arguments, it reads the file specified by CLOUD_IDAAS_CONFIG_PATH, or ~/.cloud_idaas/client-config.json when that variable is not set. You can also pass an absolute file path or a configuration object.
The following snippet runs inside an async function. For complete usage, see the examples later in this topic:
const factory = new IDaaSCredentialProviderFactory();
await factory.init();
// Or: await factory.init('/absolute/path/to/client-config.json');
-
Initialization, provider retrieval, and token retrieval are all asynchronous. Use
awaitwhen you call them. -
Initialization fails if the configuration is invalid or the first credential retrieval fails. You can retry after the issue is fixed. A provider can be obtained only after initialization succeeds.
-
After initialization succeeds, calling
init()again keeps the existing configuration. Create a new factory to switch identities or replace the entire configuration. A closed factory cannot be reinitialized.
Get an access token
Obtain a provider from an initialized factory. The scope in the configuration file is used by default:
const provider = await factory.getIDaaSCredentialProvider();
const accessToken = await provider.getAccessToken();
You can also retrieve the complete credential object first and then read the token property:
const credential = await provider.getCredential();
const accessToken = credential.accessToken;
The access token is a bearer token. A scope joins the audience identifier and the permission identifier with a vertical bar, for example api.example.com|read:file. To access another authorized scope, call factory.getIDaaSCredentialProvider(scope). Reuse the factory and provider within your application, and close the factory after all related requests are complete.
Complete code example
Save the following TypeScript code as app.cts:
import {
IDaaSCredentialProviderFactory,
isIDaaSException,
} from '@cloud-idaas/core-sdk';
async function main(): Promise<void> {
const factory = new IDaaSCredentialProviderFactory();
try {
await factory.init();
const provider = await factory.getIDaaSCredentialProvider();
const accessToken = await provider.getAccessToken();
if (!accessToken) throw new Error('The token is empty.');
// Use accessToken in the Authorization: Bearer header of requests to the target resource.
// Do not print the token to logs.
console.log('SDK initialization and token retrieval succeeded.');
} finally {
// Long-running applications should close the factory once after all related requests are complete.
await factory.close();
}
}
main().catch((error: unknown) => {
console.error('The SDK call failed.', {
errorCode: isIDaaSException(error) ? error.errorCode : 'UnexpectedError',
});
process.exitCode = 1;
});
Install the build dependencies, compile, and run:
npm install --save-dev --save-exact --registry=https://registry.npmjs.org/ typescript@5.9.3 @types/node@20.17.0
npx tsc --module Node16 --moduleResolution Node16 --target ES2022 --strict --outDir dist app.cts
node dist/app.cjs
JavaScript applications use the same logic without type annotations. For ESM, use .mjs or set type=module in package.json. For CommonJS, use .cjs and change the import at the top to:
const { IDaaSCredentialProviderFactory, isIDaaSException } = require('@cloud-idaas/core-sdk');
Alibaba Cloud OpenAPI authentication (optional)
To use PLUGIN authentication, first install the plugin and configure the permissions, endpoint, and pluginName as described in Environment preparation. Add the following import at the top of your code:
import { AlibabaOpenApiCredentialProvider } from '@cloud-idaas/core-alibabacloud-authentication-plugin';
Replace the factory creation statement in the complete example with the following code. The remaining initialization and token retrieval logic stays the same:
const factory = new IDaaSCredentialProviderFactory({
plugins: [new AlibabaOpenApiCredentialProvider()],
});
The plugin must be registered before init() is called on the same factory. Each plugin authentication request can contain only one audience, and token exchange is not supported.
Token exchange
Token exchange (RFC 8693) exchanges a subject token trusted by the authorization server for an access token with a target scope. Use it for token downscoping and service-to-service calls.
Save the following example as exchange.cts. A trusted business process supplies a valid IDaaS user access token and injects it into the example through IDAAS_SUBJECT_TOKEN. This environment variable is a convention of the example, not a configuration field that the SDK reads automatically. Replace the target scope with an audience and permission that are actually authorized.
import {
IDaaSCredentialProviderFactory,
isIDaaSException,
} from '@cloud-idaas/core-sdk';
async function main(): Promise<void> {
const subjectToken = process.env.IDAAS_SUBJECT_TOKEN;
if (!subjectToken) throw new Error('The subject token for exchange is missing.');
const factory = new IDaaSCredentialProviderFactory();
try {
await factory.init();
const provider = await factory.getIDaaSCredentialProvider();
const credential = await provider.tokenExchange({
subjectToken,
subjectTokenType: 'urn:ietf:params:oauth:token-type:access_token',
scope: 'api.example.com|read:file',
});
const accessToken = credential.accessToken;
if (!accessToken) throw new Error('The exchanged token is empty.');
// Use accessToken in requests to the target resource. Do not print the token or the credential object.
console.log('Token exchange succeeded.');
} finally {
await factory.close();
}
}
main().catch((error: unknown) => {
console.error('Token exchange failed.', {
errorCode: isIDaaSException(error) ? error.errorCode : 'UnexpectedError',
});
process.exitCode = 1;
});
npx tsc --module Node16 --moduleResolution Node16 --target ES2022 --strict --outDir dist exchange.cts
node dist/exchange.cjs
Token exchange parameters
|
Parameter |
Type |
Required |
Description |
|
subjectToken |
string |
Yes |
The subject token to exchange. |
|
subjectTokenType |
string |
No |
Default value: |
|
requestedTokenType |
string |
No |
Default value: |
|
scope |
string |
No |
When omitted, the |
|
audience |
string |
No |
When explicitly specified, it must match the audience of the target |
In this release, token exchange accepts only trusted IDaaS user access tokens, the target scope contains only one audience, and actor-token delegation and resource extensions are not supported. The return value is a credential object. Read the token from credential.accessToken.
Exchange results are not written to the regular client_credentials cache, so subsequent getAccessToken() calls still return the regular token of the original provider. The application manages the usable lifetime of an exchange result based on expiresAt, which is in Unix seconds.