Blog
HADESS
Cyber Security Magic

Secure Coding in .NET: Input Validation, Auth, and CSRF Defense

Secure Coding in .NET: Input Validation, Auth, and CSRF Defense

Part of the Cybersecurity Skills Guide — This article is one deep-dive in our complete guide series.

By HADESS Team | February 28, 2026 | Updated: February 28, 2026 | 5 min read

.NET gives you a lot of security features out of the box. The problem is that most developers either misconfigure them or skip them entirely. Writing secure .NET code means understanding what the framework provides and where it falls short.

Input Validation

Never trust user input. That applies to query strings, form data, headers, cookies, and anything else that crosses a trust boundary.

Use data annotations on your models as a first layer:

csharp public class UserInput { [Required] [StringLength(100, MinimumLength = 1)] [RegularExpression(@"^[a-zA-Z0-9\s]+$")] public string Name { get; set; } } `

Data annotations catch obvious problems, but they are not sufficient on their own. Add FluentValidation for complex business rules. Always validate on the server side — client-side validation is a UX feature, not a security control.

For API endpoints, use [ApiController] attribute which automatically returns 400 for invalid model state. Without it, invalid input silently passes through to your controller logic.

Authentication Patterns

ASP.NET Core Identity handles password hashing, lockout policies, and two-factor auth. Configure it properly:

`csharp
services.Configure(options =>
{
options.Password.RequiredLength = 12;
options.Lockout.MaxFailedAccessAttempts = 5;
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(15);
});
`

For JWT-based APIs, validate the issuer, audience, and signing key. A common mistake is setting ValidateIssuer = false during development and shipping it to production. Use AddAuthentication().AddJwtBearer() with all validation parameters explicitly set.

CSRF Prevention

ASP.NET Core includes anti-forgery tokens. For Razor Pages, they are automatic. For MVC, you need [ValidateAntiForgeryToken] on POST actions and @Html.AntiForgeryToken() in forms. For SPAs calling APIs, use the cookie-to-header pattern with IAntiforgery.

The mistake people make: disabling anti-forgery for convenience during development and forgetting to re-enable it.

Output Encoding

Razor automatically HTML-encodes output with @. But if you use @Html.Raw(), you bypass encoding entirely. Audit every use of Html.Raw() in your codebase — each one is a potential XSS vector.

For JSON responses, use System.Text.Json which encodes HTML-sensitive characters by default. If you switch to custom encoders, you may reintroduce XSS in API responses consumed by browser clients.

Parameterized Queries

Entity Framework uses parameterized queries by default, but FromSqlRaw() with string concatenation reintroduces SQL injection. Always use FromSqlInterpolated() or pass parameters explicitly:

`csharp
// Safe
context.Users.FromSqlInterpolated($"SELECT * FROM Users WHERE Id = {userId}");

// Dangerous context.Users.FromSqlRaw("SELECT * FROM Users WHERE Id = " + userId);

Related Career Paths

Secure .NET development maps directly to Application Security Expert and Source Code Auditor roles. Code review and secure design are core competencies in both paths.

Next Steps

  • Evaluate your current .NET security knowledge with the skills assessment
  • Browse the skills library for related web security topics like OWASP Top 10 and secure architecture
  • Use the coaching tool to build a study plan around secure .NET development

Related Guides in This Series

Take the Next Step

Browse 80+ skills on HADESS. Go to the browse 80+ skills on hadess on HADESS.

See your certification roadmap. Check out the see your certification roadmap.

Get started freeCreate your HADESS account and access all career tools.

Frequently Asked Questions

How long does it take to learn this skill?

Most practitioners build working proficiency in 4-8 weeks of dedicated study with hands-on practice. Mastery takes longer and comes primarily through on-the-job experience.

Do I need certifications for this skill?

Certifications validate your knowledge to employers but are not strictly required. Hands-on experience and portfolio projects often carry more weight in technical interviews. Check the certification roadmap for relevant options.

What career paths use this skill?

Explore the career path explorer to see which roles require this skill and how it fits into different cybersecurity specializations.

HADESS Team consists of cybersecurity practitioners, hiring managers, and career strategists who have collectively spent 50+ years in the field.

Leave a Reply

Your email address will not be published. Required fields are marked *