I was reading through Scott Mitchell's article
Key Configuration Settings When Deploying a Web Application
over on 4GuysFromRolla when something occurred to me. While the article is full of great information, the one deployment issue that
caught me off guard the first time I deployed an ASP.NET Web site to a server farm
isn't mentioned. Those of you who have deployed to a Web farm probably already know
that I'm talking about the <machineKey> setting. It's a simple
little setting, but can cause some interesting problems.
The machineKey element is where you configure the keys that ASP.NET will use to
encrypt and decrypt data for your application. This includes forms authentication cookies,
out-of-process session state information, and viewstate data. By default, ASP.NET generates
the keys for you automatically. This normally works great... as long as your application
runs on only one server.
The problems start when you add a second server to the mix. If a user happens to bounce
from one server to the other (ie. non-sticky sessions or a server goes down), the
keys on the second server won't match those from the first. After all each server
automatically generated its own unique key. The first symptom you'll probably notice
is viewstate errors. In order to ensure users don't tamper with your site's
viewstate, ASP.NET includes the machineKey information in it. If it comes back and the
keys don't match, the server will throw an error stating that the viewstate is invalid.
The solution is to find a way to get the keys to match. The way to do that is to
simply set them yourself. The setting goes in the <system.web>
section of your machine.config or web.config file and
looks like this:
The values for validationKey and decryptionKey are the things you'll want to set and keep
to yourself. They're normally 64 bytes (128 hex characters) and 32 bytes (64 hex characters)
respectively. Creating your own is pretty easy, but if you want some help, simply do a Web
search for "machineKey generator" and you'll find plenty of online tools
that will generate one for you.
Once you choose a value, the only thing left to do is make sure it's the same
on every server in the Web farm. Generally each application should have a different key,
but each application's key needs to be the same on all the servers on which that application runs.
Personally, I find it easiest to simply set the key in my application's
web.config file. That way the key gets copied to the servers
right along with the application.
For more information on the machineKey element, you may find the following links helpful: