Volume 2 · Chapter 9 — ASP.NET Core Enterprise Development

Security Hardening

Goutham Mayaluri 8 min read .NETC#ASP.NET CoreSecurity

9.1 Introduction

Security hardening reduces an application’s attack surface through secure coding, defensive architecture, and operational controls. Beyond authentication and authorization, enterprise apps - especially financial ones - must defend against the common web vulnerabilities catalogued by the OWASP Top 10: injection, broken access control, cryptographic failures, misconfiguration, and more. The unifying principle is to never trust external input and to apply layered controls so a single flaw does not become a breach.

9.2 Never Trust Input: Injection and Validation

All external input is untrusted and must be validated at the boundary before reaching business logic. The most dangerous consequence of trusting input is injection - SQL injection being the classic. The defense is parameterized queries (or an ORM like EF Core, which parameterizes automatically), never string- concatenating user input into queries, plus input validation and least-privilege database accounts.


// UNSAFE - string concatenation allows SQL injection:
// var sql = $"SELECT * FROM Users WHERE Name = '{name}'";

// SAFE - parameterized (EF Core / Dapper parameterize for you):
var user = await db.Users.FirstOrDefaultAsync(u => u.Name == name, ct);   // parameterized

9.3 XSS, CSRF, and CORS

XSS(cross-site scripting) injects malicious scripts into content shown to users - defended with output encoding, input validation, a Content-Security-Policy, and avoiding unsafe HTML rendering.CSRFtricks an authenticated user’s browser into unwanted actions - defended with anti-forgery tokens andSameSitecookies.CORScontrols which origins may call your API - in production, restrict to known domains rather than allowing all origins.

9.4 Transport, Headers, and Rate Limiting

All communication must use HTTPS/TLS with valid certificates and weak protocols disabled. Security response headers (Strict-Transport-Security,Content-Security-Policy,X-Content-Type-Options,X-Frame-Options) add browser-side protections. Rate limiting protects against abuse, accidental overload, and denial-of-service.


app.UseHsts();
app.UseHttpsRedirection();
builder.Services.AddRateLimiter(o => o.AddSlidingWindowLimiter("per-user", w =>
{
    w.PermitLimit = 100; w.Window = TimeSpan.FromMinutes(1); w.SegmentsPerWindow = 6;
}));

9.5 Security Logging and Auditing

Security-relevant events - login attempts, authorization failures, administrative actions, sensitive-data access - must be logged (without leaking sensitive data itself) for investigation, compliance, and monitoring. Combined with alerting, this is how intrusions and anomalies are detected. Secrets stay in a vault, never in code or logs (Volume 5, Chapter 9 and Volume 8 cover this in depth).

Senior Interview Question

How do you prevent SQL injection, and why is string concatenation dangerous?

SQL injection happens when untrusted input is incorporated into a SQL query in a way that lets an attacker alter the query’s structure - so if you build a query by concatenating user input directly into the SQL string, a malicious input like' OR '1'='1or'; DROP TABLE Users;--changes what the query does, letting the attacker read, modify, or destroy data or bypass authentication. String concatenation is dangerous precisely because the input becomes part of the executable SQL rather than being treated as data. The primary defense is parameterized queries: you write the query with placeholders and pass the user values as parameters, so the database treats them strictly as data values, never as SQL syntax, and injection is impossible regardless of what the input contains. Using an ORM like EF Core is the common way to get this automatically - LINQ queries and its raw-SQL APIs with parameters are parameterized for you (though you must still use parameters, not string interpolation, with raw SQL). Additional defense-in-depth layers: validate and constrain input at the boundary (type, length, allowed values) so malformed input is rejected early; use least-privilege database accounts so even a successful injection has limited reach (an app account that can’t drop tables); and avoid dynamic SQL where possible. But the core, non-negotiable rule is: never concatenate user input into queries - always parameterize - because parameterization removes the mechanism injection relies on. So I prevent SQL injection by using parameterized queries / an ORM everywhere user input touches the database, backed by input validation and least-privilege database access, and I treat any string-concatenated SQL with user input as a critical vulnerability to fix.

Senior Interview Question

What are XSS and CSRF, and how do you defend against each?

They’re two different web vulnerabilities. XSS (cross-site scripting) is when an attacker gets malicious script injected into content that your application renders to other users’ browsers - for example storing a script in a comment that then executes when others view it (stored XSS), or reflecting unescaped input back in a response (reflected XSS) - and that script runs in the victim’s browser with their session, letting it steal cookies/tokens, perform actions as the user, or deface the page. You defend against XSS by treating output as the danger point: encode/escape all user-supplied content when rendering it (so it’s displayed as text, not executed as markup/script) - modern frameworks like Razor auto-encode by default - validate input, avoid rendering raw HTML from untrusted sources, and add a Content-Security-Policy header that restricts which scripts can run as a strong second layer. CSRF (cross-site request forgery) is different: it tricks an already-authenticated user’s browser into sending an unwanted state-changing request to your site, relying on the browser automatically attaching the user’s cookies - so a malicious page can cause the user’s browser to submit, say, a transfer request to your bank without the user intending it. You defend against CSRF with anti-forgery tokens (a per-session/per-request token the legitimate form/app includes and the server validates, which the attacker’s cross-site request can’t know), and withSameSitecookie attributes (SameSite=Lax/Strict) that prevent the browser from sending your cookies on cross-site requests; APIs that use bearer tokens in headers (rather than cookies) are largely immune since the token isn’t sent automatically. The key distinction to convey: XSS is about untrusted content executing in the browser (defended by output encoding, input validation, and CSP), while CSRF is about the browser being tricked into sending authenticated requests (defended by anti-forgery tokens and SameSite cookies). Both are OWASP-class risks that enterprise apps must address deliberately.

Principal Engineer Question

How do you make security a systemic property across many teams rather than a manual afterthought?

I make the secure path the default and easy path, and enforce it through automation and shared infrastructure rather than relying on each team and each code review to get security right. Concretely: I provide reusable, hardened building blocks - shared libraries and templates that bake in authentication, authorization patterns, input validation, secure error handling, security headers, TLS, and secret access via the vault - so teams get secure defaults by consuming them rather than reimplementing (and mis-implementing) security. I bake security into the delivery pipeline (shift left): SAST for insecure code, dependency/SCA scanning for vulnerable packages, secret scanning to block committed credentials, container and IaC scanning, all running automatically on every pull request and gating merges, so vulnerabilities are caught early and cheaply rather than in a late manual review. I enforce non-negotiable guardrails through policy (allowed configurations, mandatory HTTPS, no public secrets, required auth) at the platform level, so non-compliant setups are blocked regardless of what a team writes. I establish secure defaults in the framework configuration (HTTPS redirection, HSTS, secure cookies, restrictive CORS) so the starting point is safe. I invest in developer education and a security-champions model - embedding security awareness in each team - and I use threat modeling for significant designs and regular security reviews for governance. And I make security observable: centralized security logging, monitoring, and alerting so issues are detected in production. The principle, echoing OWASP and DevSecOps, is that security must be built into the architecture, tooling, and culture through reusable frameworks, automated checks, secure defaults, and shared ownership - so it scales across many teams and is applied consistently and continuously - rather than being a manual gate someone applies (or forgets) at the end. That’s what turns security from an afterthought that depends on individual diligence into a systemic property of how the organization builds software, which also balances security with developer productivity because the secure way is also the fast, default way.

9.6 Production Scenario

A financial API’s security review finds excessive API permissions, missing input validation, and insufficient audit logging. The team applies least-privilege access, centralizes input validation at the boundary, adds security headers and rate limiting, moves secrets to a vault, and implements comprehensive security logging and monitoring - then encodes these as shared libraries and pipeline scans so every team inherits the hardened defaults and the gaps cannot silently return.

Chapter Revision Notes

  • Treat all external input as untrusted; validate at the boundary.
  • Prevent SQL injection with parameterized queries / an ORM - never concatenate input.
  • Defend XSS with output encoding and CSP; CSRF with anti-forgery tokens and SameSite cookies.
  • Enforce HTTPS/TLS, security headers, restricted CORS, and rate limiting.
  • Log and monitor security events; make security systemic via shared libraries and pipeline scans.