I. Overview
Second, what is XSS
Iii. Methods of prevention
Iv. how to achieve in WEBAPI
Before implementation, you need to understand the pipeline mechanism of the ASP.
As above, the parameters can be filtered in various ways
1, rewrite the Delegatinghandler SendAsync method to filter, combined with ANTIXSS class library implementation
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingsystem.web;usingSystem.Web.Http;usingSYSTEM.WEB.MVC;usingSystem.Web.Optimization;usingSystem.Web.Routing;usingSystem.Web.Http.Controllers;usingMicrosoft.Security.Application;usingSystem.Reflection;usingSystem.ComponentModel;usingSystem.Threading;usingSystem.Net.Http;namespacemynamespace{ Public classAntixsshttpmessagehandler:delegatinghandler {protected OverrideSystem.threading.tasks.taskSendAsync (httprequestmessage Request, System.Threading.CancellationToken cancellationtoken) {foreach(varKeyinchRequest.RequestUri.ParseQueryString (). AllKeys) {varValue =sanitizer.getsafehtmlfragment (Request.RequestUri.ParseQueryString () [key]); if(Value! =Request.RequestUri.ParseQueryString () [key]) { Throw NewException (); } } return Base. SendAsync (Request, CancellationToken); } }}
Public Static classWebapiconfig { Public Static voidRegister (httpconfiguration config) {config. Routes.maphttproute (Name:"Defaultapi", Routetemplate:"Api/{controller}/{id}", defaults:New{id =routeparameter.optional}); Config. Enablesystemdiagnosticstracing (); Config. Messagehandlers.add (NewAntixsshttpmessagehandler ()); } }
2, rewrite the Invokeactionasync method of Apicontrolleractioninvoker
Public classXssactioninvoker:apicontrolleractioninvoker { Public OverrideSystem.threading.tasks.task<system.net.http.httpresponsemessage>Invokeactionasync (Httpactioncontext filtercontext, System.Threading.CancellationToken cancellationtoken) { Dictionary<string,Object> changedictionary =Newdictionary<string,Object>(); foreach(varParainchfiltercontext.actionarguments) {if(para. Value.gettype () = =typeof(string)) { varValue = para. Value as string; if(!string. Isnullorwhitespace (value)) {Value=sanitizer.getsafehtmlfragment (value); Changedictionary.add (para. Key, value); } } } foreach(varChangeparainchchangedictionary) {Filtercontext.actionarguments[changepara.key]=Changepara.value; } return Base. Invokeactionasync (Filtercontext, CancellationToken); } }
Public class WebApiApplication:System.Web.HttpApplication { protectedvoid Application_Start () { GlobalConfiguration.Configuration.Services.Replace (typeofnew Xssactioninvoker ( )); } }
How to make the ASP. NET Web API prevent XSS attacks globally