Log Aggregation :👈 👉:MSBuild-Index

Security Basics: XSS Prevention and Input Sanitization

XSS Prevention and Input Sanitization in ASP.NET Core

πŸ” Understanding XSS (Cross-Site Scripting)

  • Definition: XSS is a vulnerability where attackers inject malicious scripts into web applications. These scripts run in the victim’s browser, potentially stealing cookies, session tokens, or sensitive data.
  • Impact:
    • Account impersonation
    • Theft of sensitive information
    • Defacement of websites
    • Bypassing CSRF protections

πŸ›‘οΈ XSS Prevention Techniques

  • Input Validation:
    • Accept only expected formats (e.g., numbers for age, email regex for email fields).
    • Reject or escape unexpected characters.
  • Output Encoding:
    • Encode data before rendering in HTML, JavaScript, or URLs.
    • Example: Convert <script> into &lt;script&gt; so it displays as text, not executable code.
  • Contextual Escaping: Use different escaping depending on where data is placed (HTML, attributes, JavaScript, CSS).
  • Content Security Policy (CSP): Restrict sources of scripts, styles, and media. Prevent inline scripts from executing.
  • Framework Security: Modern frameworks (React, Angular) automatically escape outputs, reducing XSS risks.
  • Web Application Firewalls (WAFs): Block known malicious payloads before they reach the application.

1. What Is XSS?

XSS (Cross-Site Scripting) is a web security vulnerability in which an attacker causes malicious JavaScript to execute in another user's browser through a vulnerable website.

This usually happens when an application accepts user input and displays it on a web page without handling it safely.

Example: Imagine a website that allows users to submit comments. A malicious user submits HTML containing JavaScript instead of a normal comment. If the application displays that content unsafely, the browser may execute the script.

Example of Unsafe Input

<script>
    alert('XSS Attack');
</script>

If an application inserts this input directly into an HTML page without proper encoding, the browser may execute the JavaScript.

Important: XSS is a client-side browser security vulnerability, but it often originates from unsafe server-side handling of user input or output.

2. Types of XSS Attacks

1. Stored XSS (Persistent XSS)

Stored XSS occurs when malicious content is saved in a database and later displayed to other users without proper output encoding.

Example:

User submits a comment Application saves comment Comment stored in database Another user opens the page Unsafe content is rendered Browser executes malicious script

Common vulnerable areas:

  • Comments.
  • Product reviews.
  • User profile descriptions.
  • Forum posts.
  • Support tickets.

2. Reflected XSS

Reflected XSS occurs when user-controlled input is included in an immediate server response without proper output encoding.

Example: A search page displays the search term entered by the user.

If the application renders that value as executable HTML instead of displaying it as text, it may introduce an XSS vulnerability.

User sends search input Server receives request Application uses input in response Unsafe HTML is returned Browser may execute script

3. DOM-Based XSS

DOM-based XSS occurs when client-side JavaScript takes untrusted data and inserts it into the page using an unsafe DOM operation.

For example, using innerHTML with untrusted data can cause a vulnerability.

// Unsafe JavaScript
const search = new URLSearchParams(
    window.location.search
).get('search');
document.getElementById('result').innerHTML = search;

The problem is not necessarily the server response. It is the unsafe way client-side JavaScript handles the data.

3. What Is Input Sanitization?

Input sanitization means processing untrusted input to remove or neutralize content that is not permitted by the application's requirements.

However, sanitization is not the primary defense against every XSS vulnerability.

Different types of input require different handling:

Input TypeRecommended Handling
NameValidate length and allowed characters.
EmailValidate email format and length.
Phone numberValidate according to the expected format.
Plain-text commentsValidate input and encode when displaying.
Rich HTML contentUse a trusted HTML sanitization library with an explicit allowlist.
URLValidate allowed schemes and destinations before using it.

Key principle: Validate input when it enters the application and encode output according to the context in which it is displayed.

4. Input Validation in ASP.NET Core

ASP.NET Core supports input validation through data annotations and model validation.

Example: Product Model

using System.ComponentModel.DataAnnotations;
public class Product
{
    public int Id { get; set; }
    [Required]
    [StringLength(100, MinimumLength = 2)]
    public string Name { get; set; } = string.Empty;
    [Range(1, 1000000)]
    public decimal Price { get; set; }
}

Controller Example

[ApiController]
[Route("api/products")]
public class ProductsController : ControllerBase
{
    [HttpPost]
    public IActionResult CreateProduct(Product product)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }
        return Ok(new
        {
            Message = "Product is valid",
            Product = product
        });
    }
}

With [ApiController], ASP.NET Core automatically returns a 400 Bad Request response when model validation fails, unless that behavior has been customized.

Note: Input validation checks whether the data meets application rules. It does not replace output encoding or HTML sanitization.

5. Preventing XSS Through Output Encoding

Output encoding is one of the most important defenses against XSS.

Output encoding converts special characters into representations that the browser treats as data instead of executable markup.

For example:

CharacterHTML Encoded Representation
<&lt;
>&gt;
&&amp;
"&quot;

Razor View Example

Razor automatically HTML-encodes ordinary variable output.

@model string
<h2>User Comment</h2>
<p>@Model</p>

If the model contains HTML or script-like text, Razor displays it as text rather than treating it as executable HTML.

Unsafe Razor Example

@Html.Raw(Model)

Why is this dangerous?

Html.Raw() tells Razor not to HTML-encode the supplied content. If the content is untrusted, it can introduce an XSS vulnerability.

Use Html.Raw() only when the HTML has been safely sanitized for the intended context or comes from a trusted source.

6. Preventing XSS in ASP.NET Core Web APIs

ASP.NET Core Web APIs commonly return JSON rather than HTML.

Returning user input as JSON is generally safer than inserting it directly into an HTML page, because JSON serialization encodes data according to JSON rules.

However, a frontend application can still introduce XSS if it takes the returned data and inserts it into the DOM unsafely.

Example API

[HttpGet("{id}")]
public IActionResult GetComment(int id)
{
    var comment = _context.Comments
        .FirstOrDefault(x => x.Id == id);
    if (comment == null)
    {
        return NotFound();
    }
    return Ok(comment);
}

The frontend should display the returned comment as text rather than inserting it as raw HTML.

7. Preventing XSS in JavaScript and React

If an ASP.NET Core backend serves a React frontend, both backend and frontend security practices are important.

Unsafe JavaScript

element.innerHTML = userInput;

Safer JavaScript

element.textContent = userInput;

textContent treats the supplied value as text instead of parsing it as HTML.

React Example

React safely renders ordinary string values as text by default.

function Comment({ message }) {
    return (
        <div>
            {message}
        </div>
    );
}

Avoid using dangerouslySetInnerHTML with untrusted content.

// Potentially unsafe
function Comment({ message }) {
    return (
        <div
            dangerouslySetInnerHTML={{
                __html: message
            }}
        />
    );
}

If rendering user-provided rich HTML is genuinely required, sanitize it with a maintained HTML sanitizer and a restrictive allowlist before rendering.

8. HTML Sanitization in ASP.NET Core

Sometimes an application needs to allow users to submit formatted HTML, such as bold text, lists or links.

In that situation, simply removing the <script> tag is not sufficient. HTML can contain dangerous event handlers, URL schemes and other executable constructs.

Use a well-maintained HTML sanitization library with an explicit allowlist of permitted tags, attributes and URL schemes.

Example Using HtmlSanitizer

One commonly used .NET library is HtmlSanitizer from the Ganss.Xss package.

Install the package:

dotnet add package HtmlSanitizer

Example:

using Ganss.Xss;
public class HtmlContentService
{
    private readonly HtmlSanitizer _sanitizer;
    public HtmlContentService()
    {
        _sanitizer = new HtmlSanitizer();
        _sanitizer.AllowedTags.Clear();
        _sanitizer.AllowedTags.Add("p");
        _sanitizer.AllowedTags.Add("strong");
        _sanitizer.AllowedTags.Add("em");
        _sanitizer.AllowedTags.Add("ul");
        _sanitizer.AllowedTags.Add("ol");
        _sanitizer.AllowedTags.Add("li");
        _sanitizer.AllowedTags.Add("a");
    }
    public string Sanitize(string html)
    {
        return _sanitizer.Sanitize(html);
    }
}

Usage:

var contentService = new HtmlContentService();
string userHtml = "<p>Hello</p>";
string safeHtml = contentService.Sanitize(userHtml);

Important: This is an example of an allowlist approach. Review the library's supported configuration and explicitly restrict allowed attributes and URL schemes according to your application requirements. Sanitization does not make HTML safe for every possible output context.

9. Content Security Policy (CSP)

Content Security Policy is an additional browser security mechanism that helps reduce the impact of XSS attacks.

CSP allows developers to define which sources the browser can load scripts, styles, images and other resources from.

Example CSP Header

Content-Security-Policy:
default-src 'self';
script-src 'self';
object-src 'none';
base-uri 'self';
frame-ancestors 'none';

Explanation:

  • default-src 'self' restricts resources to the application's own origin by default.
  • script-src 'self' allows scripts from the same origin.
  • object-src 'none' blocks plugin-based content.
  • base-uri 'self' restricts the document's base URL.
  • frame-ancestors 'none' prevents the page from being embedded in frames.

Configure CSP in ASP.NET Core Middleware

app.Use(async (context, next) =>
{
    context.Response.Headers.Append(
        "Content-Security-Policy",
        "default-src 'self'; script-src 'self'; object-src 'none'; base-uri 'self'; frame-ancestors 'none'");
    await next();
});

Place the middleware early enough so that the header is added to the relevant responses.

Best practice: Start with a Content Security Policy in report-only mode, examine violations, and then enforce a suitable policy. Avoid allowing inline scripts broadly with 'unsafe-inline'. Nonces or hashes can support legitimate inline scripts when necessary.

10. HTTP Security Headers in ASP.NET Core

Security headers provide additional protection for web applications.

HeaderPurpose
Content-Security-PolicyRestricts permitted resource sources and helps mitigate XSS.
X-Content-Type-OptionsPrevents browsers from MIME-sniffing responses when set to nosniff.
Strict-Transport-SecurityInstructs browsers to use HTTPS for the configured period.
Referrer-PolicyControls how much referrer information is sent.
Permissions-PolicyControls access to selected browser features.

Example Middleware

app.Use(async (context, next) =>
{
    context.Response.Headers.Append(
        "X-Content-Type-Options",
        "nosniff");
    context.Response.Headers.Append(
        "Referrer-Policy",
        "strict-origin-when-cross-origin");
    await next();
});

Configure HTTPS redirection and HSTS appropriately for production deployments:

if (!app.Environment.IsDevelopment())
{
    app.UseHsts();
}
app.UseHttpsRedirection();

11. Common XSS Prevention Mistakes

MistakeCorrect Approach
Using Html.Raw() with untrusted input.Use normal Razor output or sanitize HTML when rich content is required.
Assuming validation alone prevents XSS.Use context-appropriate output encoding.
Removing only script tags.Use a trusted HTML sanitizer with an allowlist.
Using innerHTML with user input.Use textContent when displaying plain text.
Trusting data because it comes from a database.Treat stored user content as untrusted when rendering it.
Assuming JSON serialization prevents all XSS.Handle data safely when the frontend displays it.
Relying only on CSP.Use CSP as an additional defense, not a replacement for safe rendering.
Allowing arbitrary HTML attributes.Allow only required tags and attributes.

12. Best Practices for XSS Prevention in ASP.NET Core

  1. Validate all untrusted input using appropriate application rules.
  2. Use Razor's automatic HTML encoding.
  3. Avoid Html.Raw() for untrusted content.
  4. Use a trusted HTML sanitizer when rich HTML is required.
  5. Use context-specific encoding for HTML, attributes, JavaScript, CSS and URLs.
  6. Avoid inserting untrusted values into JavaScript or CSS contexts.
  7. Use textContent instead of innerHTML for plain text.
  8. Use a restrictive Content Security Policy.
  9. Keep frontend frameworks and sanitization libraries updated.
  10. Review third-party scripts and dependencies.
  11. Test stored, reflected and DOM-based XSS scenarios.
  12. Treat data retrieved from databases as untrusted if it originated from users.

13. XSS Prevention Flow in ASP.NET Core

User Input ASP.NET Core API Input Validation Business Logic Database Storage Retrieve Data Context-Appropriate Output Encoding Browser Displays Data Safely

If rich HTML is required, sanitize it using an allowlist before storing or rendering it, and still use the correct output handling for its destination context.

14. Common Interview Questions and Answers

Q1. What is XSS?

Cross-Site Scripting is a security vulnerability in which malicious scripts execute in a user's browser through a vulnerable web application.

Q2. What are the three main types of XSS?

Stored XSS, reflected XSS and DOM-based XSS.

Q3. What is the difference between input validation and output encoding?

Input validation checks whether incoming data meets application requirements. Output encoding ensures that data is displayed as text rather than interpreted as executable content in a particular output context.

Q4. How does ASP.NET Core Razor prevent XSS?

Razor automatically HTML-encodes ordinary variable output. This helps prevent user-provided HTML from being interpreted as executable markup.

Q5. Why is Html.Raw() dangerous?

Html.Raw() disables Razor's automatic HTML encoding for the supplied value. Using it with untrusted content can introduce XSS vulnerabilities.

Q6. Does ASP.NET Core automatically sanitize all user input?

No. ASP.NET Core provides model binding and validation capabilities, but developers must handle untrusted content appropriately through validation, output encoding and HTML sanitization where required.

Q7. What is Content Security Policy?

CSP is a browser security mechanism that restricts the sources from which a page can load resources. It provides an additional layer of protection against XSS.

Q8. Is input sanitization enough to prevent XSS?

No. Sanitization is useful when accepting rich HTML, but output encoding appropriate to the destination context is essential. Input validation and CSP provide additional protection.

Q9. How do you prevent XSS in a React frontend with an ASP.NET Core backend?

Use ASP.NET Core validation, return data using appropriate JSON serialization, render ordinary values through React's normal text interpolation and avoid unsafe HTML insertion. Sanitize rich HTML before rendering it.

Q10. What is the difference between XSS and SQL Injection?

XSS targets users' browsers by causing unwanted script execution. SQL Injection targets database queries by manipulating SQL statements. Parameterized queries help prevent SQL Injection, while context-aware output encoding and safe HTML handling help prevent XSS.

15. Final Takeaway

  • Input validation: Checks whether incoming data follows application rules.
  • Input sanitization: Removes or neutralizes disallowed content when required, especially for rich HTML.
  • Output encoding: Displays untrusted data safely in the intended context.
  • Content Security Policy: Adds browser-level protection by restricting resource sources.
  • Safe frontend rendering: Avoids inserting untrusted content as executable HTML.

Most important rule: Never trust user input. Validate it, encode it for the output context, and sanitize it when accepting rich HTML. Do not rely on a single security mechanism to prevent XSS.

🧹 Input Sanitization

  • Whitelist Filtering: Define allowed characters/inputs (e.g., only digits for phone numbers).
  • Blacklist Filtering (Less Secure): Block known dangerous inputs (e.g., <script> tags). Not foolproof, as attackers can bypass with obfuscation.
  • Libraries & Tools: Use trusted sanitization libraries (DOMPurify for JavaScript, OWASP ESAPI for Java).
  • Server-Side Enforcement: Never rely solely on client-side validation. Always sanitize and validate inputs on the server.

βš–οΈ Comparison Table

Aspect XSS Prevention Input Sanitization
Goal Stop malicious scripts from executing Ensure user input is safe and expected
Techniques Encoding, CSP, WAF, framework security Whitelisting, regex validation, libraries
Focus Output handling Input handling
Strengths Protects against runtime attacks Blocks malicious payloads early
Weaknesses Needs contextual encoding, CSP setup Blacklists can be bypassed
Best Practice Combine with sanitization for full safety Always validate on server-side

🚨 Risks & Trade-offs

  • Over-reliance on Blacklists: Attackers can bypass filters with encoded payloads.
  • Improper Encoding: Encoding in the wrong context (e.g., HTML vs. JavaScript) can still leave vulnerabilities.
  • Performance Trade-offs: CSP and WAFs may add overhead but are critical for security.

Bottom Line

Effective security requires a layered approach: sanitize inputs, validate formats, encode outputs, and enforce CSP. Relying on a single technique is insufficient; combining multiple defenses is the best way to prevent XSS and ensure safe input handling.

Official Documentation and References

πŸ”™
Log Aggregation :👈 👉:MSBuild-Index