Node.JS Typescript sample set up to use OIDC authentication.
This kind of authentication will log you with the OIDC method.
Make sure you have read the prerequisite-guide before continuing.
Go to this folder in your terminal and run:
npm install
or with yarn:
yarn
AZURE_TENANT_ID=... COGNITE_PROJECT=... CLIENT_ID=... CLIENT_SECRET=... node build/quickstart.ts
- Add the Cognite SDK and @azure/msal-node to your project with yarn or npm.
yarn add @cognite/[email protected]
yarn add @azure/msal-node
npm install @cognite/[email protected]
npm install @azure/msal-node
- Create a new file called
quickstart.ts
and import all necessary things.
import { CogniteClient } from '@cognite/sdk';
import { ConfidentialClientApplication } from '@azure/msal-node';
- Instantiate four consts with your project name, clientID, clientSecret and your tenantID.
const project: string = process.env.COGNITE_PROJECT!;
const clientId: string = process.env.CLIENT_ID!;
const clientSecret: string = process.env.CLIENT_SECRET!;
const azureTenant = process.env.AZURE_TENANT_ID!;
- Create a function called
quickstart
with the following code:
async function quickstart() {
const pca = new ConfidentialClientApplication({
auth: {
clientId,
clientSecret,
authority: `https://login.microsoftonline.com/${azureTenant}`,
},
});
const client = new CogniteClient({
appId: 'Cognite SDK samples',
project,
baseUrl: 'https://api.cognitedata.com',
oidcTokenProvider: () =>
pca
.acquireTokenByClientCredential({
scopes: ['https://api.cognitedata.com/.default'],
skipCache: true,
})
.then((response) => response?.accessToken! as string),
});
await client.authenticate();
const info = (await client.get('/api/v1/token/inspect')).data;
console.log('tokenInfo', JSON.stringify(info, null, 2));
try {
const assets = await client.assets.list();
console.log(assets);
} catch (e) {
console.log('asset error');
console.log(e);
} //
}
- Call the
quickstart
function.
quickstart()
.then(() => { process.exit(0); })
.catch((err) => { console.error(err); process.exit(1); });
- Build your project.
npm run tsc
or with yarn
yarn tsc
- Finally, run your code with:
AZURE_TENANT_ID=... COGNITE_PROJECT=... CLIENT_ID=... CLIENT_SECRET=... node build/quickstart.js