Sharing sessions between subdomains – Asp.Net Mvc Apps on IIS
Sometimes, you need to share sessions between different apps on different sub domains. There are some steps to achieve this behaviour and I will try to explain them today.
If we want apps to behave like single app on different subdomains, firstly they must use same cookies. With shared cookies, users won’t have to logged in for each app. They will be able to logged in / out only once for all apps. In order to share cookies we need to add a setting under system.web section in webconfig for cookies:
With this setting, any subdomain under yourmaindomain.com use the same cookies. But there is one more step here, all apps have to same machinekey setting on webconfig. Machinekey attribute is used while encrypting and decrypting the data for the webapplication in ASP.NET.
Before move further, Lets create two websites on our web server.
After creating two websites, for one, select MachineKey feature and click Generate Keys. Copy Validation Key and Decryption Key. Then open other app’s Machine Key feature and paste copied values to related fields.
These values will be pasted to a web config attribute too.
<machineKey validationKey="XXXXX" decryptionKey="XXXXX" validation="SHA1" decryption="AES" />
This attribute will be under system.web section in webconfig.
These changes helps us to use shared cookies without any problem. But to achieve our goal completely, we need to do one more thing. We have to store session state in database, so all applications will share same session data. By adding setting below to web config and editing to connection string, all session data will be shared.
<sessionState mode="SQLServer" sqlConnectionString="data source=127.0.0.1;user id=username;password=strongpassword" cookieless="false" timeout="20"/>
Leave a Reply