Secure Coding Practices in .NET Core Web API

Secure Coding Practices in .NET Core Web API

1. Prevent SQL Injection

Always use parameterized queries with EF Core or Dapper.

// EF Core

var user = await _context.Users.FirstOrDefaultAsync(u => u.Username == username);

 

// Dapper

var sql = "SELECT * FROM Users WHERE Username = @Username";

var user = connection.QueryFirstOrDefault<User>(sql, new { Username = username });

 

2. Prevent CSRF (When using cookies)

Apply the [ValidateAntiForgeryToken] attribute for form submissions.

[ValidateAntiForgeryToken]

[HttpPost]

public IActionResult SubmitForm([FromBody] FormModel model)

{

    // Handle securely

}

For JWT-based APIs, CSRF is less of a concern due to lack of cookie-based state.

 

3. Secure Authentication and Authorization

Use JWT or OAuth2 for token-based authentication. Secure sensitive endpoints:

[Authorize(Roles = "Admin")]

[HttpGet("admin/data")]

public IActionResult GetAdminData()

{

    return Ok("Admin access granted.");

}

Enforce role-based access control in your policies and services.

 

4. Secure Error Handling

Never return raw exception messages to the client. Log them internally and respond generically.

try

{

    // risky logic

}

catch (Exception ex)

{

    _logger.LogError(ex, "Unexpected error");

    return StatusCode(500, "An unexpected error occurred.");

}

Use global exception middleware for centralized error handling.

 

5. Enforce HTTPS

Redirect all HTTP traffic to HTTPS in production.

app.UseHttpsRedirection();

 

6. Add Security Headers

Protect your API with appropriate HTTP headers:

app.Use(async (context, next) =>

{

    context.Response.Headers.Add("X-Frame-Options", "DENY");

    context.Response.Headers.Add("X-Content-Type-Options", "nosniff");

    context.Response.Headers.Add("Content-Security-Policy", "default-src 'self'");

    await next();

});

 

7. Token Expiry and Refresh Support

  • Use short-lived JWT access tokens
  • Provide a refresh-token endpoint
  • Issue new tokens securely without re-authenticating

 

Summary

.NET Core Web API (Backend)

  • Use parameterized queries
  • Validate and authorize all requests
  • Handle errors securely
  • Apply HTTPS and security headers
  • Issue and manage tokens correctly

 


Comments

Popular posts from this blog

Factory Method Design Pattern in .NET — Real-Time Finance Example

Logging in .NET Core: Built-in Logging vs Serilog with Full Implementation Guide

Implementing Single Sign-On (SSO) in .NET Core and Angular