Skip to main content
 首页 » 编程设计

c#之WIF: "ID1014: The signature is not valid. The data may have been tampered with"使用非商店证书时出错

2024年02月06日17三少

在开发基于声明的身份验证应用程序时,为了使应用程序在部署到负载平衡服务器时能够正常工作,我遵循了http://msdn.microsoft.com/en-us/library/ff803371.aspx。通过使用 RsaTokenTransform 处理程序替换默认的 SecurityTokenHandler 以使用自行提供的证书加密 session cookie:

X509Certificate2 serviceCertificate = new X509Certificate2(certificate, certificatePassword); 
List<CookieTransform> sessionTransformers = 
    new List<CookieTransform> 
    ( 
            new CookieTransform[] 
        { 
            new DeflateCookieTransform(), 
            new RsaEncryptionCookieTransform(serviceCertificate), 
            new RsaSignatureCookieTransform(serviceCertificate) 
        } 
    ); 
SessionSecurityTokenHandler sessionHandler = new SessionSecurityTokenHandler(sessionTransformers.AsReadOnly()); 
 
FederatedAuthentication.ServiceConfiguration.SecurityTokenHandlers.AddOrReplace(sessionHandler); 

为了使应用程序更加灵活和便携,证书在运行时从数据库中提取并存储在 X509Certificate2 对象中。

这是在一台托管应用程序的服务器上工作,但是一旦我切换到服务器场,我时不时会收到错误消息:

ID1014:签名无效。数据可能已被篡改

由于同样的问题,一些 javascript、css 和字体文件也无法加载。

相关问题但没有解决问题:

WIF- ID1014: The signature is not valid. The data may have been tampered with

WIF: ID1014: The signature is not valid. The data may have been tampered with

请您参考如下方法:

在互联网上搜索后,我没有找到明确的解释或解决问题的方法;为了节省可能遇到与我相同问题的人的时间,这里是解释:

问题的原因是默认情况下,X509Certificate2 对象只提供一个临时的 Privatekey Provider,它不会在服务器场的不同服务器之间持续存在。一旦请求从原始服务器转到另一台服务器,Privatekey Provider 在该服务器上变为空(因为它不会持久存在),因此会抛出异常,因为签名验证需要证书的私钥。

要解决这个问题,只需要在创建 X509Certificate2 对象时使 Privatekey Provider 持久化:

X509Certificate2 serviceCertificate = new X509Certificate2(certificate, certificatePassword, X509KeyStorageFlags.MachineKeySet|X509KeyStorageFlags.PersistKeySet);