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