FormsAuthenticationTicket identity authentication based on ASP.MVC bill

Source: Internet
Author: User
Tags httpcontext ticket

Do a basic business requirement the user logs in, sends the user's identity back to the client's cookie, and then the user accesses the Web app, which is sent to the server along with the identity cookie. The authorization settings on the server can control the access authorization of different users according to different directories.

1. Scene

When the user logs on successfully to the cookie to add a global static variable, jump to the main interface if the user authentication information fails to re-jump to the login screen

2. Code

2.1 Setting Cookies

  /// <summary>        ///Login Verification/// </summary>        /// <returns></returns>[HttpPost] [allowanonymous] PublicActionResult Setcookie (stringLoginName,stringpwd) {Adminlogininfo Admin=NewAdminlogininfo (); Admin. LoginName=LoginName; Admin. PWD=pwd; //data into TicketFormsAuthenticationTicket ticket =NewFormsAuthenticationTicket (1,"Login", DateTime.Now, DateTime.Now.AddMinutes ( -),false, Newtonsoft.Json.JsonConvert.SerializeObject (admin)); //Data Encryption            stringEnyticket =Formsauthentication.encrypt (ticket); HttpCookie Cookies=NewHttpCookie (ticket.            Name, Enyticket); if(ticket. ispersistent) {cookie. Expires=ticket.            expiration;            } Response.Cookies.Add (cookie); return  This. Json (New{success =true, msg ="Success" }); }  

2.2 Controller base class Basecontroller

[Authorizeadmin]      Public class Basecontroller:controller    {        protected adminlogininfo info = adminlogininfo. Get ();    }

2.3 Authorizeadmin Custom Permission Authentication

Inherit Authorizeattribute and rewrite

Call processing an HTTP request that fails to authorize when the procedure requests authorization

  Public classAuthorizeadmin:authorizeattribute {protected Override BOOLAuthorizecore (HttpContextBase HttpContext) {Adminlogininfo Info= Adminlogininfo.Get(); BOOLPass =false; if(Info = =NULL) {HttpContext.Response.StatusCode=401; Pass=false; }            Else{Pass=true; }            returnPass; }               protected Override voidhandleunauthorizedrequest (AuthorizationContext filtercontext) {Base.            Handleunauthorizedrequest (Filtercontext);            FilterContext.HttpContext.Response.Write (FilterContext.HttpContext.Response.StatusCode); if(FilterContext.HttpContext.Response.StatusCode = =401) {Filtercontext.result=NewRedirectresult ("/home/login"); }        }    }

2.4 Global User logon information

    Public classAdminlogininfo { Public StaticAdminlogininfoGet() {HttpCookie Cook= httpcontext.current.request.cookies["Login"]; if(Cook = =NULL)            {                return NULL; }            Else if(Cook.) Value = =NULL)            {                return NULL; } adminlogininfo Mode=NULL; Try{FormsAuthenticationTicket AuthTicket=Formsauthentication.decrypt (Cook.                Value); Mode= newtonsoft.json.jsonconvert.deserializeobject<adminlogininfo>(Authticket.userdata); //Dealer Simulation Login                returnmode; }            Catch            {                return NULL; }                }         Public stringLoginName {Get;Set; }  Public stringPWD {Get;Set; } }

FormsAuthenticationTicket identity authentication based on ASP.MVC bill

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.