Use Cookies to implement ASP. NET cross-origin Single Sign-On

Source: Internet
Author: User

At the beginning, I learned how to use ASP. when using NET to log on, Session is used as the logon credential. However, as more and more functions of the website are available in the future, we want to break down the functions of the website, similar to CSDN, each website sub-category has its own domain name, such as news.mysite.com and blog.mysite.com. But the problem is that the Session cannot be used across applications and then searched on the website, however, all the sub-websites are found to be merged into the main website, which shows that this approach is extremely unreasonable;

Then the following is my idea.

Use Cookies as logon creden instead of Session as logon creden

1: create two websites, News.MySite.com and Blog.MySite.com, in IIS. (Note that these websites are redirected to the Hosts file. You can search for them online if you do not understand them ), note that you must have a website with a domain name. Otherwise, the Host Header such as 127.0.0.1 or localhost cannot store domain Cookies.

2: Add appsetting in the Web. config of the two websites

 <appSettings>
<add key="RootDomain" value="mysite.com"/>
<add key="PrivateKey" value="12345678"/>
</appSettings>

This is to make it easier for the website to change the domain name without changing the code. PrivateKey is used to prevent the tampering of Cookies and add an MD5 verification function to follow the online banking function.

3: Compile Cookies

Using system; using system. web; namespace Z. core. tools {// <summary> /// cookie operation class /// </Summary> public class cookie {/// <summary> /// set a cookie /// </Summary> /// <Param name = "name"> name </param> /// <Param name = "value"> value </param> Public static void set (string name, string Value) {set (name, value, 0 );} /// <summary> /// set a cookie // </Summary> /// <Param name = "name"> name </param> /// <Param name = "Value"> value </param> // <Param name = "expiresdays"> expiration time </param> Public static void set (string name, string value, int expiresdays) {// Delete the same cookie foreach (string item in httpcontext. current. response. cookies. allkeys) {// remove if (item = Name) {httpcontext. current. response. cookies. remove (name) ;}} httpcookie mycookie = new httpcookie (name); If (system. configuration. confi Gurationmanager. deleetask[ "rootdomain"] = NULL) {Throw new exception (Lang. define. get (Lang. defineenum. rootdomain _ not set);} mycookie. domain = system. configuration. configurationmanager. deleetask[ "rootdomain"]; If (value! = NULL) {mycookie. value = system. web. httputility. urlencode (value ). replace ("+", "% 20");} // if the value is null, delete this cookie If (value = NULL & expiresdays = 0) {expiresdays =-1;} If (expiresdays! = 0) {datetime expires = datetime. now. adddays (expiresdays); mycookie. expires = expires;} httpcontext. current. response. cookies. add (mycookie );} /// <summary> /// delete a cookie /// </Summary> /// <Param name = "name"> name </param> Public static void delele (string name) {set (name, "",-1 );} /// <summary> /// obtain a valid cookie // </Summary> /// <Param name = "name"> name </param> /// <returns> value </returns> Public sta TIC string get (string name) {string result = NULL; foreach (string item in httpcontext. current. response. cookies. allkeys) {If (item = Name) {If (httpcontext. current. response. cookies [name]. expires> datetime. now | httpcontext. current. response. cookies [name]. expires = new datetime (1, 1, 1) {// If the cookie is determined to be valid, obtain the valid new value result = system. web. httputility. urldecode (httpcontext. current. response. cook IES [name]. value); return result;} If else {// is invalid, return NULL. current. request. cookies [name]! = NULL) {result = system. web. httputility. urldecode (httpcontext. current. request. cookies [name]. value. replace ("% 20", "+");} return result ;} /// <summary> /// clear cookie /// </Summary> Public static void clear () {for (INT I = 0; I <= httpcontext. current. request. cookies. count-1; I ++) {// when the cookie name is not ASP. net_sessionid is deleted, because deleting this cookie will lead to re-creation of the session link if (httpcontext. current. request. cookies [I]. Name. tolower ()! = "Asp.net _ sessionid") {set (httpcontext. Current. Request. Cookies [I]. Name, "",-1 );}}}}}

 

4: Write logon creden

Using system; using system. collections. generic; using system. LINQ; using system. text; namespace Z. core. tools {// <summary> /// website Cookie set /// </Summary> public class cookiegrouptemplate {/// <summary> // log on to the user // </Summary> Public static string usercode {get {checkkey (); return Z. core. tools. cookie. get ("usercode");} set {z. core. tools. cookie. set ("usercode", value); setkey () ;}/// <summary> // /Login username // </Summary> Public static string username {get {checkkey (); Return Z. core. tools. cookie. get ("username");} set {z. core. tools. cookie. set ("username", value); setkey ();}} /// <summary> /// logon user's parent code /// </Summary> Public static string parentcode {get {checkkey (); Return Z. core. tools. cookie. get ("parentcode");} set {z. core. tools. cookie. set ("parentcode", value); setkey () ;}/// <Su Mmary> // The parent name of the logon user /// </Summary> Public static string parentname {get {checkkey (); Return Z. core. tools. cookie. get ("parentname");} set {z. core. tools. cookie. set ("parentname", value); setkey ();}} /// <summary> /// logon permission group /// </Summary> Public static string groups {get {checkkey (); Return Z. core. tools. cookie. get ("groups");} set {z. core. tools. cookie. set ("groups", value); setkey ();}}/// <Summary> /// operation location /// </Summary> Public static string operatefrom {get {return Z. core. tools. cookie. get ("operatefrom");} set {z. core. tools. cookie. set ("operatefrom", value );}} /// <summary> /// encryption cookie definition /// </Summary> static list <string> cookiekeys = new list <string> () {"usercode ", "username", "parentcode", "parentname", "groups", "operatefrom "}; /// <summary> /// generate the verification key /// </Summary> stati C void setkey () {string key = ""; foreach (VAR s in cookiekeys) {key + = s; Key + = "="; Key + = cookie. get (s); Key + = "&";} key + = settinggrouptemplate. privatekey; Key = key. tomd5 (); cookie. set ("privatekey", key) ;}/// <summary >/// verify cookie /// </Summary> static void checkkey () {string key = ""; foreach (VAR s in cookiekeys) {key + = s; Key + = "="; Key + = cookie. get (s); Key + = "&";} string PR Ivatekey = cookie. get ("privatekey"); If (privatekey = NULL) {string _ key = ""; foreach (VAR s in cookiekeys) {_ key + = s; _ key + = "="; _ key + = "&";} If (Key = _ key) {setkey (); Return ;}} key + = settinggrouptemplate. privatekey; Key = key. tomd5 (); If (privatekey = NULL) {} If (key! = Privatekey) {Throw new exceptionmessage (Lang. defineenum. Cookie verification error. Define ());}}}}

 

----------------------------------------

Okay. By default, I add several frequently used values to my Cookies to perform MD5 verification when reading these Cookies to ensure the security of Cookies.

Then, you only need to reference the above two classes in your website project,

Then write code on any website

Z. Core. Tools. CookieGroupTemplate. UserCode = "123 ";

Then use code on other websites

Z. Core. Tools. CookieGroupTemplate. UserCode;

Can be read to get the Login User ID

Isn't it easy ....

 

Source: http://www.cnblogs.com/JerryBaxia/archive/2010/08/22/1805648.html

You are welcome to reprint it, but you must retain the copyright.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.