1, the principle is to use ActionFilterAttribute to intercept the request, the cookies are decrypted. The user's information is encrypted and stored in the cookie.
Custom Authentication Attributes
[AttributeUsage (AttributeTargets.Class | AttributeTargets.Method, inherited =true, AllowMultiple =true)] Public classFormauthattribute:actionfilterattribute { Public Override voidonactionexecuting (Httpactioncontext actioncontext) {Try { if(Actioncontext.actiondescriptor.getcustomattributes<allowanonymousattribute> (). Count >0) {//filtering the action that allows anonymous access Base. OnActionExecuting (Actioncontext); return; } varCookie = ActionContext.Request.Headers.GetCookies ();//Access to Cookies if(Cookie = =NULL|| Cookies. Count <1) {Actioncontext.response=Newhttpresponsemessage (Httpstatuscode.forbidden); return; } FormsAuthenticationTicket Ticket=NULL; //traverse cookies, obtain authentication cookies and decrypt foreach(varPercookieinchcookie[0]. Cookies) {if(Percookie.name = =formsauthentication.formscookiename) {ticket=Formsauthentication.decrypt (Percookie.value); Break; } } if(Ticket = =NULL) {Actioncontext.response=Newhttpresponsemessage (Httpstatuscode.forbidden); return; } //TODO: Add additional validation methods Base. OnActionExecuting (Actioncontext); } Catch{actioncontext.response=Newhttpresponsemessage (Httpstatuscode.forbidden); } } }
Login Verification API
[Route ("Login")] [allowanonymous] Publicihttpactionresult Login ([Frombody]loginmodel model) {if(model. Username.equals ("Admin") && model. Password.equals ("123456") {Formsauthentication.setauthcookie (model. UserName,false); if(model. Isrememberme) {HttpContext.Current.Response.SetCookie (NewHttpCookie ("UserName", model. UserName) {Expires = DateTime.Now.AddDays (7) }); } returnOk (); } Else { returnNotFound (); } //return Ok ();}
Add the [Formauth] attribute to APIs that require login to access.
form verification of ASP. NET Web API authentication