. Net-based Single Sign-On (SSO) solution (2)

Source: Internet
Author: User
Tags urlencode
[CSHARP]View plaincopy
  1. // Generate a token
  2. String tokenvalue = guid. newguid (). tostring (). toupper ();
  3. Httpcookie tokencookie = new httpcookie ("token ");
  4. Tokencookie. Values. Add ("value", tokenvalue );
  5. Tokencookie. Domain = "passport.com ";
  6. Response. appendcookie (tokencookie );

Master site credential: The master site credential is a relational table that contains three fields: Token, credential data, and expiration time. There are multiple implementation methods to choose from. If you require reliability, you can use the database. If you require performance, you can use the cache. In the demo, I use the datatable in the cache. The following code is used:

[CSHARP]View plaincopy
  1. /// <Summary>
  2. /// Initialize the Data Structure
  3. /// </Summary>
  4. /// <Remarks>
  5. ///----------------------------------------------------
  6. /// | Token | info | timeout |
  7. /// | ---------------------------------------------------- |
  8. /// </Remarks>
  9. Private Static void cacheinit ()
  10. {
  11. If (httpcontext. Current. cache ["Cert"] = NULL)
  12. {
  13. Datatable dt = new datatable ();
  14. DT. Columns. Add ("token", type. GetType ("system. String "));
  15. DT. Columns ["token"]. Unique = true;
  16. DT. Columns. Add ("info", type. GetType ("system. Object "));
  17. DT. Columns ["info"]. defaultvalue = NULL;
  18. DT. Columns. Add ("timeout", type. GetType ("system. datetime "));
  19. DT. Columns ["timeout"]. defaultvalue = datetime. Now. addminutes (double. parse (system. configuration. configurationmanager. etettings ["timeout"]);
  20. Datacolumn [] keys = new datacolumn [1];
  21. Keys [0] = DT. Columns ["token"];
  22. DT. primarykey = keys;
  23. // The cache expiration time is the token expiration time * 2
  24. Httpcontext. current. cache. insert ("Cert", DT, null, datetime. maxvalue, timespan. fromminutes (double. parse (system. configuration. configurationmanager. appsettings ["timeout"]) * 2 ));
  25. }
  26. }

Substation credential: Substation creden are mainly used to reduce network interaction during repeated verification. For example, if a user has logged on to substation A and accessed substation A again, you do not need to use the token to go to the master site for verification, because substation A already has the user's credential. The substation creden。 are relatively simple and can be used with session and cookie.

Substation SSO Page Base: The sub-station uses SSO pages to perform a series of logic judgment processes, such as the flowchart at the beginning of the article. If there are multiple pages, it is impossible to write such logic for each page. OK, then this logic is encapsulated into a base class. Any page that uses SSO can inherit this base class. The following code is used:

[CSHARP]View plaincopy
  1. Using system;
  2. Using system. Data;
  3. Using system. configuration;
  4. Using system. Web;
  5. Using system. Web. Security;
  6. Using system. Web. UI;
  7. Using system. Web. UI. webcontrols;
  8. Using system. Web. UI. webcontrols. webparts;
  9. Using system. Web. UI. htmlcontrols;
  10. Using system. Text. regularexpressions;
  11. Namespace SSO. sitea. Class
  12. {
  13. /// <Summary>
  14. /// Authorization Page Base Class
  15. /// </Summary>
  16. Publicclass authbase: system. Web. UI. Page
  17. {
  18. Protectedoverride void onload (eventargs E)
  19. {
  20. If (session ["token"]! = NULL)
  21. {
  22. // The substation credential exists.
  23. Response. Write ("congratulations, the substation credential exists. You are authorized to access this page! ");
  24. }
  25. Else
  26. {
  27. // Token Verification Result
  28. If (request. querystring ["token"]! = NULL)
  29. {
  30. If (request. querystring ["token"]! = "$ Token $ ")
  31. {
  32. // Hold the token
  33. String tokenvalue = request. querystring ["token"];
  34. // Call WebService to obtain the master site credential
  35. SSO. sitea. refpassport. tokenservice = new SSO. sitea. refpassport. tokenservice ();
  36. Object o = tokenservice. tokengetcredence (tokenvalue );
  37. If (o! = NULL)
  38. {
  39. // The token is correct.
  40. Session ["token"] = O;
  41. Response. Write ("congratulations, the token exists. You are authorized to access this page! ");
  42. }
  43. Else
  44. {
  45. // Token Error
  46. Response. Redirect (this. replacetoken ());
  47. }
  48. }
  49. Else
  50. {
  51. // Token not held
  52. Response. Redirect (this. replacetoken ());
  53. }
  54. }
  55. // Token verification is not performed, go to the master site for verification
  56. Else
  57. {
  58. Response. Redirect (this. gettokenurl ());
  59. }
  60. }
  61. Base. onload (E );
  62. }
  63. /// <Summary>
  64. /// Obtain the URL with the token request
  65. /// Append the token request parameter to the current URL
  66. /// </Summary>
  67. /// <Returns> </returns>
  68. Privatestring gettokenurl ()
  69. {
  70. String url = request. url. absoluteuri;
  71. RegEx Reg = new RegEx (@ "^ .*\?. + =. + $ ");
  72. If (Reg. ismatch (URL ))
  73. URL + = "& token = $ token $ ";
  74. Else
  75. URL + = "? Token = $ token $ ";
  76. Return "http://www.passport.com/gettoken.aspx? Backurl = "+ server. urlencode (URL );
  77. }
  78. /// <Summary>
  79. /// Remove the token from the URL
  80. /// Remove the token parameter from the current URL
  81. /// </Summary>
  82. /// <Returns> </returns>
  83. Privatestring replacetoken ()
  84. {
  85. String url = request. url. absoluteuri;
  86. Url = RegEx. Replace (URL ,@"(\? | &) Token =. * "," ", regexoptions. ignorecase );
  87. Return "http://www.passport.com/userlogin.aspx? Backurl = "+ server. urlencode (URL );
  88. }
  89. } // End class
  90. }


User logout:When the user exits, the master site creden。 and the current substation creden。 are cleared. If you want Site A to exit and site B and Site C to exit, you can expand the interface to clear the creden。 of each substation.
Master site expiration credential/token clearing: Records whose timeout field exceeds the current time in the able cache ["Cert.

Click here to download the demo

1. Configure the site in IIS

Configure four sites to point to the corresponding directory and specify the host headers of the four sites respectively:

Http://www.passport.com/

Http://www.a.com/

Http://www. B .com/

Http://www.c.com/

2. Modify the hosts file to resolve the domain name to the local site.

Http://www.passport.com/127.0.0.1/

Http://www.a.com/127.0.0.1/

Http://www. B .com/127.0.0.1/

Http://www.c.com/127.0.0.1/

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.