Sunday, March 16, 2014

Increase session token lifetime in passive federation scenario

I'm currently working on MVC 5 web application which claims based authentication. Recently I run into two small problems:
  1. How to increase session token lifetime
  2. Configure application to work properly in load balanced environment

In default passive federation scenario, web application is configured to use System.IdentityModel.Tokens.SessionSecurityTokenHandler to manage session tokens (serialize, deserialize and validate). Unfortunately this implementation of SecurityTokenHandler uses behind the scenes Data Protection API (DPAPI) to protect the cookie. To make things working properly in load balanced environment we need to use different implementation which uses Machine Key to protect cookie. System.IdentityModel.Services.Tokens.MachineKeySessionSecurityTokenHandler is perfect for this.

Additionally, I wanted to increase session token lifetime. It turns out this can be done pretty easy. It is enough to add sessionTokenRequirement tag with lifetime property.

To make things working properly, we need to replace existing securityTokenHandlers section with following:


  <system.identityModel>
    <identityConfiguration>
      <securityTokenHandlers>
        <remove type="System.IdentityModel.Tokens.SessionSecurityTokenHandler, System.IdentityModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
        <add type="System.IdentityModel.Services.Tokens.MachineKeySessionSecurityTokenHandler, System.IdentityModel.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
          <sessionTokenRequirement lifetime="12:00" />
        </add>        
      </securityTokenHandlers>
    </identityConfiguration>
  </system.identityModel>


One more step is required to make things working properly. Application on all machines in cluster should have the same machine key configuration applied. This can be done by putting following line in section of web.config

<machineKey validationKey="...,IsolateApps" 
            decryptionKey="...,IsolateApps" 
            decryption="Auto" 
            validation="HMACSHA512" 
            compatibilityMode="Framework45" />

From security perspective, it is good to have separate key for each application. This can be achieved by adding ,IsolateApps on the end of validationKey and decryptionKey. Validation and decryption keys can be generated using IIS Manager in two simple steps.

First, select Machine Key option on Web Site or Application settings page:

Next step is to generate keys and apply settings:


All done, have fun!

No comments:

Post a Comment