You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

非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 using JsonMediaTypeFormatter, you can configure it to automatically HTML-escape all string values. Update your Application_Start method 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):

    1. 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; }
      }
      
    2. 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);
      
  • 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 as HttpOnly and Secure to prevent XSS from stealing them. Add this method to your WebApiApplication class:

    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.

内容的提问来源于stack exchange,提问作者Ramakrishna Reddy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:46:44