asp.net - 通过asp.net中的X509证书进行客户端身份验证

标签 asp.net authentication digital-certificate

我有一个 asp.net 应用程序,我需要使用 X509 证书对用户进行身份验证。也就是说,用户必须安装我颁发的证书,这样他才能浏览我的网站,我可以通过这个证书识别出哪个用户。

我已经在 IIS 上配置了 SSL,但这不是我现在要找的,我不知道从哪里开始。

如何在 asp.net c# 中实现这一点?

最佳答案

要创建安全的身份验证机制,您将同时使用客户端证书和用户名/密码。原因是证书是可以被盗(复制)的东西,而密码是只有个人知道的东西。另一种选择是智能卡上的证书,受 PIN 保护。

要在 ASP.NET 应用程序中使用客户端证书,您需要执行以下操作:

第一步:在 IIS 管理器中,打开您的应用程序或网站,选择 SSL 设置,然后选择需要 SSL 和需要客户端证书。

现在,当用户打开您的网站时,浏览器将提示他选择将在通信中使用的客户端证书。

重要 此时,您必须确保证书是由您信任的人颁发的(因为任何人都可以创建自己的自签名证书)。

第 2 步:添加配置项(web.config、数据库等)。在此列表中,您将为客户端证书添加整个 CA(证书颁发机构)链的指纹。

<add key="ClientCertificateIssuerThumbprints" value="4901f5b87d736cd88792bd5ef7caee91bf7d1a2b,0113e31aa85d7fb02740a1257f8bfa534fb8549e,c9321de6b5a82666cf6971a18a56f2d3a8675602"/>

第 3 步:创建经典的用户名/密码登录页面。验证用户名/密码。

第 4 步:将以下代码添加到您的登录页面:
var x509 = new X509Certificate2(this.Request.ClientCertificate.Certificate);
var chain = new X509Chain(true);
chain.ChainPolicy.RevocationMode = X509RevocationMode.Offline;
chain.Build(x509);

var validThumbprints = new HashSet<string>(
    System.Configuration.ConfigurationManager.AppSettings["ClientCertificateIssuerThumbprints"]
        .Replace(" ", "").Split(',', ';'),
    StringComparer.OrdinalIgnoreCase);

// if the certificate is self-signed, verify itself.
for (int i = chain.ChainElements.Count > 1 ? 1 : 0; i < chain.ChainElements.Count; i++)
{
    if (!validThumbprints.Contains(chain.ChainElements[i].Certificate.Thumbprint))
        throw new UnauthorizedAccessException("The client certificate selected is not authorized for this system. Please restart the browser and pick the certificate issued by XXXXX");
}

// certificate Subject would contain some identifier of the user (an ID number, SIN number or anything else unique). here it is assumed that it contains the login name and nothing else
if (!string.Equals("CN=" + login, x509.Subject, StringComparison.OrdinalIgnoreCase))
    throw new UnauthorizedAccessException("The client certificate selected is authorized for another user. Please restart the browser and pick another certificate.");

只有在检查了密码和证书后,才允许该用户进入系统。

关于asp.net - 通过asp.net中的X509证书进行客户端身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14933477/

相关文章:

internet-explorer - 如何强制ie要求数字证书

c# - 模态弹出窗口中的客户端验证?

scala - 剪影和移动应用程序

security - 可以在保持签名完整性的同时篡改签名的可执行文件吗?

java - 使用 SQL 和 Java 登录

session - 如何在没有 session 但在 AJAX 中使用 token 的情况下进行身份验证

windows - 如何选择正确的数字证书在 Windows 下对可执行文件进行代码签名?

c# - 更改转发器行值?

asp.net - TFS 2010 - TF14040 文件夹可能无法 check out

c# - 输出到标签时有没有办法保留格式?