多服务器环境下验证视图状态MAC失败的解决办法

WEB应用中经常遇到采用集群或负载均衡交换机等方式实现多服务器共同对外提供服务,分担压力。在这样的环境下如果Asp.Net程序执行时碰到如下中文错误:

“验证视图状态 MAC 失败。如果此应用程序由网络场或群集承载,请确保 <machineKey> 配置指定了相同的 validationKey 和验证算法。不能在群集中使用 AutoGenerate。”

或如下英文错误:

Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that <machineKey> configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster.

则说明多台WEB服务器上的WEB应用程序没有使用统一的machineKey导致的。

那么machineKey的作用是什么呢?

按照MSDN的标准说法:“对密钥进行配置,以便将其用于对 Forms 身份验证 Cookie 数据和视图状态数据进行加密和解密,并将其用于对进程外会话状态标识进行验证。”

也就是说Asp.Net的很多加密,都是依赖于machineKey的设置,例如Forms 身份验证 Cookie、ViewState的加密。

默认情况下,Asp.Net的配置是自己动态生成,如果单台服务器当然没问题,但是如果多台服务器负载均衡,machineKey还采用动态生成的方式,每台服务器上的machinekey值不一致,就导致加密出来的结果也不一致,不能共享验证和ViewState,所以对于多台服务器负载均衡的情况,一定要在每台站点配置相同的machineKey。

machineKey生成的算法:

validationKey = CreateKey(20);
decryptionKey = CreateKey(24);
protected string CreateKey(int len)
{
   byte[] bytes = new byte[len];
   new RNGCryptoServiceProvider().GetBytes(bytes);
   StringBuilder sb = new StringBuilder();
   for(int i = 0; i < bytes.Length; i++)
   {
       sb.Append(string.Format("{0:X2}",bytes[i]));
   }
   return sb.ToString();
}

附参考的matchineKey配置:
<?xml version="1.0"?>
<configuration>
   <system.web>
       <machineKey validationKey="3FF1E929BC0534950B0920A7B59FA698BD02DFE8" decryptionKey="AutoGenerate,IsolateApps" decryption="Auto" validation="SHA1"/>
   </system.web>
</configuration>
 
posted @ 2009-02-22 15:14  瑞君  Views(539)  Comments(0Edit  收藏  举报