You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Azure应用注册中用证书替换客户端密钥的代码修改方法

使用证书替换客户端密钥访问Azure媒体服务

配置调整

  1. 替换环境变量:将原来的客户端密钥(AAD_SECRET)替换为证书指纹(AAD_CERT_THUMBPRINT),保留客户端ID(AAD_CLIENT_ID)和租户ID(AAD_TENANT_ID)。
  2. 证书部署:
    • 本地调试:将证书安装到当前用户->个人证书存储,确保证书包含私钥。
    • App Service部署:在App Service的「TLS/SSL设置」->「私钥证书」上传证书,然后在应用设置中添加WEBSITE_LOAD_CERTIFICATES,值为证书指纹(多个证书用逗号分隔),让代码能访问到证书。

代码修改

先添加根据指纹获取证书的辅助方法,再修改原有的认证逻辑:

using System.Security.Cryptography.X509Certificates;
using Microsoft.IdentityModel.Clients.ActiveDirectory;

// 辅助方法:从证书存储获取指定指纹的证书
private X509Certificate2 GetCertificate(string certificateThumbprint)
{
    using var store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
    store.Open(OpenFlags.ReadOnly);
    
    var certCollection = store.Certificates.Find(
        X509FindType.FindByThumbprint,
        certificateThumbprint,
        validOnly: false); // 若需严格验证证书有效性,可改为true
    
    if (certCollection.Count > 0)
    {
        return certCollection[0];
    }
    
    throw new InvalidOperationException($"未找到指纹为 {certificateThumbprint} 的证书");
}

// 修改后的认证方法
private async Task<ServiceClientCredentials> GetCredentialsAsync(string aadClientId, string certificateThumbprint, string aadTenantId)
{
    var certificate = GetCertificate(certificateThumbprint);
    var clientCertCredential = new ClientAssertionCertificate(aadClientId, certificate);
    
    return await ApplicationTokenProvider.LoginSilentAsync(
        aadTenantId, 
        clientCertCredential, 
        ActiveDirectoryServiceSettings.Azure);
}

关键注意事项

  • 证书必须包含可导出的私钥,否则无法生成签名断言完成认证。
  • 如果使用MSAL(微软推荐的新版认证库),可以替换为ClientCertificateCredential实现更简洁的逻辑,但需要调整依赖包。
  • 在App Service中,WEBSITE_LOAD_CERTIFICATES设为*可加载所有上传的证书,但生产环境建议指定具体指纹以提升安全性。

内容的提问来源于stack exchange,提问作者PT2550

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 15:25:10