Jasinski Technical Wiki

Navigation

Home Page
Index
All Pages

Quick Search
»
Advanced Search »

Contributor Links

Create a new Page
Administration
File Management
Login/Logout
Your Profile

Other Wiki Sections

Software

PoweredBy

Forms Authentication Behind a Load Balancer - ASP.NET

RSS
Modified on Mon, Jan 05, 2015, 2:21 PM by Administrator Categorized as Uncategorized

Overview

When using Forms Authentication in a web farm situation, additional configuration must be done to ensure the Forms Authentication cookie will be accepted no matter which web server receives it.

Procedure

The following changes need to be made to the web.config file, both under the system.web node

1. A machineKey node needs to be created

AttributeValue
validation"SHA1"
validationKey(a 128-hex-digit random key)
decryption"AES"
decryptionKey(a 64-hex-digit random key)

2. Under authentication/forms the protection attribute should be set to "All". The following code will generate a machine key node with cryptographically random keys.

Utility Code

private void GenerateWebConfigXml()
{
    var newLine = Environment.NewLine + "    ";
    var format ="<machineKey";
    format += newLine;
    format += "validation=\"SHA1\"";
    format += newLine;
    format += "validationKey=\"{0}\"";
    format += newLine;
    format += "decryption=\"AES\"";
    format += newLine;
    format += "decryptionKey=\"{1}\"";
    format += newLine;
    format += "/>";
            
    var dKey = GenerateRandomKey(64);
    var vKey = GenerateRandomKey(128);

    var result = string.Format(format, vKey, dKey);
    uxResultTextBox.Text = result;
}

/// <summary>
/// 
/// </summary>
/// <param name="len">KEY length (e.g., for a 32-byte key, pass 64)</param>
/// <returns></returns>
private string GenerateRandomKey(int len)
{
    byte[] buff = new byte[len / 2];
    var rng = new RNGCryptoServiceProvider();
    rng.GetBytes(buff);
    var sb = new StringBuilder(len);

    for (int i = 0; i < buff.Length; i++)
        sb.Append(string.Format("{0:X2}", buff[i]));

    return sb.ToString();
}

Reference

ScrewTurn Wiki version 3.0.1.400. Some of the icons created by FamFamFam. Except where noted, all contents Copyright © 1999-2018, Patrick Jasinski.