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

如何在Xamarin Forms中使用CA根证书完成LDAPS身份认证

修改方案

你目前使用的应该是Novell.Directory.Ldap.NETStandard跨平台LDAP库,这是Xamarin Forms生态下兼容最好的LDAP实现,按以下步骤修改代码即可实现带CA根证书校验的LDAPS连接:


第一步:导入CA根证书到项目

将你公司提供的CA根证书(通常为.cer或.pem格式)按平台规则放入对应目录:

  • Android平台:放入Assets文件夹,设置生成操作为AndroidAsset
  • iOS平台:放入Resources文件夹,设置生成操作为BundleResource

第二步:修改认证代码

using System.Security.Cryptography.X509Certificates;
using Novell.Directory.Ldap;

// 全局预加载CA根证书,仅需加载一次
private X509Certificate2 _rootCaCert;

void LoadRootCaCert()
{
    // 替换为你实际的根证书文件名
    using var stream = FileSystem.OpenAppPackageFileAsync("company_root_ca.cer").Result;
    using var ms = new MemoryStream();
    stream.CopyTo(ms);
    _rootCaCert = new X509Certificate2(ms.ToArray());
}

void ldap_check() {
    // 确保根证书已加载
    if (_rootCaCert == null) LoadRootCaCert();

    // 自定义SSL证书校验逻辑
    LdapConnection.ServerCertValidationCallback = (sender, certificate, chain, sslPolicyErrors) =>
    {
        // 把内置根证书加入校验链
        chain.ChainPolicy.ExtraStore.Add(_rootCaCert);
        // 根据公司安全要求调整吊销校验规则,不需要校验可设为NoCheck
        chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
        chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority;
        
        // 校验服务端证书是否由内置CA根证书签发
        var isChainValid = chain.Build((X509Certificate2)certificate);
        if (!isChainValid) return false;
        
        // 额外校验根证书指纹匹配,防止伪造CA攻击
        var chainRootCert = chain.ChainElements[^1].Certificate;
        return chainRootCert.Thumbprint == _rootCaCert.Thumbprint;
    };

    // 第三个参数传true启用SSL,端口改为LDAPS默认的636
    cn.Connect("209.132.219.125", 636, true);

    try
    {
        cn.Bind("uid=adam,ou=People,dc=localdomain,dc=local", "3923dEf!fde1");
        Console.WriteLine("::: LDAP success" + cn.ToString() + " ::: ");
    }
    catch (LdapException f)
    {
        Console.WriteLine("LDAP FAIL : " + f.ResultCode.ToString());
        return;
    }
    catch (Exception f)
    {
        Console.WriteLine("LDAP FAIL : " + f.Message);
        return;
    }
}

注意事项

  • 不要直接在校验回调里返回true跳过证书校验,会导致LDAPS的安全能力完全失效,存在中间人攻击风险
  • 如果你的CA体系有中间证书,也需要按相同方式加入chain.ChainPolicy.ExtraStore中
  • 如果连接失败可先确认服务器636端口对外暴露,且证书域名/IP和连接地址匹配

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 00:15:03