XSS and CSRF Protection

Advanced 25 min read Lesson 4 of 6

Cross-Site Scripting (XSS)

XSS occurs when malicious scripts are injected into trusted websites.

Prevention

1. Input Encoding

// Razor automatically encodes output
<div>@userInput</div> // HTML encoded

// For manual encoding
@Html.Raw(HttpUtility.HtmlEncode(userInput))

2. Content Security Policy (CSP)

// Add CSP header
app.Use(async (context, next) =>
{
    context.Response.Headers.Add("Content-Security-Policy",
        "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'");
    await next();
});

3. Anti-XSS Library

// Install: dotnet add package Microsoft.Security.Application
using Microsoft.Security.Application;

string safeInput = Sanitizer.GetSafeHtmlFragment(userInput);

Cross-Site Request Forgery (CSRF)

CSRF tricks a user into performing unwanted actions on a website where they're authenticated.

Prevention in ASP.NET Core

1. Anti-Forgery Tokens

// In forms
<form method="post">
    @Html.AntiForgeryToken()
    // or
    <input type="hidden" name="__RequestVerificationToken" 
           value="@Html.AntiForgeryToken()" />
</form>

2. Validate Tokens

// Auto-validation for all POST requests
[AutoValidateAntiforgeryToken]
public class SomeController : Controller { }

// Manual validation
[ValidateAntiForgeryToken]
public IActionResult PostMethod() { }

3. Global Configuration

// Program.cs
builder.Services.AddAntiforgery(options => 
{
    options.HeaderName = "X-CSRF-TOKEN";
    options.SuppressXFrameOptionsHeader = false;
});

4. SameSite Cookies

builder.Services.ConfigureApplicationCookie(options =>
{
    options.Cookie.SameSite = SameSiteMode.Strict;
    options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
});
Key Takeaway

Prevent XSS by encoding user input and using CSP. Prevent CSRF with anti-forgery tokens and SameSite cookies.

Test Your Knowledge - Take Quiz