Frontier:
In general, when we do access management, the user's correct login after the basic information is saved in the session, the user each time the page or interface data request, get
The user basic information stored in the session to see if he has logged in and can access the current page.
The principle of the session, that is, the server side to generate a sessionid corresponding to the stored user data, and SessionID stored in the cookie, the client after each request will take this
Cookie, the server-side finds data stored on the server side of the corresponding current user based on the SessionID in the cookie.
FormsAuthentication is used by Microsoft to provide us developers with the use of identity authentication. With this authentication, we can store the user name and some user data in a cookie,
It is simple to implement basic identity role authentication through the basic condition setting.
1. Configuration Items
Configure Web. config on the site root directory
<authentication> <forms name=". Aspxauth"Loginurl="Account/index"Defaulturl="http://www.baidu.com"protection=" All"timeout=" -"Path="/"Requiressl="false"slidingexpiration="true"enablecrossappredirects="false"cookieless="UseDeviceProfile"domain=""></forms> </authentication>
2. Controller code
Public classAccountcontroller:controller {//Get:account PublicActionResult Index () {returnView (); } [Authentication] PublicActionResult Demo () =View (); [HttpPost] [Validateantiforgerytoken] PublicActionResult Index (stringUsernamestringuserpwd) {List<LoginVm> userlist =NewList<loginvm> ()//Analog Data { NewLOGINVM () {name="Zara", pwd="123456", state=1}, NewLOGINVM () {name="AAAA", pwd="666666", state=0} }; if(!modelstate.isvalid) {returnView (); } BOOLStatus =request.isauthenticated; LOGINVM VMS= UserList. FirstOrDefault (U = u.name = = Username && U.pwd = =userpwd); JavaScriptSerializer Serial=NewJavaScriptSerializer (); //determine presence and status OK if(vm!=NULL) { if(VM. state==0) Content ("you times the number of the seal"); FormsAuthenticationTicket AuthTicket=NewFormsAuthenticationTicket (1, Vm.name, DateTime.Now, DateTime.Now.AddMinutes ( -),false, serial. Serialize (VM)); stringEncrytedticket = Formsauthentication.encrypt (AuthTicket);//Create a ticket//Responding to clientsHttpCookie Authcookie =NewHttpCookie (Formsauthentication.formscookiename,encrytedticket); HTTPCONTEXT.RESPONSE.COOKIES.ADD (Authcookie); } returnView (); } }
3. Filter aspects
/// <summary> ///This filter provides services to the website///Service Content: Behaviors Add tags to filter. Do not filter in every action! /// </summary> Public classAuthenticationattribute:actionfilterattribute { Public Override voidonactionexecuting (ActionExecutingContext filtercontext) {if(!filterContext.RequestContext.HttpContext.Request.IsAuthenticated) {if(FilterContext.HttpContext.Request.IsAjaxRequest ()) {Filtercontext.result=NewJsonresult {Data=New{Status= -1, Message="login expired, please login again!"}, Jsonrequestbehavior=Jsonrequestbehavior.allowget}; } Else{formsauthentication.redirecttologinpage ();//REDIRECT login page } } Else { varCookie =Filtercontext.httpcontext.request.cookies[formsauthentication.formscookiename]; //decrypting a user ticket varTicket =Formsauthentication.decrypt (cookies. Value); //mapping ciphertext to the entity modelLOGINVM admin =NewJavaScriptSerializer (). Deserialize<loginvm>(ticket. UserData); //put the data in the ViewData page usefiltercontext.controller.viewdata["username"] =Admin.name; filtercontext.controller.viewdata["userpwd"] =admin.pwd; } //Don ' t forget this one Base. OnActionExecuting (Filtercontext); } }
We can add a view that requires login in the Aciton behavior so that the package does not have to be one on the controller.
Say a authentication filter of MVC (iv)