How would you secure an ASP.NET Core web app against threats?

Focus on SQL injection, CSRF protection, and XSS prevention using ASP.NET Core features.
Build an ASP.NET Core security plan: block injection, prevent CSRF, and stop XSS with encoding, CSP, and least privilege.

answer

Strong ASP.NET Core security layers validation, encoding, and built-in guards. Prevent SQL injection with EF Core LINQ and parameterized queries—no string concatenation—and least-privilege DB users. Enable CSRF protection via antiforgery tokens and secure SameSite cookies. Add XSS prevention with Razor contextual encoding, sanitization, and a strict Content Security Policy. Harden headers (HSTS, nosniff), use DTOs to avoid over-posting, and log/alert on blocked attempts.

Long Answer

Treat the internet as hostile and every input as untrusted. An effective ASP.NET Core security approach uses defense in depth so SQL injection, CSRF protection, and XSS prevention each have multiple layers, favoring framework primitives over custom code.

1) SQL injection
Never build SQL with strings. Use EF Core LINQ and compiled queries; when raw SQL is unavoidable, use FromSqlInterpolated or DbParameter so values are parameterized. Separate DB users by environment/service and grant only required CRUD rights—avoid ALTER/DROP. Scope access by schema or vetted stored procedures. Validate inputs with Data Annotations (Required, StringLength, Range) or FluentValidation; reject unknown fields and clip excessive lengths. Maintain allowlists for enums/state transitions to prevent logic abuse. Add database firewall rules and auditing; ship slow/abnormal query patterns to your SIEM to catch probing early. These practices embody EF Core parameterized queries as a first-class control against injection.

2) CSRF protection
In cookie-based auth, enable antiforgery on all state-changing endpoints using [ValidateAntiForgeryToken] and @Html.AntiForgeryToken(). Mark auth cookies HttpOnly, Secure, and set SameSite=Lax or Strict by default; use SameSite=None; Secure only for trusted cross-site flows. Validate Origin/Referer for sensitive POST/PUT/DELETE requests. Keep GET idempotent; move mutations behind POST with automatic token validation. For SPAs, prefer bearer tokens in the Authorization header (not cookies) to shrink the CSRF surface. Together, antiforgery tokens, SameSite cookies, and origin checks provide robust CSRF protection with minimal friction.

3) XSS prevention
Razor encodes output by default—don’t disable it. Avoid Html.Raw unless content is sanitized. Apply contextual encoders: HtmlEncoder, UrlEncoder, JavaScriptEncoder. For rich text, use an allowlist sanitizer (e.g., Ganss.XSS) and persist only sanitized HTML. Enforce Content Security Policy: block unsafe-inline, require script nonces, and whitelist domains. Add HSTS, X-Content-Type-Options: nosniff, Referrer-Policy, and frame-ancestors in CSP to stop clickjacking. Run CSP in report-only first, fix violations, then enforce. These moves anchor your XSS prevention program.

4) Binding, over-posting, and uploads
Bind to DTOs, not domain entities; use [FromBody]/[FromForm] explicitly and Bind to whitelist properties. Enable SuppressInferBindingSourcesForParameters to prevent accidental binding. Set model-binding limits; reject unknown fields and oversized payloads. Validate file uploads by size, MIME, and magic bytes; rename and store outside wwwroot; scan and serve via controlled endpoints.

5) Auth, secrets, and sessions
Prefer OpenID Connect via Microsoft.Identity.Web; keep cookies short-lived with rotation, and use replay protection (nonce, state). For service-to-service, add mTLS or private networking. Externalize secrets to a vault (Azure Key Vault or AWS Secrets Manager) and rotate regularly—never commit secrets.

6) Observability and testing
Emit structured JSON logs with trace_id/request_id; correlate via Serilog or Application Insights. Alert on spikes in antiforgery failures, validation errors, and CSP violations. Automate security checks in CI: SAST (CodeQL/SecurityCodeScan), DAST (OWASP ZAP), dependency audits. Add unit tests that assert parameterization; add integration tests for antiforgery and encoders. Publish a concise developer checklist: EF Core parameterized queries, antiforgery on mutations, nonce-based Content Security Policy, hardened cookies, DTO binding, upload hygiene, and security headers. Together, these controls keep ASP.NET Core security tight while preserving developer velocity.

Table

Threat Primary control Framework / Headers Outcome
SQL injection EF Core parameterized queries FromSqlInterpolated, DbParameter Inputs cannot reshape SQL
CSRF Antiforgery + SameSite cookies [ValidateAntiForgeryToken], Origin checks Forged requests blocked
XSS Contextual encoding + sanitization Razor encoders, Ganss.XSS Script payloads neutralized
Over-posting DTOs + explicit binding [FromBody], Bind allowlist Hidden fields can’t mutate state
Headers HSTS, Content Security Policy, nosniff Nonces, frame-ancestors, Referrer-Policy Safer browser defaults
Uploads Validate + scan + store outside webroot Size/MIME/magic bytes Risky files defanged
Secrets Vault + rotation Key Vault / Secrets Manager Credentials out of code
Logging Structured JSON + IDs Serilog, App Insights Fast correlation / forensics

Common Mistakes

String-building SQL instead of EF Core parameterized queries. Turning on Html.Raw and echoing user input. Shipping cookie-based endpoints without antiforgery and assuming SameSite “solves” CSRF protection. Trusting only client-side validation; server accepts oversized or unknown fields. Binding domain entities directly, enabling over-posting of sensitive properties. No Content Security Policy, or a lax one with unsafe-inline and wildcard scripts. Long-lived cookies without HttpOnly/Secure. Accepting uploads by extension only, skipping magic-byte checks and scanning. Secrets in appsettings.json or source control. No logs for antiforgery failures, XSS sanitizer hits, or CSP reports—attacks slip by without a trace.

Sample Answers (Junior / Mid / Senior)

Junior:
“I rely on EF Core parameterized queries and LINQ to stop injection. I enable antiforgery on POST/PUT/DELETE and set cookies to HttpOnly, Secure, and SameSite. For XSS prevention, I keep Razor encoding on, sanitize rich text, and add a basic Content Security Policy.”

Mid:
“Repositories enforce parameterization; DTO binding prevents over-posting. Antiforgery tokens plus Origin checks provide reliable CSRF protection. A nonce-based Content Security Policy and sanitizers block XSS. Secrets live in a vault; headers (HSTS, nosniff, frame-ancestors) harden defaults. Structured logs track validation/antiforgery failures.”

Senior:
“We standardize an ASP.NET Core security baseline: least-privilege DB roles, antiforgery on mutations, DTOs, upload hygiene. CSP ships report-only, then enforced with nonces. OIDC with short-lived cookies, rotation, and replay protection. CI runs SAST/DAST; CSP reports feed the SIEM to tune XSS prevention continuously.”

Evaluation Criteria

Expect a concrete ASP.NET Core security plan covering SQL injection, CSRF protection, and XSS prevention. Strong answers show EF Core parameterized queries, least-privilege DB users, and validated models. CSRF: antiforgery on mutations, HttpOnly/Secure cookies with correct SameSite, plus Origin checks. XSS: contextual Razor encoding, sanitized HTML, and a nonce-based Content Security Policy; headers (HSTS, nosniff, frame-ancestors, Referrer-Policy). Look for DTO binding to stop over-posting, upload validation/scanning, secret management via a vault, structured JSON logging with correlation IDs, and alerts for antiforgery/CSP events. Bonus: CI pipelines (CodeQL/ZAP), dependency auditing, and a living checklist used in code reviews

Preparation Tips

Build a sample CRUD app with repositories and DTOs; write unit tests that fail if SQL is concatenated—proving EF Core parameterized queries. Enable antiforgery on POST/PUT/DELETE and verify HttpOnly/Secure/SameSite cookies; add Origin validation for sensitive routes. Create a nonce-based Content Security Policy (report-only first), then enforce; sanitize rich text with Ganss.XSS and confirm Razor encoding blocks reflected XSS. Validate uploads (size, MIME, magic bytes), scan, rename, and store outside wwwroot. Add Serilog/Application Insights with trace_id/request_id; alert on antiforgery failures, model-validation spikes, and CSP reports. Document a brief ASP.NET Core security checklist and rehearse it in mock reviews.

Real-world Context

A fintech cut injection risk by migrating ad-hoc SQL to EF Core parameterized queries and locking DB roles to CRUD; probing inputs showed up in logs but couldn’t alter queries. A marketplace fixed CSRF protection by applying antiforgery across all writes, setting SameSite correctly after SSO, and validating Origin; forged actions stopped. An e-commerce team removed Html.Raw, sanitized stored HTML, and enforced a nonce-based Content Security Policy; XSS alerts plummeted and rendering stabilized. Another product hardened uploads (magic bytes, scanning) and wired structured logs to a SIEM; malicious archives were detected within minutes, and the incident playbook reduced MTTR during peak traffic.

Key Takeaways

  • Make EF Core parameterized queries your default; least-privilege DB users.
  • Apply CSRF protection: antiforgery tokens, SameSite cookies, Origin checks.
  • Enforce XSS prevention: Razor encoding, sanitizers, strict Content Security Policy.
  • Use DTOs to block over-posting; validate and scan uploads.
  • Externalize secrets; log and alert on blocked events for fast response.

Practice Exercise

Scenario:
You inherit a content-heavy ASP.NET Core app with cookie auth, user uploads, and a few raw SQL endpoints. Reports show odd query strings, surprise state changes, and script tags in comments. Your goal: harden security without torpedoing UX.

Tasks:

  1. Replace raw SQL with EF Core LINQ or FromSqlInterpolated + DbParameter; assign least-privilege DB roles per environment and enable query logging.
  2. Add antiforgery to all POST/PUT/DELETE; ensure cookies are HttpOnly, Secure, and correctly SameSite; validate Origin/Referer on sensitive routes; keep GET idempotent.
  3. Enforce Razor contextual encoding; remove Html.Raw. Sanitize rich text (Ganss.XSS) and store only sanitized content.
  4. Ship a nonce-based Content Security Policy (no unsafe-inline); add HSTS, nosniff, and frame-ancestors.
  5. Prevent over-posting with DTOs and explicit binding; reject unknown fields and clamp lengths.
  6. Validate uploads (size, MIME, magic bytes), scan, rename, store outside wwwroot, and serve via controlled endpoints.
  7. Add structured logging (JSON) with correlation IDs; alert on antiforgery failures, sanitizer hits, CSP reports, and suspicious DB patterns.

Deliverable:
A 60–90s walkthrough + test/telemetry screenshots proving SQL injection is neutralized, CSRF protection holds, and XSS prevention works under load.

Still got questions?

Privacy Preferences

Essential cookies
Required
Marketing cookies
Personalization cookies
Analytics cookies
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.