Asp.net Single Sign-On Solution

Source: Internet
Author: User
Tags asymmetric encryption

Asp.net Single Sign-On Solution

Wu jian2009-06-24

OriginalArticle, Reprint must indicate the source: http://www.cnblogs.com/wu-jian

 

Preface

This is an old article written in. It introduces the design, process, implementation key points, and Asp.net of Single Sign-On (SSO ).CodeDemo. Recently, I sorted out the article, re-painted UML, and rewritten the code in the demo. As a learning memo, it is a great honor to help people. At the same time, my personal abilities are limited. please correct me if you have any shortcomings in this article.

To facilitate the description, we first define several uniform nouns, which are described as follows.

Main Site:Passport centralized verification server, in the demo: http://www.passport.com/

Substation:Http://www.a.com/?http://www. B .com/?http://www.c.com/

Credential:The authentication ID generated after a user logs on. It is used to identify authorized users. The main site in the demo uses the cache and the sub-site uses the session.

Token:Passport issues a unique authentication ID for users that can be circulated in different substations. Cookies are used in the demo.

 

Core Logic

With centralized authentication, user data is stored in passport, and all sub-stations use passport for logon and authentication, as shown in <Figure 1>:

<Figure 1>

<Figure 2>

<Figure 2> describes the single sign-on logic and process in detail.

Process 1: anonymous users access substation

When an anonymous user accesses an authorization page on Substation A, he first jumps to the master station for logon authentication by account and password. After the authentication is passed, the master station creden。 are generated, and a token is generated, which redirects back to substation.

At this time, substation A detects that the user has a token, So it uses the token to go to the master site again to obtain the User Token. After obtaining the token, the user is allowed to access the authorization page. Generate local creden。 for substation A at the same time.

When the user needs to verify again, the local credential will be used to reduce network interaction.

Process 2: users logging on to substation A to access substation B

Because the user has logged on to substation A and has held a token, substation B will use the token to obtain the user token from the main site. After obtaining the token, the user can access the authorization page. Generate local creden。 for substation B at the same time.

 

Key Points

Token

Tokens are issued by the primary site. The primary site issues tokens to generate user creden; at the same time, and records the relationship between the tokens and user creden; to respond to the corresponding creden; Based on the token provided by the user;

Tokens must be circulated in cross-origin substations. Cookies are used in the demo and cookie. Domain = "passport.com" is specified ";

How do substations share the cookies of the main station? From the substation redirect to the main site page, then the page reads the cookie and returns it as a URL parameter. You can view the detailed implementation in the Demo code.

  //   Generate a token  httpcookie tokencookie =  New  httpcookie ("   passport. token   " ); tokencookie. domain  =  "  passport.com  "  ;   //   you can use a custom  algorithm  to avoid illegal cookie copying  ///   tokencookie. values. add ("key", "encryption algorithm");  tokencookie. values. add ( "  value  "  , tokenvalue ); response. appendcookie (tokencookie);  

In the previous article, readers mentioned the security problem caused by illegal copying of tokens (cookies.

First, the cookie is set by default to disable the browser, that is, the user will continue to open the browser after successful authentication to cause the token to leak.

Then there is an expiration time item in the passport token design. You can also use the expiration time of the token to ensure the token security.

If you think it is not enough, you only need to add some custom logic during token verification, such as using time and user features to generate a hash value as the security key of the token.

This article focuses on the SSO logic. The code in some details is not perfect, and readers can improve it according to their actual needs.

 

Master site credential

The master site credential is a relational table that contains three fields: Token, user credential, and expiration time.

The master site creden have multiple implementation methods to choose from. For example, you can use the database if it is reliable, and you can use the cache if it requires performance. In the demo, I use the cache. The following code is used:

 ///   <Summary>  ///  Initialize cache Data Structure  ///   </Summary>  ///  <Remarks>  ///  ----------------------------------------------------  ///  | Token | Cert | timeout |  ///  | ------------------------------------------------ |  ///   </Remarks>  Private   Static   Void  Cacheinit (){  If (Httpcontext. Current. cache ["  Passport. Token  " ] = Null  ) {Datatable dt = New  Datatable (); DT. Columns. Add (  "  Token  " , Type. GetType ( "  System. String  "  ); DT. Columns [  " Token  " ]. Unique = True  ; DT. Columns. Add (  "  CERT  " , Type. GetType ( "  System. Object  "  ); DT. Columns [  "  CERT  " ]. Defaultvalue = Null ; DT. Columns. Add (  "  Timeout  " , Type. GetType ( "  System. datetime  "  ); DT. Columns [  "  Timeout  " ]. Defaultvalue = datetime. Now. addminutes ( Double . Parse (system. configuration. configurationmanager. receivettings [ "  Timeout "  ]); Datacolumn [] keys = New Datacolumn [ 1  ]; Keys [  0 ] = DT. Columns [ "  Token  "  ]; DT. primarykey = Keys;  //  The cache expiration time is the token expiration time * 2 Httpcontext. Current. cache. insert ( " Passport. Token  " , DT, Null , Datetime. maxvalue, timespan. fromminutes ( Double . Parse (system. configuration. configurationmanager. receivettings [ "  Timeout  " ]) * 2  ));}} 

 

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, when he accesses substation A again, he does not have to use the token to go to the main station for verification, because substation A already has creden for this user.

The substation creden。 are relatively simple and can be used with session and cookie.

 

Substation SSO Page Base

The sub-station page that uses SSO performs a series of logical judgment processes, as shown in <Figure 2>. It would be very complicated to write this 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:

 Public   Class  Authbase: system. Web. UI. Page {  Protected   Override   Void  Onload (eventargs e ){  If (Session [ "  A. Cert  " ]! = Null  ){ //  Substation credential exists Response. Write ( "  Congratulations! The substation credential exists. You are authorized to access this page!  "  );}  Else  {  //  Token verification result returned              If (Request. querystring [ "  Token  " ]! = Null ){  //  Hold token                  If (Request. querystring [ "  Token  " ]! = "  $ Token $  "  ){  String Tokenvalue = request. querystring [ "  Token  " ];  //  Call WebService to obtain the master site credential  //  Prevent token forgery  //  You can also use the asymmetric encryption policy of the public key and private key. SSO. sitea. servicereference1.passportservicesoapclient passportservice = New  SSO. sitea. servicereference1.passportservicesoapclient ();  Object CERT = Passportservice. tokengetcert (tokenvalue );  If (CERT! = Null  ){  //  The token is correct. Session [ "  A. Cert  " ] = CERT; response. Write (  "  Congratulations! The token exists. You are authorized to access this page!  "  );}  Else {  //  Incorrect token. log on to passport  Response. Redirect (SSO. Common. Tools. tokenreplace ());}}  //  Log on to passport without a token                  Else  {Response. Redirect (SSO. Common. Tools. tokenreplace ());}}  //  No token verification is performed. Pass passport verification.              Else {  //  Add the token parameter to the current URL  Response. Redirect (SSO. Common. Tools. tokenurl ());}}  Base  . Onload (e );}}  //  End Class 

User logout

<Figure 3>

When the user exits, the master site token/credential and all substation creden。 are cleared. In the demo, call WebService to clear the user's master site token/credential, and use IFRAME to clear the creden of each substation. See the detailed code implementation in the demo.

 

Master site expiration token/credential clearing

Readers can implement this logic by themselves and regularly clear records whose timeout field in ["passport. Token"] exceeds the current time.

 

Demo

Demo Development Environment

. NET Framework 4.0

Visual Studio 2012

 

Configure a 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/

 

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/

 

Download demo

Http://files.cnblogs.com/wu-jian/wujian_sso.rar

 

<Full text>

 

Author: Wu Jian
Source: http://www.cnblogs.com/wu-jian/
The copyright of this article is shared by the author and the blog Park. You are welcome to repost it, but you must specify the source and provide the original article connection clearly on the article page. Otherwise, you will be held legally liable.

Related Article

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.