1. Define the authentication failure result generator
/// <summary> ///certificate failure result Generator/// </summary> Public classAuthenticationfailureresult:ihttpactionresult { PublicAuthenticationfailureresult (stringreasonphrase, httprequestmessage request) {Reasonphrase=reasonphrase; Request=request; } Public stringReasonphrase {Get;Private Set; } PublicHttprequestmessage Request {Get;Private Set; } PublicTaskExecuteasync (CancellationToken cancellationtoken) {returnTask.fromresult (Execute ()); } Privatehttpresponsemessage Execute () {returnRequest.createerrorresponse (httpstatuscode.unauthorized, This. Reasonphrase); } }
2. Define a custom authentication filter (based on cookies)
/// <summary> ///Custom Certifications/// </summary> Public classCustomauthenticationfilter:attribute, Iauthenticationfilter { Public Virtual BOOLAllowMultiple {Get{return false; } } Public AsyncTask Authenticateasync (httpauthenticationcontext context, CancellationToken CancellationToken) {
varPrincipal =await This. Authenticateasync (context. Request); if(Principal = =NULL) {context. Request.Headers.GetCookies (). Clear (); Context. Errorresult=NewAuthenticationfailureresult ("Request not authorized", context. Request); } Else{context. Principal=principal; } } PublicTask Challengeasync (httpauthenticationchallengecontext context, CancellationToken CancellationToken) { returnTask.fromresult (0); } PrivateTask<iprincipal>Authenticateasync (Httprequestmessage request) {returnTask.run<iprincipal> (() ={cookieheadervalue Cookiemobile= Request. Headers.getcookies ("Clientmobile"). FirstOrDefault (), Cookietoken= Request. Headers.getcookies ("Clienttoken"). FirstOrDefault (); if(Cookiemobile = =NULL|| Cookietoken = =NULL||string. Isnullorwhitespace (cookiemobile["Clientmobile"]. Value)||string. Isnullorwhitespace (cookietoken["Clienttoken"]. Value)) {return NULL; } stringMobile = cookiemobile["Clientmobile"]. Value, token= cookietoken["Clienttoken"]. Value; Clientdto Client=NULL;
Remove the designated user from the Redis server here, you can change your own as neededusing(ICache cache = objectcontainer.current.resolve<icachefactory>(). Createcache ()) {client= Cache. Get<clientdto>(redistables.client, mobile); }
Verify user legitimacy, if legitimate, build declarative security topic permission mode and return if user authentication does not pass return nullif(Client! =NULL&&string. Equals (token, MD5HELPER.MD5 (string. Format ("{0}{1}", mobile, client. Msgcode), +) ( stringcomparison.ordinal)) {IEnumerable<Claim> claims =NewList<claim>() { NewClaim (Claimtypes.name, Mobile)}; varIdentity =NewClaimsidentity ("Loancookie"); Identity. Addclaims (claims); return NewClaimsPrincipal (identity); } return NULL; }); } }
3. Apply the authentication characteristic tag to the global, controller or controller operation, take the controller operation as an example:
ASP. NET Web API Add custom Authentication