使用 AAD 应用程序(ClientID、TenantID、Cert-Thumbprint)从 Azure 获取令牌

Get Token from Azure using AAD App (ClientID, TenantID, Cert-Thumbprint)

我有以下方法使用 ClientIDTenantIDAADAppPassword[=31= 从 Azure 获取令牌]

这很棒,但现在我需要切换到不同的 AAD AppID 并使用 Certificate ThumbprintCertificate pfx。 我不想更改我的 1000 多行代码。

谁能帮我获得一个令牌,就像我使用下面的方法一样,但使用 Certificate Thumbprint 而不是 returns token 这样我就可以在我即将进行休息 API 调用之前调用该方法。

public static async Task<string> GetAccessToken(string tenantId, string clientId, string clientKey)
        {
            string authContextURL = "https://login.windows.net/" + tenantId;
            var authenticationContext = new AuthenticationContext(authContextURL);
            var credential = new ClientCredential(clientId, clientKey);
            var result = await authenticationContext

            .AcquireTokenAsync("https://management.azure.com/", credential);
            if (result == null)
            {
                throw new InvalidOperationException("Failed to obtain the JWT token");
            }
            string token = result.AccessToken;
            return token;
    }

您必须使用 ClientAssertionCertificate 而不是 ClientCredential

X509Certificate2 cert = ReadCertificateFromStore(config.CertName);
certCred = new ClientAssertionCertificate(config.ClientId, cert);
result = await authContext.AcquireTokenAsync(todoListResourceId, certCred);

您可以参考 Azure AD v1 Sample

MSAL.NET 现在是推荐的与 Microsoft 标识平台一起使用的身份验证库。 ADAL.NET 上不会实现任何新功能。这些努力的重点是改进 MSAL。如果您打算将应用程序迁移到 MSAL.NET

,您可以在此处参考 documentation