I am trying to get the @azure/openai nodejs package to work with a token received from an OAuth2 (clientId, clientSecret) credentials. but it is not working.
Somewhere I’ve read that replacing the api-key with the token would works, but no luck.
async function run2(){
const token = "<the-token>";
const deploymentName = "<the-deployment-name>";
const customUrl = "https://<resource-name>.openai.azure.com"
const client = new OpenAIClient(
customUrl,
new AzureKeyCredential(token)
);
const response = await client.getChatCompletions(
deploymentName,
[{role: "user", content: "How are you?"}]
);
console.log(response.choices![0]!.message!.content); }
Has anyone tried this before?
2
Answers
The
AzureKeyCredential
class is used for API key authentication only. You can indeed use a service principal to authenticate. You need to ensure you have registered an app and assigned the principal the"Cognitive Services User"
role in your Azure OpenAI resource.Using the Azure SDKs for Node.js and Entra ID, you have a couple of options.
Both of the below use the Azure Identity Library.
npm install @azure/identity
You can specify your Client ID, Client Secret, and Tenant ID in code, or load it from configuration or KeyVault. Here’s an example:
If you configured your App Service to use System Managed Identity, or User-defined Managed Identity then you can use this class. This will obtain a token from Entra automatically.
You do also have the option to use
EnvironmentCredential
, whereby you would set the appropriate environment variables for your app:AZURE_TENANT_ID
AZURE_CLIENT_ID
AZURE_CLIENT_SECRET
The Microsoft Authentication Library (MSAL) doesn’t provide a method to construct a TokenCredential using the token string, and OpenAIClient can only be passed types of this base type.
You’ll need to create a custom token credential which extends TokenCredential. However, using this method, you will forfeit the built-in token lifecycle management mechanisms provided by the other TokenCredential types.