Say a authentication filter of MVC (iv)

Source: Internet
Author: User
Tags httpcontext ticket

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)

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.