生成访问令牌以验证 Azure 活动目录应用程序

Generate access token to authenticate Azure Active directory App

我正在使用 Azure Active Directory 应用程序对部署在 Azure 上的其余端点进行身份验证。 我使用 pfx 证书类型和下面的代码来生成访问令牌,以便可以通过该访问令牌访问我的端点。

        var authority = string.Format(authorityUri, credentialConfigOptions.TenantId);
        var authContext = new AuthenticationContext(authority);
        X509Certificate2 certificate = default;using (var store = new X509Store(StoreName.My, StoreLocation.CurrentUser, OpenFlags.ReadOnly))
        {
            var certificateCollection = store.Certificates.Find(X509FindType.FindBySubjectName, credentialConfigOptions.CertificateName, false);
            if (certificateCollection.Count > 0)
            {
                certificate = certificateCollection[0];
            }
        };
        
        var clientAssertionCertificate = new ClientAssertionCertificate(credentialConfigOptions.AppId, certificate);
        AuthenticationResult token = await authContext.AcquireTokenAsync(appId, clientAssertionCertificate);
        return token?.AccessToken;

现在我必须使用 PEM 证书类型而不是 pfx 证书类型,所以我在将 PEM 格式转换为 X509Certificate2 时遇到问题。 如何使用 PEM 证书生成访问令牌?

如果您使用 Net 5.0,我们可以直接使用方法 X509Certificate2.CreateFromPemFile(<certpath>,<keypath>) 使用证书和密钥创建 X509Certificate2。详情请参考here.

如果您使用其他版本,我们可以创建一个 X509Certificate2 with cert 文件,然后使用方法 CopyWithPrivateKey 导入私钥。最后我们用代码创建证书 new X509Certificate2(pubKey.Export(X509ContentType.Pfx))。详情请参考.