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

如何用C#在Microsoft Entra ID中动态编程注册应用?

Can I replicate az ad app create in C#?

Absolutely. The az ad app create command under the hood uses Microsoft Graph API to create Entra ID applications, leveraging the authenticated user's context from az login. You can replicate this exact flow in C# using the Microsoft Graph SDK and MSAL (Microsoft Authentication Library) for user authentication.

How it matches Azure CLI's behavior

When you run az login, you authenticate as a user with permissions to create Entra ID apps. The CLI uses this authenticated session to call Graph's POST /applications endpoint—same as the Graph API you tried earlier, but it uses your user's access token instead of a service principal's credentials.

In C#, you can mirror this by:

  • Authenticating the user interactively (just like az login prompts you to sign in).
  • Using the resulting access token to call Graph API and create the application.

Code Example

First, install these NuGet packages:

  • Microsoft.Graph
  • Microsoft.Identity.Client

Here's a working snippet:

using Microsoft.Graph;
using Microsoft.Identity.Client;
using System;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        // Use Azure CLI's pre-registered app ID to skip creating your own (for testing)
        // Official Azure CLI client ID: 04b07795-8ddb-461a-bbee-02f9e1bf7b46
        var clientId = "04b07795-8ddb-461a-bbee-02f9e1bf7b46";
        var tenantId = "your-tenant-id"; // Replace with your tenant ID or use "common" for multi-tenant
        var requiredScopes = new[] { "Application.ReadWrite.All" };

        // Set up public client auth (matches az login's interactive flow)
        var authApp = PublicClientApplicationBuilder
            .Create(clientId)
            .WithTenantId(tenantId)
            .WithRedirectUri("http://localhost")
            .Build();

        // Prompt user to sign in and get access token
        var authResult = await authApp.AcquireTokenInteractive(requiredScopes)
            .ExecuteAsync();

        // Initialize Graph client with the access token
        var graphClient = new GraphServiceClient(
            new DelegateAuthenticationProvider(req =>
            {
                req.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(
                    "Bearer", authResult.AccessToken);
                return Task.CompletedTask;
            }));

        // Create the application (equivalent to az ad app create --display-name "test-app")
        var newApplication = new Application
        {
            DisplayName = "test-app",
            // Add optional properties here: reply URLs, identifiers, credentials, etc.
        };

        var createdApp = await graphClient.Applications
            .Request()
            .AddAsync(newApplication);

        Console.WriteLine($"Successfully created app. ID: {createdApp.Id}");
    }
}

Key Notes

  • Using Azure CLI's App ID: The client ID in the example is Azure CLI's official pre-registered app. This lets you skip registering your own app for testing purposes. For production, it's better to register your own public client app in Entra ID (a simple, one-time setup).
  • Permissions: The user signing in needs the Application.ReadWrite.All delegated permission (or Application.ReadWrite.OwnedBy for more restricted access). You may need to grant admin consent for this permission in your Entra ID tenant.
  • Customization: You can extend the Application object in the code to include additional properties (like reply URLs, API permissions, or client secrets) just like you would with az ad app create flags.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 09:10:53