【问题标题】:Generate access token to authenticate Azure Active directory App生成访问令牌以对 Azure Active Directory 应用程序进行身份验证
【发布时间】:2021-04-03 16:38:33
【问题描述】:

我正在使用 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 证书生成访问令牌?

【问题讨论】:

    标签: c# azure azure-active-directory azure-authentication


    【解决方案1】:

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

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-25
    • 2021-10-26
    • 1970-01-01
    • 2023-01-24
    • 1970-01-01
    • 2019-09-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多