Explain Cross-Site Scripting (XSS) and Cross-Site Request Forgery (CSRF)

4 minadvancedsecurityXSSCSRFweb

Quick Answer

XSS injects malicious scripts into pages that other users view, stealing cookies/tokens or performing actions as the victim; prevent it with output encoding (Razor encodes by default), input validation, and a Content Security Policy. CSRF tricks an authenticated user's browser into submitting unwanted requests; prevent it with anti-forgery tokens (`[ValidateAntiForgeryToken]`), SameSite cookies, and verifying the origin. Both exploit trust — XSS abuses the user's trust in a site, CSRF abuses the site's trust in the user's browser.

Detailed Answer

Cross-Site Scripting (XSS)

XSS allows attackers to inject malicious scripts into web pages viewed by other users, stealing cookies, session tokens, or other sensitive information.

Types of XSS:

  • Stored XSS: Malicious script stored in database
  • Reflected XSS: Script reflected off web server
  • DOM-based XSS: Vulnerability in client-side code

Prevention in .NET Core:

  1. Use Razor Encoding (Automatic):
@Model.UserInput  // Automatically HTML encoded
  1. For Raw HTML (Use with Caution):
@Html.Raw(Model.TrustedContent)  // Only for trusted content
  1. Content Security Policy:
app.Use(async (context, next) =>
{
    context.Response.Headers.Add("Content-Security-Policy", 
        "default-src 'self'; script-src 'self' 'unsafe-inline'");
    await next();
});
  1. Anti-XSS Library:
using Microsoft.Security.Application;
string safe = Encoder.HtmlEncode(userInput);

Cross-Site Request Forgery (CSRF)

CSRF forces authenticated users to execute unwanted actions on a web application by exploiting their active session.

Prevention in .NET Core:

  1. Anti-Forgery Tokens (Built-in):
// In Startup.cs
services.AddControllersWithViews(options =>
{
    options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute());
});

// In Razor view

    @Html.AntiForgeryToken()
    


// In Controller
[ValidateAntiForgeryToken]
public IActionResult SubmitForm(FormModel model)
{
    // Process form
}
  1. For AJAX Requests:
// In _Layout.cshtml


// JavaScript
var token = document.querySelector('meta[name="csrf-token"]').content;
fetch('/api/data', {
    method: 'POST',
    headers: {
        'RequestVerificationToken': token
    }
});
  1. SameSite Cookies:
services.ConfigureApplicationCookie(options =>
{
    options.Cookie.SameSite = SameSiteMode.Strict;
    options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
});