非MVC模式创建的WebAPI 2.0防范XSS攻击的安全措施咨询
Hey there! Since you're working with Web API 2.0 (not an MVC app, no Startup.cs, relying on Global.asax.cs), here are targeted XSS prevention steps you can implement right away:
Encode All Output Data
The most critical step is ensuring any data your API returns is properly encoded to prevent browsers from interpreting it as executable script. Since you're usingJsonMediaTypeFormatter, you can configure it to automatically HTML-escape all string values. Update yourApplication_Startmethod in Global.asax.cs like this:protected void Application_Start() { System.Web.Http.GlobalConfiguration.Configure(WebApiConfig.Register); var jsonFormatter = new JsonMediaTypeFormatter(); // Enable HTML escaping for all string properties in JSON responses jsonFormatter.SerializerSettings.StringEscapeHandling = Newtonsoft.Json.StringEscapeHandling.EscapeHtml; System.Web.Http.GlobalConfiguration.Configuration.Formatters.Clear(); System.Web.Http.GlobalConfiguration.Configuration.Formatters.Add(jsonFormatter); // Rest of your existing code... AreaRegistration.RegisterAllAreas(); RouteConfig.RegisterRoutes(RouteTable.Routes); Hangfire.GlobalConfiguration.Configuration.UseSqlServerStorage("HangfireConnection"); }This ensures that strings like
<script>alert('xss')</script>get converted to\u003cscript\u003ealert(\u0027xss\u0027)\u003c/script\u003e, which is safe when rendered by front-end code.Validate and Sanitize Input
Don't trust any user input! Add validation to your models to block malicious characters, and sanitize content if you need to allow HTML (like rich text):- Model Validation: Use data annotations to restrict allowed input characters:
public class UserInputModel { [RegularExpression(@"^[a-zA-Z0-9\s.,!?]*$", ErrorMessage = "Input contains invalid characters")] public string Comment { get; set; } } - HTML Sanitization: If you must accept HTML, use a library like Microsoft Anti-Cross Site Scripting Library (AntiXSS) to clean the input:
using Microsoft.Security.Application; // Sanitize user-provided HTML to remove malicious tags string safeHtml = Sanitizer.GetSafeHtmlFragment(userSubmittedHtml);
- Model Validation: Use data annotations to restrict allowed input characters:
Add Content Security Policy (CSP) Headers
CSP acts as an extra layer of defense by telling browsers which sources of content are allowed. Add this to your Global.asax.cs to define a strict policy:protected void Application_BeginRequest() { // Allow only scripts and resources from your own domain Response.Headers.Add("Content-Security-Policy", "default-src 'self'; script-src 'self'; style-src 'self'"); }This prevents browsers from executing any injected scripts even if XSS slips through your other defenses.
Secure Cookies (If Used)
If your API uses cookies for authentication or session management, mark them asHttpOnlyandSecureto prevent XSS from stealing them. Add this method to yourWebApiApplicationclass:protected void Application_EndRequest() { if (Response.Cookies.Count > 0) { foreach (string cookieName in Response.Cookies.AllKeys) { var cookie = Response.Cookies[cookieName]; cookie.HttpOnly = true; // Prevents access via JavaScript cookie.Secure = Request.IsSecureConnection; // Only send over HTTPS } } }Disable Unsafe Features
- JSONP: JSONP is inherently risky for XSS. If you haven't explicitly enabled it, you're good—but if you have, remove the JSONP formatter from your Web API config:
// In WebApiConfig.Register method config.Formatters.Remove(config.Formatters.JsonFormatter); // Or if you need JSON, use the escaped formatter we configured earlier instead - Avoid returning HTML: Stick to JSON responses (which you're already doing) instead of HTML, since HTML is more vulnerable to XSS injection.
- JSONP: JSONP is inherently risky for XSS. If you haven't explicitly enabled it, you're good—but if you have, remove the JSONP formatter from your Web API config:
内容的提问来源于stack exchange,提问作者Ramakrishna Reddy

