Understanding Single Sign-On in ASP.NET 2.0
 
Published: 16 Jan 2008
Abstract
In this article, Masoud discusses the concept of Cross Application Authentication using ASP.NET authentication model consisting of Membership Providers, web.config configuration, encryption, and decryption of configuration files. At the end of the article he also examines the application of the concept using ASP.NET login controls.
by Masoud Tabatabaei
Feedback
Average Rating: 
Views (Total / Last 10 Days): 147421/ 299

Introduction

Normally when you are implementing authentication in ASP.NET web application, you have to create a login page for each of your applications. Imagine that you have two or more web application which are related together. So you may want to use a mechanism which allows you to create just one login page for all your related applications. In this way, once you have logged in you can browse other application without any extra login required. Single sign-on (SSO) is a method of access control that enables a user to authenticate once and gain access to the resources of multiple software systems.

Consider you have created two or more web sites in your server. As any other web site, you have just used the ASP.NET authentication mechanism to authenticate your users. So you have two or more login pages depending on your web sites. Now we are going demonstrate how to modify your setting to accomplish the goal of Cross Application login. In other words, we just want to have one login page for whole web site, and once the users have been authenticated they can browse to other web sites, without the need to re-login. In addition you can see how you can encrypt your configuration files during this article.

What's SSO and how it works?

In many companies there are some web sites or web base applications which are developed to cover the software needs in the systems. Of course, because of security issues they will have they authentication and authorization systems base on ASP.NET 2.0 built in Membership Provider and Role Provider or custom implementation of these mechanism. Anyway, by default all the web sites will have a "Login.aspx" web form which will authenticate the users throw their User and Passwords available in the database. While you have just one web site or web sites which are working independently there would be no problem, but since you may have two or more web site which are related together or having links together, you may think Why do you have to login in each application every time separately? Why cannot you have just one "Login.aspx" web page which authenticates the users and throw all the web application related together. Fortunately, in ASP .NET 2.0 you can achieve your goal of Cross Application Login by some configuration in your new or existing web sites.

In ASP .NET configuration file (web.config) there is an element inside <system.web> element named <machineKey> which Configures keys to use for encryption and decryption of Forms authentication cookie data and view-state data and for verification of out-of-process session state identification. If in each of your web sites you set the same <machineKey>, those applications can read Forms authentication cookies. So after the users have been authenticated and a cookie saved on its computer, the other applications with the same <machineKey>, can accept this cookie as a valid authentication ticket. So there would be no need to re-login in other applications with the same <machineKey> in their web.config file.

Because <machineKey> information is sensitive, you should encrypt the section information of your configuration file.

To accomplish this goal, I am going to use ConfigurationManager class and its members. There is also a class named SectionInformation which Contains meta-information on an individual section within the configuration. There is a method called ProtectSection(); this method is used to encrypt a section of your configuration file.

System Requirements

·         A web server running on Windows 2000 or later

·         .NET Framework 2.0

·         Visual Studio 2005

·         Microsoft SQL Server 2005 Express Edition

Working

Now let see what is happening in our projects. I have a web site, Aspalliance1, which has a "Login.aspx" as its login page. Users can be authenticated here in that page. In this web site there is also a web page named "Default.aspx" which has just a header and some text and also a link to Aspalliance2 web site. You will see that once the user has been logged in, it can navigate cross other web sites without re-login needed. There is also a web page "Encryption.aspx" which has two buttons to encrypt or decrypt the configuration files.

As I said before, you can have cross application login with a little bit of configuration in your web configuration file. In web.config file there is an element under configuration section which named <system.web>. We are going to set some configuration here inside <system.web> section. We just need to add <machineKey> section with its value inside <system.web> element. <machineKey> has there attribute and I am going to set them. The first one is validation which specifies the type of encryption used for validation. validationKey specifies the key used for validation of encrypted data and decryptionKey specifies the key that is used to encrypt and decrypt data or the process by which the key is generated.

Listing 1: Setting machineKey element in web.config

<machineKey       
validationKey="282487E295028E59B8F411ACB689CCD6F39DDD21E6055A3EE480424315994760ADF
21B580D8587DB675FA02F79167413044E25309CCCDB647174D5B3D0DD9141" 
decryptionKey="8B6697227CBCA902B1A0925D40FAA00B353F2DF4359D2099"       
validation="SHA1"/>

The demonstrated code is not encrypted, and it will not be published on the server. Because of security it is important to encrypt the <machineKey> configuration section and publish it to the server. You can see encrypted <machineKey> element in Listing2.

Listing 2: Encryped machineKey element in web.config

<machineKey configProtectionProvider="RsaProtectedConfigurationProvider">
      <EncryptedData Type="http://www.w3.org/2001/04/xmlenc#Element"
        xmlns="http://www.w3.org/2001/04/xmlenc#">
        <EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#tripledes-cbc" />
        <KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
          <EncryptedKey xmlns="http://www.w3.org/2001/04/xmlenc#">
            <EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-1_5" />
            <KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
              <KeyName>Rsa Key</KeyName>
            </KeyInfo>
            <CipherData>
              <CipherValue>
lm3mfPX/94Zm3HgdbsmKiIxbrWM14t3/ugxs40BFOAHbIaCtwQ3gVQusFtOFVUoNVny01kgBCeh10rVEId
djNZ/8luBNoCbHm8OLjgPLHVrT+G0c/LRpESJk2ni/Jy2sWKXlgejgSQ1W5NE53GZtG3s9hu+nk4OWxntS
6z3v7AM=
              </CipherValue>
            </CipherData>
          </EncryptedKey>
        </KeyInfo>
        <CipherData>
          <CipherValue>
BCEGUV/dh1Imbcm5vn0Kn8NrD+EX+KemenR7x+VekwT1ZO6y5+jRyF4RDWMJCfJ1jHC36+MAfCdHuXN0rP
B6hu5YUtX9VA5q5N0NGrs9AIpG+0ihuuS3HDzQe3P6nlI30m1h0pmL1yJBovY0i6fbCA6++GT2MdwCLERk
+PVWmoq7p1q97n5pNzNqhVKCX45lhS5ySVS+MjJXVeTrcatftpvaUcjLsNcL2kMerzf5w/SU3AbLEuY04w
dgYWX5tWzxqeUcghdlWLD0tQi8qyyfVfzXPYozR5sspWHdgqmAycrACHN2dcONWPjT4BanRWb1ouKuP8K+
0CEFE/Hj2ChpYw==
          </CipherValue>
        </CipherData>
      </EncryptedData>
</machineKey>

You can encrypt your configuration files using Configuration and SectionInformation classes. Let us write some code in order to encrypt or decrypt your <machineKey> section. SectionInformation class has a method ProtectSection() which gets an string representing the Protection Provider like "RSAProctedConfigurationProvider" and encrypt the section. There is also a Boolean property ForceSave which has to be true when wanted to save the configuration file with save method of configuration class. Here is the code of "Encryption.aspx" web page which has two buttons to encrypt and decrypt the configuration file.

Listing 3: Encryption code on web configuration file

protected void btnEncrypt_Click(object sender, EventArgs e)
{
  try
  {
    Configuration config = WebConfigurationManager.OpenWebConfiguration(
      "/Aspalliance1 ");
    ConfigurationSection machineKeySection = config.GetSection(
      "system.web/machineKey");
    machineKeySection.SectionInformation.ProtectSection(
      "RSAProtectedConfigurationProvider");
    machineKeySection.SectionInformation.ForceSave = true;
    config.Save();
 
    Response.Write("<h2 style='color:red'>Encryption Succeed</h2>");
  }
  catch (Exception ex)
  {
    Response.Write("<h2 style='color:red'>Error while encrypting</h2><br/>");
    Response.Write(ex.Message);
  }
}

Listing 4: Decryption of web configuration file

protected void btnDecrypt_Click(object sender, EventArgs e)
{
  try
  {
    Configuration config = WebConfigurationManager.OpenWebConfiguration(
      "/Aspalliance1 ");
    ConfigurationSection machineKeySection = config.GetSection(
      "system.web/machineKey");
    machineKeySection.SectionInformation.UnprotectSection();
    machineKeySection.SectionInformation.ForceSave = true;
 
    config.Save();
    Response.Write("<h2 style='color:red'>Decryption Succeed</h2>");
  }
  catch (Exception ex)
  {
    Response.Write("<h2 style='color:red'>Error while decrypting</h2><br/>");
    Response.Write(ex.Message);
  }
}

Now you have to set some configuration in this web site. First you have to change loginUrl of your <forms> section, which will be used to redirect an anonymous user to "Login.aspx" web page. But this time it will redirect users to "Login.aspx" page in Aspalliance1 web site.

Listing 5: Setting authentication element in web.config

<authentication mode="Forms">
<forms loginUrl="http://localhost/Aspalliance1/login.aspx" name=".ASPXAUTH"/>
</authentication>

The most important part of our article is that if you wan to implement cross application login in your web sites, you must have two or more web sites with the same <machineKey> configurations. So I just copy and paste the <machineKey> section of Aspalliance1 web site to Aspalliance2 web site. Now it is ready and you can just test you web sites.

Listing 6: Setting machineKey element in web.config

<machineKey       
validationKey="282487E295028E59B8F411ACB689CCD6F39DDD21E6055A3EE480424315994760ADF
21B580D8587DB675FA02F79167413044E25309CCCDB647174D5B3D0DD9141" 
decryptionKey="8B6697227CBCA902B1A0925D40FAA00B353F2DF4359D2099"       
validation="SHA1"/>
Downloads

[Download Sample]

For testing the web site try to login with Admin username and 123456& password.

The sample download for this article contains a VS 2005 solution containing two web sites: aspalliance1 and aspalliance2.

To install the sample, you should first create two IIS virtual directory called aspalliance1 and aspalliance2, which points to the folder to which you have installed these two projects. You can also open web sites with File System in Visual Studio 2005.

Conclusion

It is really nagging if you have two or more web sites on a server and the users have to login whenever they want to cross between them. So it would be very good to allow user's to just login once. To accomplish this you just need to add <machineKey> section to your "web.config" file in all your web sites with the same values. And because of security, I recommend you encrypt this section. The encryption is covered with ProtectSection() method of SectionInformation class with a RSAProtecConfigurationProvider value.



User Comments

Title: Very Good Article   
Name: Josh from Web Development Australia
Date: 10/11/2011 9:11:59 AM
Comment:
At first I was really confused in understanding ASP.net. Tags are really confusing.. Isn’t it? Anyways, as far as I know, service controls are tags basically an HTML tags understood by servers. Server control must always be properly executed so that you will not have a problem in your codes.
Title: Very Good Article   
Name: Ahmed Soliman
Date: 10/3/2011 10:27:05 AM
Comment:
Thanks a lot
Title: How can i open differnt application from single login   
Name: Priti
Date: 9/30/2011 6:22:07 AM
Comment:
i have main application where i have retrieve the other two application name(which have their own login form) in grid view using single user.
Now when i click any one application name,how can i avoid the login page of the application and redirect with the page which i need.

Plz give me the solution.
Title: I cannot access the page in the aspalliance2 app   
Name: praveen
Date: 8/3/2011 11:14:43 PM
Comment:
suppose i add another page called home.aspx in aspalliance2,now i request that page directly
http://localhost/Aspalliance2/home.aspx ..in this case it has to redirect to login page and once it is validated then redirect to requested page .in this case it is not working...how to solve this one..please help urgent
my mail id: praveen7k@yahoo.co.in ..please reply to it
Title: Very beautiful   
Name: Paul
Date: 9/9/2010 6:03:59 AM
Comment:
Now I am Write SSO Program! But I don't know how to do it!
so I want to get this code to study!I from china!
Thank you!
Title: ConnectionSection properties cannot be edited when locked   
Name: ravindra
Date: 6/15/2010 12:49:07 PM
Comment:
Hi,
I am getting this error message.
ConfigurationSection properties cannot be edited when locked.
Title: Very usefull article   
Name: Indra
Date: 5/20/2010 11:03:35 AM
Comment:
This is a very nice article... very usefull, got the same problem like u mentioned on ure article. I've tried it. And it works well. Thx
Title: Good to know such implementation   
Name: Milind
Date: 5/6/2010 12:36:26 AM
Comment:
Good to know such implementation, nice article. Hope to get such solutions.

Will this work on different App Domains as well??
Title: Login problem   
Name: Jaini
Date: 4/9/2010 6:34:19 AM
Comment:
Working fine in local machine with diffreent websites But when I host it on the IIS and try to open the 2nd site through the main site then login does not work.
urls example http://site1.mysite.com, http://site2.mysite.com

Kindly Help.
Title: Login not working   
Name: learner
Date: 4/1/2010 6:26:53 AM
Comment:
Given credential are not working on login
Title: How to login...   
Name: Learner
Date: 4/1/2010 6:12:32 AM
Comment:
hi Masoud,

i am new to this please tell me how to log in into it
Title: tyco   
Name: nik
Date: 3/5/2010 2:41:49 AM
Comment:
we r doing project on this we just Love it
Title: Just What I needed   
Name: Ray
Date: 2/4/2010 1:46:39 PM
Comment:
Excellent article and exactly what I have been tryign to find. The article is well written and the examples showed just what I needed to see to adapt it for my use case.

Thanks for posting!
Title: Nice Artcle   
Name: James
Date: 2/1/2010 8:56:29 AM
Comment:
Please is it possible to use the same logic for websites hosted on a different domain. E.g. www.me.com and www.you.com.

Please help me answer the question

Thanks
Title: Nice artile   
Name: James
Date: 2/1/2010 7:17:45 AM
Comment:
Please is it possible to use the same logic for websites hostedon a different domain. E.g. www.me.com and www.you.com.

Please help me answer the question

Thanks
Title: SSO like meebo   
Name: Shawn D Kennedy
Date: 1/9/2010 5:28:15 PM
Comment:
Hello. We would like to use sso to login to multiple sites that we do not own. Is this possible with this script/info? Thanks Shawn
Title: Very limited   
Name: Car Market
Date: 12/6/2009 3:39:04 PM
Comment:
Although useful for applications running under asp.net 2.0, this solution is not open for other applications like php or even asp.net 1.0

Thanks anyway ... good effort
Title: How to achieve SSO authentication for different plateform site like ASP.NET to SAP   
Name: Kalpesh
Date: 11/5/2009 9:07:42 AM
Comment:
Hi,

I want to show SAP dashboard in my asp.net application. I have URL of SAP dashboard, Credentials to access it. But I dont know how to pass credentials with the URL for the user authentication.

Any help would be appreciated.
Title: Mr   
Name: Nick
Date: 8/5/2009 6:26:52 PM
Comment:
Hi,

I just took the code and was trying to run. I am unable to figure out where is the code for authenticating the user to sql server. There is no code is Login.aspx.cs also from is the login page controls like textboxes and buttons coming from...
Title: Mr   
Name: Nitesh Kumar Bahety
Date: 6/22/2009 1:33:51 AM
Comment:
Hi Masoud
This is very usefull article but i am unable to login with the differnt username and password.How i can change the username and password of the website from the membership provider.
Please help
Title: Mr   
Name: Rakesh Singh
Date: 5/24/2009 12:34:49 AM
Comment:
Hi Masoud
I created a SSO application. It works fine when I run it through the source code and 2nd site doesn't need authentication when opened through main site after login. But when I host it on the IIS and try to open the 2nd site through the main site it redirects me to the login page.
Kindly Help.
Title: sample error   
Name: Anton
Date: 5/21/2009 6:23:06 AM
Comment:
hi,
thanks for the article. i've tried it. but your code didn't work at all. probably you've uploaded the wrong code, because i couldn't find any code inside the login.cs and there is no code for connection to sql server. CMIIW thanks
Title: COO   
Name: Garret Grajek
Date: 3/27/2009 11:14:34 AM
Comment:
Love it!

We took "Forms Authentication Across Applications" and built a 2-way, 2-factor authentication appliance that utilizes this wonderful SSO feature and integrated this into ASP.NET, SharePoint, MOSS 3.0, OWA 2003 and OWA 2007.

Please see:
http://www.multifa.com/msapps.aspx

Garret Grajek, CISSP
COO, MultiFactor Corp
www.multifa.com
Title: Tanks   
Name: Amir Goodarzi
Date: 1/12/2009 5:37:52 AM
Comment:
Hello!
very tanks for your article.
waintg for other articles ...

bye
Title: Need Help   
Name: John
Date: 10/16/2008 12:55:31 AM
Comment:
I have 3 ,4 applications currently working with Forms Auth: . I m also usin Membership & role Providers also .i need to login these apps with a single login page.But if a particular user who has logged in does not have permission to another application he should not able to enter to that application he should be redirected to its own some login page or some sort of mechanism needed to deny that user.how to acheive this.
Title: Gr8   
Name: Ravi
Date: 7/28/2008 2:43:18 AM
Comment:
Can we implement this on windows authentication
Title: Need help   
Name: Satyen
Date: 6/13/2008 5:25:18 AM
Comment:
I have an intranet solution that has 2 websites. Once i login to the first application then i should be able to go to the 2nd application and get the username buy which i can get data for application 2 ...please tell me how to do this. Both apps have a login page and are using forms authentication.The user need not login twice Please let me know how to do this?
Title: Manager Application Development   
Name: Satyen
Date: 6/12/2008 3:58:40 AM
Comment:
Great help...
Title: Author Comments   
Name: Masoud Tabatabaei
Date: 3/1/2008 1:57:04 AM
Comment:
About Tomcat, I don't have enough information, sorry.
About the SqlServer you need Microsoft SQL Server Express Edition to run the sample, and the sample has been tested many times and it 's ok.
Title: Complain   
Name: Lê Văn Linh
Date: 2/27/2008 11:34:41 PM
Comment:
Demo can not connect to sql server ,it error about remote to to server,please check and fix,thanks
Title: SSO on multiple websites   
Name: P.Ramprathap
Date: 2/12/2008 2:49:57 AM
Comment:
Its really intresting and iam planned to use it asap . but could you please let me know how to integrate it with other webserver like Tomcat
Title: Good   
Name: Alireza Montazeri
Date: 2/9/2008 4:34:49 AM
Comment:
Hi Mr. Tabatabaei
this article is very important and good.
I waiting for another your articles.
bye
Title: MSDN article on the topic   
Name: smokopilomidanek
Date: 2/8/2008 9:23:56 AM
Comment:
The MSDN article covers it all in more detail: http://msdn2.microsoft.com/en-us/library/ms998288.aspx#paght000007_sharingauthenticationtickets
Title: SSO on multiple websites   
Name: Dave
Date: 2/1/2008 6:10:44 PM
Comment:
Maybe i'm missing something. When I have several websites working together let's say on example1.org, example2.net and example3.com. Because of the different domains example1.org cannot read the cookie of example3.com.

There are even browsers out there which don't even allow sub1.example.com to query cookies for sub2.example.com.

So it's nice that using same machine on several webservers make it possible to 'understand' each other cookies, but the other website will NEVER receive those cookies, because they aren't part of the request headers.

This problem was created somewhere in 1996/1997 when *bad* people started to abuse cookies from other domains using javascript. Microsoft had an even bigger issue with VBScript which was able to access the harddrive and read the cookie files. Nowadays browsers uses sandboxes and using domain scopes to secure the browser and the privacy of the user.

MS Passport is a SSO service. You register once, but can use the credentials on multiple websites.

A workaround is using an automated login page which receives the ProfileID, SessionID and an HMAC generated checksum using password authenticated user as the key. On the targeted website you perform the same checksum generation and when the checksums match, you can set the SessionID.
Title: Answer to some questions   
Name: Masoud Tabatabaei (Author)
Date: 2/1/2008 3:33:02 PM
Comment:
First About ASP.Net 1.1 and 2.0: Yes, you can use it when you have two or more web sites with ASP .NET 1.1 or 2.0.

Jim has asked about SubDomains. It works for each and every web site with the same MachineKey information.

Samit Kumar and Galip Gulsen had problem with login, It's because probably you are not use Microsoft SQL Server 2005 Express Edition and our membership database is working with that.
Muhammad Adnan is asking about what will happen if you disable your cookie? You know the behavior of Membership will still be the same but using the MachineKey config section will help you when your Membership provider is OK.

About the session, normally you will not share information of each application session within the others, but anyway if your are insist of doing that, you can reach that by implementing a Session-State Store Provider.

Finally, thanks for Dave Black comment about Query Strings.
Title: Login Problem   
Name: Samit Kumar
Date: 2/1/2008 2:44:23 AM
Comment:
This Login page is not working.Its not a valid userid and password.
Title: Problem with login   
Name: Galip Gülsen
Date: 2/1/2008 2:34:19 AM
Comment:
I have used the sample code in this site. But, I can't login with the given data, there comes always an error. This happens also in my code.
Best regards.
Title: informative but incomplete solution   
Name: Muhammad Adnan
Date: 2/1/2008 12:25:30 AM
Comment:
its informative somehow but doesn't provide complete solution for SSO. what would be in case of cookie get disable at client side and what about session management (out proc/sql server based)
anyhow its good article. keep it up man :)
Title: Theres better   
Name: NA
Date: 1/31/2008 10:05:30 PM
Comment:
Still have the problem of sessions. Sessions do not go from app to app. We have a portal app with numerous other apps tied to it. We were able to do what you did in half the code and not pass anything in the URL except for a GUID from app to app.
Title: ASP.Net 1.1 and 2.0   
Name: Oran
Date: 1/31/2008 1:08:13 PM
Comment:
Can this work with a main dashboard website in asp.net 2.0 that has links to asp.net 1.1 websites?
Title: Query Strings   
Name: Dave Black
Date: 1/31/2008 12:44:27 PM
Comment:
Just an important note: Query Strings are not secure EVEN when using SSL!

Plus if IIS Logging is setup on the webserver, every request, including the query sring is logged in a clear text file!
Title: What about when the domain changes?   
Name: Jim
Date: 1/31/2008 10:33:09 AM
Comment:
Something like http://myintranet/app provides a link to https://www.myextranet.com?
Title: Query String   
Name: Masoud Tabatabaei
Date: 1/31/2008 2:32:10 AM
Comment:
About the query string you have to use it whenever the is not problem to show it to users. I mean no secure data has to be in query strings. There are also other ways to manipulate state data in ASP.NET which is more secure and will not shown to users. Use hidden field or view state if it 's just the ID and you just want to hide it but notice that ViewState and HiddenField still can be read by pro users. Also you can use Server Side State Management for more security.
Title: Excellent   
Name: shafaqat
Date: 1/31/2008 12:11:47 AM
Comment:
its a very good article and really helpful.
But i have another issue but it is not related to this article
consider this querystring http://localhost/abc/page.aspx?ID=10
i m saving some xyz data against this id, but if user changes this id to 20 data will b saved against id 20
so is there any machanism to hide id in query string
Title: Thankyou   
Name: Jan Eirik
Date: 1/30/2008 6:41:10 PM
Comment:
Thank you so much for writing this article. This is exactly what I need for the admin and portal part of a school project I'm working on atm. Great stuff!
Title: about the U key   
Name: gowhere
Date: 1/30/2008 4:34:03 AM
Comment:
actualy,I want to know of the U key login principle which likes the U disk insert into the plugin and then login.
I don't think I say clearly :)
Title: SSO on across a network of Web servers   
Name: Masoud Tabatabaei
Date: 1/29/2008 12:06:05 AM
Comment:
Yes, If you need to support configuration across a network of Web servers (a Web farm), set the ValidationKey & DecryptionKey property manually to ensure consistent configuration.
Title: Test   
Name: Test
Date: 1/28/2008 12:08:25 PM
Comment:
Does this work if the sites are hosted on different servers?
Title: Nice article   
Name: AH
Date: 1/16/2008 2:09:27 AM
Comment:
I'm sure quite a few people are in need of such a solution.

Product Spotlight
Product Spotlight 





Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2014 ASPAlliance.com  |  Page Processed at 10/21/2014 3:00:05 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search