ASP. NET Web API Add custom Authentication

Source: Internet
Author: User
Tags redis server

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

Related Article

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.