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

如何使用TypeScript/JavaScript编程创建Azure App Registration

TypeScript/JavaScript 编程创建Azure App Registration 自动化方案

目前所有新的Azure AD自动化操作统一基于Microsoft Graph SDK实现,旧版Azure AD Graph相关SDK已全部弃用,以下是可直接运行的实现方式,覆盖日常批量创建的常用配置需求。

前置准备

  • 安装依赖包
npm install @azure/identity @microsoft/microsoft-graph-client @microsoft/microsoft-graph-types
  • 权限配置:用于执行脚本的身份(个人账号/服务主体)必须持有Azure AD的Application.ReadWrite.All 应用/委派权限,否则无法创建应用注册。本地调试可直接用自己的工作账号登录Azure CLI即可,不需要额外创建服务主体。

可直接运行的TypeScript实现代码

import { Client } from "@microsoft/microsoft-graph-client";
import { TokenCredentialAuthenticationProvider } from "@microsoft/microsoft-graph-client/authProviders/azureTokenCredentials";
import { DefaultAzureCredential, ClientSecretCredential } from "@azure/identity";
import { Application, PasswordCredential } from "@microsoft/microsoft-graph-types";

// 初始化Graph客户端
// 本地调试直接用DefaultAzureCredential,会自动读取本地az login凭据、VS Code登录凭据等
// 生产/流水线运行可替换为ClientSecretCredential,传入租户ID、自动化服务主体App ID、客户端密钥
const credential = new DefaultAzureCredential();
// 服务主体鉴权示例
// const credential = new ClientSecretCredential(
//   "目标Azure AD租户ID",
//   "自动化服务主体的App ID",
//   "自动化服务主体的客户端密钥"
// );

const authProvider = new TokenCredentialAuthenticationProvider(credential, {
  scopes: ["https://graph.microsoft.com/.default"]
});
const graphClient = Client.initWithMiddleware({ authProvider: authProvider });

/**
 * 创建Azure App Registration
 * @param appName 应用注册显示名称
 * @param redirectUris 重定向URI列表,对应Web/SPA应用的回调地址
 * @param secretExpireMonths 客户端密钥有效期,单位月,默认12个月
 * @returns 创建完成的应用信息+明文客户端密钥(密钥仅返回一次,需及时保存)
 */
async function createAppRegistration(
  appName: string,
  redirectUris: string[] = [],
  secretExpireMonths: number = 12
): Promise<{app: Application, clientSecret: string}> {
  // 1. 创建基础应用注册
  const newApp = await graphClient.api("/applications")
    .post({
      displayName: appName,
      signInAudience: "AzureADMyOrg", // 仅当前租户账号可登录,按需替换为AzureADMultipleOrgs、AzureADandPersonalMicrosoftAccount等受众配置
      web: {
        redirectUris: redirectUris,
        implicitGrantSettings: {
          enableIdTokenIssuance: false,
          enableAccessTokenIssuance: false
        }
      },
      // 如果创建单页应用,注释上面的web节点,改用下面的spa配置
      // spa: {
      //   redirectUris: redirectUris
      // }
    }) as Application;

  // 2. 为应用生成客户端密钥
  const startDate = new Date();
  const endDate = new Date();
  endDate.setMonth(startDate.getMonth() + secretExpireMonths);
  const secret = await graphClient.api(`/applications/${newApp.id}/addPassword`)
    .post({
      passwordCredential: {
        displayName: "Auto-generated by automation script",
        endDateTime: endDate.toISOString()
      }
    }) as PasswordCredential;

  // 3. 按需扩展其他配置:添加API权限、配置应用所有者、设置品牌logo、开启公开API范围等,都可通过对应Graph接口完成
  // 示例:添加Microsoft Graph的User.Read委派权限
  // await graphClient.api(`/applications/${newApp.id}/requiredResourceAccess`).post({
  //   requiredResourceAccess: [
  //     {
  //       resourceAppId: "00000003-0000-0000-c000-000000000000", // Microsoft Graph固定资源ID
  //       resourceAccess: [
  //         {
  //           id: "e1fe6dd8-ba31-4d61-89e7-88639da4683d", // User.Read权限固定ID
  //           type: "Scope"
  //         }
  //       ]
  //     }
  //   ]
  // });

  return {
    app: newApp,
    clientSecret: secret.secretText!
  }
}

// 调用示例
async function main() {
  const result = await createAppRegistration(
    "AutoCreated-BusinessApp",
    ["https://businessapp.example.com/auth/callback"],
    12
  );
  console.log("应用创建完成,App ID:", result.app.appId);
  console.log("生成的客户端密钥:", result.clientSecret);
}

main().catch(console.error);

批量使用说明

  • 本地运行前先执行az login切换到目标租户,不需要在代码里硬编码账号密钥。
  • 批量创建时直接循环调用createAppRegistration方法即可,单次创建量超过100个时建议在请求间加200-500ms延迟,避免触发Graph接口限流。
  • 客户端密钥明文仅在创建接口返回时输出一次,后续无法通过任何接口查询,运行脚本时需要及时将密钥存入密钥管理服务,避免丢失。
  • Azure门户上所有可配置的App Registration选项,都可以通过扩展Graph调用实现,不需要手动介入操作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 11:51:23