Custom authentication requires the implementation of both IIdentity and IPrincipal interfaces, and this process is done in the authenticaterequest phase. The following procedure is a simulation of the implementation of identity authentication, in this way can be stored in the ticket data to initialize the implementation of the IPrincipal, thereby changing the HttpContext.Current.User point to the object instance.
<authentication mode="Forms"> <forms loginurl="a.html " name="Andy"></forms> </authentication>
View Code
1 Public classMyprincipal:iprincipal2 {3 PublicIIdentity Identity4 {5 Get{return NewMyidendity ("AA"); }6 }7 8 Public BOOLIsInRole (stringrole)9 {Ten if(string. Compare (role,"A, b",true) ==0) One { A return true; - } - Else the { - return false; - } - } +}View Code
1 Public classmyidendity:iidentity2 {3 4 PublicMyidendity (stringdata)5 { 6 7 }8 Public stringAuthenticationType9 {Ten Get{return "myidendity"; } One } A - Public BOOLisauthenticated - { the Get{return true; } - } - - Public stringName + { - Get{return "Andy"; } + } A}View Code
1 protected voidPage_Load (Objectsender, EventArgs e)2 {3 stringUserroles ="admin,test";4FormsAuthenticationTicket ticket =NewFormsAuthenticationTicket (5 1,6 "a",7 DateTime.Now,8DateTime.Now.AddMinutes ( -),9 true,Ten Userroles, One "/" A ); - stringHaskticket =Formsauthentication.encrypt (ticket); -HttpCookie Usercookie =NewHttpCookie (formsauthentication.formscookiename,haskticket); the Response.Cookies.Add (Usercookie); - - } - + protected voidButton1_Click (Objectsender, EventArgs e) - { + varContext =HttpContext.Current; A if(Context. User.Identity isformsidentity) at { - if(! (Context. User ismyprincipal)) - { -FormsIdentity forms =(formsidentity) context. user.identity; - stringdata =forms. Ticket.userdata; -Myprincipal principal =NewMyprincipal (); inContext. User =principal; - } to } + } -}View Code
Custom Identity Authentication