Section 2 of 6

Cross-Site Scripting (XSS)

🎯 What You'll Learn

  • What is XSS
  • Types of XSS attacks
  • Razor automatic encoding
  • @Html.Raw() dangers
  • Content Security Policy

What is XSS?

Cross-Site Scripting (XSS) is an injection attack where malicious scripts are injected into trusted websites. The attacker's script executes in the victim's browser.

Types of XSS

1. Stored XSS (Persistent)

Malicious script stored in database and displayed to all users.

Example Attack JavaScript
// User submits comment:
<script>alert('XSS')</script>

// Stored in database, executed when displayed

2. Reflected XSS

Malicious script in URL, reflected back to user.

Example Attack Text
https://example.com/search?q=<script>alert('XSS')</script>

3. DOM-based XSS

Client-side JavaScript modifies DOM with untrusted data.

Razor Automatic Encoding

Razor automatically HTML-encodes output, preventing XSS.

Safe (Automatic Encoding) HTML
@Model.UserInput

<!-- If UserInput = "<script>alert('XSS')</script>" -->
<!-- Rendered as: &lt;script&gt;alert('XSS')&lt;/script&gt; -->

@Html.Raw() Dangers

@Html.Raw() bypasses encoding - use with extreme caution!

Dangerous (No Encoding) HTML
@Html.Raw(Model.UserInput)

<!-- Script executes! DANGEROUS! -->
⚠️ Warning

Only use @Html.Raw() with trusted, sanitized content. Never with user input!

Sanitizing HTML

If you must allow HTML, use a sanitizer library.

Install HtmlSanitizer Bash
dotnet add package HtmlSanitizer
Sanitize HTML C#
var sanitizer = new HtmlSanitizer();
var clean = sanitizer.Sanitize(userInput);

// Now safe to use with @Html.Raw()
@Html.Raw(clean)

Content Security Policy (CSP)

CSP header restricts which scripts can execute.

Add CSP Header C#
app.Use(async (context, next) =>
{
    context.Response.Headers.Add(
        "Content-Security-Policy",
        "default-src 'self'; script-src 'self'");
    await next();
});

Best Practices

  • Trust Razor encoding: Don't use @Html.Raw() with user input
  • Validate input: Reject suspicious input
  • Sanitize HTML: Use HtmlSanitizer if HTML is needed
  • Use CSP: Restrict script sources
  • HttpOnly cookies: Prevent JavaScript access to cookies

Key Takeaways

  • XSS: Malicious scripts injected into pages
  • Razor encoding: Automatic protection
  • @Html.Raw(): Dangerous with user input
  • HtmlSanitizer: Clean untrusted HTML
  • CSP: Restrict script execution