繁体   English   中英

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

[英]Generate access token to authenticate Azure Active directory App

我正在使用 Azure Active Directory 应用程序来验证部署在 Azure 上的 rest 端点。 我使用 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 更多详情,请参阅此处

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM