Skip to content

Latest commit

 

History

History
118 lines (83 loc) · 2.61 KB

File metadata and controls

118 lines (83 loc) · 2.61 KB

OIDC authentication sample w typescript

Node.JS Typescript sample set up to use OIDC authentication.

Getting Started

This kind of authentication will log you with the OIDC method.

Prerequisite

Make sure you have read the prerequisite-guide before continuing.

Install

Go to this folder in your terminal and run:

npm install

or with yarn:

yarn

Run

AZURE_TENANT_ID=... COGNITE_PROJECT=... CLIENT_ID=... CLIENT_SECRET=... node build/quickstart.ts

How to get logged by yourself?

  1. 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
  1. Create a new file called quickstart.ts and import all necessary things.
import { CogniteClient } from '@cognite/sdk';
import { ConfidentialClientApplication } from '@azure/msal-node';
  1. 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!;
  1. 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);
    } //
}
  1. Call the quickstart function.
quickstart()
  .then(() => { process.exit(0); })
  .catch((err) => { console.error(err); process.exit(1); });
  1. Build your project.

npm run tsc

or with yarn

yarn tsc

  1. Finally, run your code with:
AZURE_TENANT_ID=... COGNITE_PROJECT=... CLIENT_ID=... CLIENT_SECRET=... node build/quickstart.js