Solved

How to get CDF API Key

  • 21 February 2023
  • 3 replies
  • 103 views

Userlevel 1

While using cognite-sdk-dotnet, it needs API key whereas I have client-id and secret with me. How can I get the API key for the same? Or there is some alternative way to work with client-id and secret.

icon

Best answer by Everton Colling 22 February 2023, 13:04

View original

3 replies

Userlevel 2

Hi Mohit,

The .NET SDK supports setting a token provider, using `builder.SetTokenProvider`. In order to use this with client ID and client secret, the simplest solution might be to use the `Cognite.Extensions` package, see the bottom of this page for an example using just `Cognite.Extensions`: https://cognitedata.github.io/dotnet-extractor-utils/tutorials/minimal-usage.html

Hope this helps!

Userlevel 1

Thanks Einar for the help.

Userlevel 4

If you want to stick with using the .NET SDK you can use the MSAL .NET library to acquire a valid token. Here’s a minimal C# example that reads the AAD and associated CDF variables from environment variables, initiate an interactive flow to acquire the token and uses the token to instantiate the CDF client. If you refer to the MSAL documentation, it’s straightforward to extend this example to other authentication flows.

string clientId = System.Environment.GetEnvironmentVariable("CLIENT_ID");
string tenantId = System.Environment.GetEnvironmentVariable("TENANT_ID");
string cluster = System.Environment.GetEnvironmentVariable("CDF_CLUSTER");
string project = System.Environment.GetEnvironmentVariable("CDF_PROJECT");

var scopes = new List<string>{ $"https://{cluster}.cognitedata.com/.default" };

var app = PublicClientApplicationBuilder
.Create(clientId)
.WithAuthority(AzureCloudInstance.AzurePublic, tenantId)
.WithRedirectUri("http://local host")
.Build();

AuthenticationResult result = await app.AcquireTokenInteractive(scopes).ExecuteAsync();
string accessToken = result.AccessToken;

var httpClient = new HttpClient();
var client = Client.Builder.Create(httpClient)
.SetAppId("testNotebook")
.AddHeader("Authorization", $"Bearer {accessToken}")
.SetProject(project)
.SetBaseUrl(new Uri($"https://{cluster}.cognitedata.com"))
.Build();

Be mindful that I had to separate the words local and host, as this is a word that’s currently not allowed in the Cognite Hub.

Reply