ASP. NET MVC Cookie authentication

Source: Internet
Author: User
Tags ticket

1 Creating an ASP. NET MVC Project

Add a AccountController class.

 Public classAccountcontroller:controller {[HttpGet] PublicActionResult Login (stringRETURNURL) {viewbag.returnurl = RETURNURL;returnView (); } [HttpPost] PublicActionResult Login (stringUserName,stringPasswordstringRETURNURL) {if(Checklogin (userName, password)) {//Add notes//Save identity informationAccountmodel Modeluser =NewAccountmodel () {UserName = UserName, Password = Password};stringUserData = Jsonconvert.serializeobject (Modeluser);//Serialize user entityFormsAuthenticationTicket Ticket =NewFormsAuthenticationTicket (1, UserName, DateTime.Now, DateTime.Now.AddHours (1),false, UserData); HttpCookie Cookie =NewHttpCookie (Formsauthentication.formscookiename, Formsauthentication.encrypt (Ticket));//Encrypt identity information, save to CookieRESPONSE.COOKIES.ADD (Cookie);if(string. IsNullOrEmpty (RETURNURL)) {returnRedirect ("~/home/index"); }Else{returnRedirect (RETURNURL); }                           }Else{returnView ("Login",Newresultmodel<string> () {Code = 1, Message ="User name or password error"}); }                    } PublicActionResult Logout () {formsauthentication.signout ();returnRedirecttoaction ("Login"); }Private BOOLChecklogin (stringUserName,stringPassword) {returnMvcApplication.DBList.Any (n = n.username = = UserName && N.password = = Password); }    }

2 Add a custom attribute to filter the identity login
 Public classCheckloginattribute:actionfilterattribute { Public Override voidOnActionExecuting (ActionExecutingContext filtercontext) {//If identity information exists            if(! HttpContext.Current.User.Identity.IsAuthenticated) {Contentresult Content =NewContentresult ();stringURL =string. Format ("{0}?returnurl={1}", Formsauthentication.loginurl, FILTERCONTEXT.HTTPCONTEXT.REQUEST.RAWURL); Content.content =string. Format ("<script type= ' text/javascript ' >alert (' Please login first! '); window.location.href= ' {0} ';</script> ', URL);            Filtercontext.result = Content; }//else            //{            //string[] Role = CheckLogin.Instance.GetUser (). Roles.split (', ');//Get all roles            //if (! Role.contains (Code))//Verify Permissions            //    {            //// verification does not pass            //Contentresult Content = new Contentresult ();            //Content.content = "<script type= ' text/javascript ' >alert (' permission validation does not pass! '); History.go ( -1);</script> ";            //Filtercontext.result = Content;            //    }            //}}    }

3 Set up Web. config, be sure to add mode= "Forms"
  <system.web> ...     .    <authentication mode="Forms">      <forms loginurl="~/account/login" name= ". Iamshop " ></forms>    </authentication> ...  </system.web>
4 where you need to add permission validation: Mark a [Checklogin] property
 [Checklogin] public  actionresult Index () {            //Get login information             Viewbag.username = User.Identity.Name;           //Get Object             //formsidentity ticket = (formsidentity) user.identity;  HttpCookie Authcookie = Httpcontext.request.cookies[formsauthentication.formscookiename];            //get cookie  FormsAuthenticationTicket Ticket = Formsauthentication.decrypt (Authcookie.value);           //decryption  //accountmodel account = (Accountmodel) jsonconvert.deserializeobject (ticket.userdata);//deserialization             Accountmodel account= jsonconvert.deserializeobject<accountmodel> (ticket.userdata); Viewbag.accountname = account.            UserName; Viewbag.password = account.            Password; return         View (); }
Online authentication Code A lot, reference to do after a note, need to use, according to the circumstances to modify the use.

ASP. NET MVC Cookie authentication

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.