在.NET中以编程方式创建Azure AD服务主体

gajydyqb  于 2023-02-26  发布在  .NET
关注(0)|答案(3)|浏览(161)

我正在寻找一个关于如何在.NET中以编程方式创建服务主体(使用另一个服务主体)的当前示例。包括设置证书凭据(理想情况下是在Azure Key Vault中存储/生成的凭据)
我找到了this old answer,但没有当前的等价物,这可能需要使用Microsoft.Graph Nuget包?!

tcbh2hod

tcbh2hod1#

我尝试在我的环境中重现相同的结果,结果如下:

我的Azure密钥库中有一个名为**sricert**的证书,如下所示:

现在,我注册了一个Azure AD应用程序并添加了相同的证书,如下所示:

确保向创建Azure AD应用程序所需的以下API permission添加并授予管理员许可

现在,我运行了以下c#代码,该代码从Azure密钥库获取证书,并通过现有服务主体使用**Microsoft.Graph**包创建新的Azure AD应用程序,如下所示:

using Azure.Identity;
using Azure.Security.KeyVault.Certificates;
using Azure.Security.KeyVault.Secrets;
using Microsoft.Graph;
using Microsoft.Identity.Client;
using System;
using System.Net.Http.Headers;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        static async Task Main(string[] args)
        {
            string tenantId = "58e70374-11f2-4e91-af40-xxxxxxxxx";
            string clientId = "cd88c0ed-30e9-4624-bfc6-xxxxxxxx";
            string certificateName = "sricert";
            string keyVaultUri = $"https://srikeyv.vault.azure.net/";

            // Authenticate with Azure Key Vault and obtain an access token
            var credential = new DefaultAzureCredential();
            var certClient = new CertificateClient(new Uri(keyVaultUri), credential);
            var cert = await certClient.GetCertificateAsync(certificateName);

            var secretClient = new SecretClient(new Uri(keyVaultUri), credential);
            var secret = await secretClient.GetSecretAsync(cert.Value.Name, cert.Value.Properties.Version);

            var certificateBytes = Convert.FromBase64String(secret.Value.Value);
            var certificate = new X509Certificate2(certificateBytes);

            var app = ConfidentialClientApplicationBuilder
                .Create(clientId)
                .WithAuthority($"https://login.microsoftonline.com/{tenantId}")
                .WithCertificate(certificate)
                .Build();

            var scopes = new[] { "https://graph.microsoft.com/.default" };
            var result = await app.AcquireTokenForClient(scopes).ExecuteAsync();
            var accessToken = result.AccessToken;

            // Create a new Azure AD application using the Microsoft Graph API
            var graphClient = new GraphServiceClient(new DelegateAuthenticationProvider((requestMessage) =>
            {
                requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", accessToken);
                return Task.FromResult(0);
            }));

            var application = new Application
            {
                DisplayName = "Sri GraphSP",
                SignInAudience = "AzureADMyOrg",
                PublicClient = new Microsoft.Graph.PublicClientApplication
                {
                    RedirectUris = new[] { "https://jwt.ms" },
                },
            };

            await graphClient.Applications
                .Request()
                .AddAsync(application);

            Console.WriteLine("New Azure AD application created successfully");
        }
    }
}
    • 答复:**

为了确认这一点,我在Azure Portal中进行了相同检查,其中成功创建了名为**Sri GraphSP新**Azure AD应用程序,如下所示:

zbsbpyhn

zbsbpyhn2#

过了一段时间我想通了,包括先在Key Vault中创建证书:

var graphClient = new GraphServiceClient(new DefaultAzureCredential());

var certName = "my-sp-cert";

var certificateClient = new CertificateClient(new Uri("https://my.vault.azure.net"), new DefaultAzureCredential());
var op = await certificateClient.StartCreateCertificateAsync(certName, CertificatePolicy.Default);
var certResponse = await op.WaitForCompletionAsync();
var cert = certResponse.Value;

// First, we need to create an App Registration, aka "AAD Application"
var application = new Application
{
    DisplayName = "my-app",
    KeyCredentials = new List<KeyCredential>()
    {
        new KeyCredential
        {
            StartDateTime = cert.Properties.CreatedOn,
            EndDateTime = cert.Properties.ExpiresOn,
            Type = "AsymmetricX509Cert",
            Usage = "Verify",
            Key = cert.Cer,
            DisplayName = certName
        }
    }
};
var createdApp = await graphClient.Applications.Request().AddAsync(application);

_logger.LogInformation("Created AAD application {appId}, {objectId}", createdApp.AppId, createdApp.Id);

// Next, we add a Service Principal (SPN) to the App Registration
var spn = new ServicePrincipal()
{
    AppId = createdApp.AppId
};

var createdSpn = await graphClient.ServicePrincipals.Request().AddAsync(spn);

_logger.LogInformation("Created AAD service principal {clientId}, {objectId}", createdSpn.AppId, createdSpn.Id);
t2a7ltrp

t2a7ltrp3#

使用Azure CLI的az ad sp create-for-rbac是最新的跨平台解决方案。

相关问题