. NET single sign-on design and practice _ practical skills

Source: Internet
Author: User
Tags httpcontext md5 encryption ticket

Objective

Recently my turn to share knowledge points in group morning, suddenly thought of single sign-on, ready to share under how to achieve a single sign-on, so there are below. The implementation and code may not be written in a very rigorous, loophole, or wrong place.

Just start thinking in mind, directly in the blog to see how others are to achieve, read a few articles found that the solution has a bit of a problem, or do not count to achieve a single sign-on

Name definition

For the sake of explanation, first explain the meaning of the nouns that appear in several texts:

P Station: Unified login Authorization Verification Center, demo domain name is www.passport.com:801

A station: Under the different domain name test website, demo domain name is www.a.com:802

B Station: Under the different domain name test website, demo domain name is www.b.com:803

Token: User access to P station secret key

Ticket: An encrypted string used to hold user information

Single point of entry

Visit a station need to log in on the jump P station for landing, p station after landing jump back to a station, users visit B station need to log on the page, users do not need to log on to the operation can be normal access.

Realize the idea

Not logged in user access to a station, the first redirect to jump to the P Station authorization center, p station first through the detection of cookies to determine the current is not in the landing state, jump to the landing page for landing operations, the successful landing after the user information encryption ticket attached to a request address on the return, A station through decryption ticket to obtain user information, decryption successfully coexist in the session (so that the user is in a login state), access through; When the user visits B station again, for B station, the user is not logged in state, the same will redirect to the P Station authorization center, P Station to detect cookies, to determine the current user in the landing state, the current user information encryption into the ticket attached to the request address B return, the following operation and a station processing the same; So after landing again access to a or b,a and B in the session has stored the user information, would not ask for P station again.

Simple diagram

Swim Lane Flowchart

Main logical Description

A Station main logic

Users first visit a station, a station will generate token, and stored in the cache. Token is a key to access p, and p needs to carry this token when a callback is given to a. A request P,p Verify TOKEN,P callback A,a detect token is sent out token, after verification token is invalidated, prevent token to be used again.

The generation of token is generated by MD5 encryption by taking different fields of timestamp, of course it can be added with a salt for anti-counterfeiting.

<summary>
    ///generate secret key
    ///</summary>
    ///<param name= "timestamp" ></param>
    <returns></returns> public
    static string Createtoken (DateTime timestamp)
    {
      StringBuilder SecurityKey = new StringBuilder (Md5encypt (timestamp. ToString ("yyyy")));
      Securitykey.append (Md5encypt) (timestamp. ToString ("MM"));
      Securitykey.append (Md5encypt) (timestamp. ToString ("DD"));
      Securitykey.append (Md5encypt) (timestamp. ToString ("HH"));
      Securitykey.append (Md5encypt) (timestamp. ToString ("MM"));
      Securitykey.append (Md5encypt) (timestamp. ToString ("ss")));
      Return Md5encypt (Securitykey.tostring ());
    }

p to call a when the time to do, a in the token to verify that the checksum is unsuccessful, request P station Unified authorization verification.

<summary>///Authorization Enumeration///</summary> public enum Authcodeenum {public = 1, Login = 2} <summary>///Authorization Filter///</summary> public class Authattribute:actionfilterattribute {///&

    lt;summary>///Permission Code///</summary> public Authcodeenum code {get; set;} 
    <summary>///Validation Permissions///</summary>///<param name= "Filtercontext" ></param> public override void OnActionExecuting (ActionExecutingContext filtercontext) {var request = Filtercontext.httpc Ontext.
      Request;
      var session = FilterContext.HttpContext.Session; If there is an identity information if (Common.currentuser = = null) {if (Code = = authcodeenum.public) {RET
        Urn
        } string reqtoken = request["Token"];
        String ticket = request["Ticket"];
        Cache cache = HttpContext.Current.Cache; Token is not obtained or token validation is not passed, or the ticket is not fetched from the P callback is requested again P
        Tokenmodel tokenmodel= Cache. Get (Constanthelper.token_key) ==null?null: (Tokenmodel) cache.
        Get (Constanthelper.token_key); if (string. IsNullOrEmpty (Reqtoken) | | Tokenmodel = = NULL | |
          tokenmodel.token!= Reqtoken | | String.
          IsNullOrEmpty (Ticket)) {DateTime timestamp = DateTime.Now; String ReturnUrl = Request.
          Url.absoluteuri; Tokenmodel = new Tokenmodel {TimeStamp = TimeStamp, Token = Authernutil.createtoken (Tim
          Estamp)}; Token added cache, design expiration time is 20 minutes cache. ADD (Constanthelper.token_key, Tokenmodel, NULL, DateTime.Now.AddMinutes (), Cache.noslidingexpiration,
          Cacheitempriority.default, NULL); Filtercontext.result = new Contentresult {Content = Getauthernscript (Authernutil.getautherurl (token
          Model.token, timestamp), ReturnUrl)};
        Return
        } loginservice service = new Loginservice (); var userinfo = sErvice.
        GetUserInfo (ticket);
        Session[constanthelper.user_session_key] = userinfo; Verification through the cache to remove token, to ensure that each token can only be used once cache.
      Remove (Constanthelper.token_key); }///<summary>///generate jump Script///</summary>///<param name= "Authernurl" > Unified License Address < /param>///<param name= "ReturnUrl" > Callback address </param>///<returns></returns> Private St
      Ring Getauthernscript (String authernurl, String returnurl) {StringBuilder sbscript = new StringBuilder ();
      Sbscript.append ("<script type= ' Text/javascript ' >"); Sbscript.appendformat ("window.location.href= ' {0}&returnurl= ' + encodeuricomponent (' {1} ');", AuthernUrl,
      ReturnUrl);
      Sbscript.append ("</script>");
    return sbscript.tostring ();

 }
  }

Code Description: Here to facilitate the setting of token expiration time, so use the cache to access token, set the token expiration time of two minutes, when the success of the verification from the cache to remove token.

Fetch Filter

[Auth (Code = authcodeenum.login)]
     Public ActionResult Index ()
     {return
       View ();
    }

P Station main logic

P Station received authorization request, p station first through Coookie to determine whether to log in, not login to the landing page to the landing operation.

<summary>
    ///Authorized login Verification
    ///</summary>
    ///<returns></returns>
    [HttpPost] Public
    ActionResult passportvertify ()
    {
      var cookie=request.cookies[constanthelper.user_cookie_key];
      if (cookie = = NULL | | String. IsNullOrEmpty (cookies. ToString ()))
      {return
        redirecttoaction ("Login", new {ReturnUrl = request["ReturnUrl"], token= request["Token" "] });
      }
      String userinfo = cookie. ToString ();
      var success= passportservice. Authernvertify (request["Token"], Convert.todatetime (request["TimeStamp"));
      if (!success)
      {return
        redirecttoaction ("Login", new {ReturnUrl = request["ReturnUrl"], Token = request[" Token "]});
      Return Redirect (Passportservice. Getreturnurl (UserInfo, request["Token"],request["ReturnUrl"));
    }

Logged in to verify the token

<summary>
    ///Authentication token
    ///</summary>
    ///<param name= "token" > Token </param>
    // /<param name= "timestamp" > Timestamp </param>
    ///<returns></returns> public
    bool Authernvertify (String token,datetime timestamp)
    {return
      authernutil.createtoken (timestamp) = = token;
    }

Test instructions

1. Modify Host

127.0.0.1 www.passport.com

127.0.0.1 www.a.com

127.0.0.1 www.b.com

2. Deploy IIS

P www.passport.com:801

A www.a.com:802

B www.b.com:803

3, test account and Webconfig

<add key= "Passportcenterurl" value= "http://www.passport.com:801"/>

User name: admin Password: 123

Demo

Download address: Source Download Address

Original link: http://www.cnblogs.com/minesnil-forfaith/p/6062943.html

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.