You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用OAuth2令牌替代API密钥调用Azure OpenAI Node.js SDK?

解决@azure/openai使用OAuth2令牌替代API密钥的问题

你当前的问题在于用AzureKeyCredential传递OAuth2令牌是错误的,这个类专门用于Azure认知服务的静态API密钥,并不适配OAuth2令牌。以下是两种可行的实现方式:

方式一:用Azure Identity自动管理OAuth2令牌

推荐这种方式,它会自动处理令牌的获取、刷新逻辑,无需手动维护令牌有效期。

  1. 先安装依赖包:
npm install @azure/openai @azure/identity
  1. 代码示例:
const { OpenAIClient } = require("@azure/openai");
const { ClientSecretCredential } = require("@azure/identity");

async function run() {
  const tenantId = "<你的租户ID>";
  const clientId = "<你的Client ID>";
  const clientSecret = "<你的Client Secret>";
  const deploymentName = "<部署名称>";
  const customUrl = "https://<资源名称>.openai.azure.com";

  // 创建凭据实例,自动获取OAuth2令牌
  const credential = new ClientSecretCredential(tenantId, clientId, clientSecret, {
    scopes: ["https://cognitiveservices.azure.com/.default"]
  });

  const client = new OpenAIClient(customUrl, credential);
  const response = await client.getChatCompletions(
    deploymentName,
    [{ role: "user", content: "How are you?" }]
  );

  console.log(response.choices[0].message.content);
}

run().catch(err => console.error(err));

方式二:手动传入已获取的OAuth2令牌

如果已经通过其他方式拿到了OAuth2令牌,需要用AccessTokenCredential包装后传入,而不是AzureKeyCredential。

  1. 安装依赖包:
npm install @azure/openai @azure/core-auth
  1. 代码示例:
const { OpenAIClient } = require("@azure/openai");
const { AccessTokenCredential } = require("@azure/core-auth");

async function run2() {
  const token = "<你的OAuth2令牌>";
  const deploymentName = "<部署名称>";
  const customUrl = "https://<资源名称>.openai.azure.com";

  // 用AccessTokenCredential包装令牌,需指定过期时间(根据实际令牌有效期调整)
  const credential = new AccessTokenCredential({
    token: token,
    expiresOnTimestamp: Date.now() + 3600 * 1000 // 示例:1小时后过期
  });

  const client = new OpenAIClient(customUrl, credential);
  const response = await client.getChatCompletions(
    deploymentName,
    [{ role: "user", content: "How are you?" }]
  );

  console.log(response.choices[0].message.content);
}

run2().catch(err => console.error(err));

注意事项

  • 确保你的服务主体(对应Client ID的身份)拥有Azure OpenAI资源的认知服务用户或Contributor权限,否则令牌会因权限不足无法调用API。
  • OAuth2令牌有有效期,手动传入时要注意及时刷新,避免令牌过期导致请求失败。

内容的提问来源于stack exchange,提问作者Loebre

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 07:47:15