.NET Coding Tips

SQL Injection Attacks

To prevent SQL Injection attacks, I use parameterized queries or stored procedures instead of concatenating SQL strings. In .NET, this can be achieved using SqlCommand with parameters. For example:


using (SqlCommand cmd = new SqlCommand("SELECT * FROM Users WHERE Username = @username", connection))
{
cmd.Parameters.AddWithValue("@username", username);
// Execute command
}

Cross-Site Scripting (XSS)

To prevent XSS, you need to ensure that any user input rendered in the browser is properly encoded by using .NET methods specifically designed for this purpose, such as HtmlEncode or the AntiXssEncoder class.


string safeOutput = HttpUtility.HtmlEncode(userInput);


You can also use Content-Security-Policy headers or within meta tags to specify the allowed origin of the content. The below policy only allows content from the same domain.

Content-Security-Policy: default-src 'self';

Implementing Authentication and Authorization

ASP.NET Identity or OAuth providers like Azure AD or Auth0 will help handle authentication securely. For authorization, you can implement role-based access control (RBAC) using the [Authorize] attribute in ASP.NET Core. This restricts access to certain actions or controllers based on user roles. For example:


[Authorize(Roles = "Admin")]
public IActionResult AdminOnly()
{
    return View();
}

@page "/"
@attribute [Authorize(Policy = "Over21")]