This is the flow used for Device Authorization Grant
Make sure you have read the prerequisite-guide before continuing.
Your application registration needs Allow public client flows
enabled for this flow to work.
Go to this folder in your terminal and run:
npm install
or with yarn:
yarn
AZURE_TENANT_ID=... COGNITE_PROJECT=... CLIENT_ID=... node build/device_grant.ts
- Add the Cognite SDK, open and @azure/msal-node to your project with yarn or npm.
yarn add @cognite/[email protected]
yarn add @azure/msal-node
yarn add open
npm install @cognite/[email protected]
npm install @azure/msal-node
npm install open
- Create a new file called
device_grant.ts
and import all necessary things.
import { CogniteClient } from '@cognite/sdk';
import { PublicClientApplication } from '@azure/msal-node';
import open from 'open';
- Instantiate three consts with your project name, clientID, and your tenantID.
const project: string = process.env.COGNITE_PROJECT!;
const clientId: string = process.env.CLIENT_ID!;
const azureTenant = process.env.AZURE_TENANT_ID!;
- Create a function called
deviceCodeGrantExample
with the following code:
async function deviceCodeGrantExample() {
const pca = new PublicClientApplication({
auth: {
clientId,
authority: `https://login.microsoftonline.com/${azureTenant}`,
},
});
const client = new CogniteClient({
appId: 'Cognite SDK samples',
project,
baseUrl: 'https://api.cognitedata.com',
getToken: () =>
pca
.acquireTokenByDeviceCode({
deviceCodeCallback: ({ message, userCode, verificationUri }) => {
open(verificationUri)
.then(() => console.log(`Enter ${userCode}`))
.catch(() => console.log(message));
},
scopes: ['https://api.cognitedata.com/.default'],
})
.then((response) => response?.accessToken!),
});
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
deviceCodeGrantExample
function.
deviceCodeGrantExample()
.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=... node build/device_grant.ts