Using Delegatinghandler to implement API key validation for Web APIs

Source: Internet
Author: User

    • Providing API key based on QueryString

      http://localhost:57967/Api/Values?key=12345

    • Request header-based Decency API key

New Uri (URL), client. DefaultRequestHeaders.Accept.Clear (); client. DEFAULTREQUESTHEADERS.ACCEPT.ADD (new mediatypewithqualityheadervalue ("application/ JSON"), client. Defaultrequestheaders.add ("x-apikey","00000") ;
Writing Apikeyhandler
 Public classApikeyhandler:delegatinghandler { Public stringKey {Get;Set; }  PublicApikeyhandler (stringkey,httpconfiguration httpconfiguration) {             This. Key =key; Innerhandler=NewHttpcontrollerdispatcher (httpconfiguration); }        protected OverrideTaskSendAsync (httprequestmessage request, CancellationToken CancellationToken) {if(!Validatekey (Request)) {                varResponse =Newhttpresponsemessage (Httpstatuscode.forbidden); varTSC =NewTaskcompletionsource(); Tsc.                Setresult (response); returnTSC.            Task; }            return Base.        SendAsync (Request, CancellationToken); }        Private BOOLValidatekey (Httprequestmessage message) {IEnumerable<string> apikeyheadervalues =NULL; if(Message. Headers.trygetvalues ("X-apikey", outapikeyheadervalues)) {                varApikeyheadervalue =Apikeyheadervalues.first (); return(Apikeyheadervalue = = This. Key)//... your authentication logic here ...                /*var username = (Apikeyheadervalue = = "00000"?)               "Maarten": "OtherUser");                var usernameclaim = new Claim (claimtypes.name, username);                var identity = new Claimsidentity (new[] {usernameclaim}, "ApiKey");                var principal = new ClaimsPrincipal (identity);             Thread.CurrentPrincipal = Principal; */            }            /*var query = message.            Requesturi.parsequerystring ();            string key = query["Key"]; return (key = = this.            Key); */        }
Configure to a specific route up
 config. Routes.maphttproute (name:   " default Api   , Routetemplate:   " api/{controller}/{id}   "  new  {ID = routeparameter.optional}, constraints:  null   new  Apik Eyhandler ( " 12345   "  

Using Delegatinghandler to implement API key validation for Web APIs

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.