Building a Secure Web Application: Best Practices (ASP.NET)

  • Reading time:8 mins read

Creating a secure web application requires meticulous planning and attention to detail, from conceptualization to hosting and maintenance. According to a recent post by Sennaike David, at least 90% of financial institutions in Nigeria have their sensitive information, such as data, server access, usernames, passwords, API keys, and confidential customer data, exposed and traded on the dark web. Given the rising sophistication of cyber threats, prioritizing security is essential for any software development endeavor. Below are key practices to ensure the security and integrity of your web application:

Validate User Input

Validating user input is a fundamental step in safeguarding web applications against security vulnerabilities. By scrutinizing input data, you can detect and prevent the entry of malicious or malformed information that could lead to attacks like cross-site scripting (XSS).

Implement Server-side Validation: While client-side validation provides immediate feedback to users, it should not be solely relied upon. Always perform server-side validation to ensure input is validated on the server, even if client-side validation fails or is bypassed. This can be achieved in ASP.NET using Data Annotation or/and writing validation logic in your controller.

Length and Format Checks: Validate input fields’ length and format, such as email addresses and passwords, to enforce complexity requirements.

Whitelist Validation: Utilize whitelist validation to allow only specified characters or patterns for input fields, rejecting any input that doesn’t match expected patterns. Regular expressions can be used to validate email addresses or phone numbers.

Context-specific Validation: Tailor validation based on the type of input. For example, validate file uploads for allowed file types and sizes or validate URLs and redirect parameters to prevent open redirects or phishing attacks.

using System;
using System.ComponentModel.DataAnnotations;

namespace TechWithYomi.Models
    public class User
        public int UserId { get; set; }

        [Required(ErrorMessage = "First Name is required")]
        [StringLength(50, MinimumLength = 2, ErrorMessage = "First Name must be between 2 and 50 characters")]
        public string FirstName { get; set; }

        [Required(ErrorMessage = "Last Name is required")]
        [StringLength(50, MinimumLength = 2, ErrorMessage = "Last Name must be between 2 and 50 characters")]
        public string LastName { get; set; }

        [RegularExpression("^[A-Za-z0-9]+$", ErrorMessage = "Only alphanumeric character is allowed for Username")]
        public string Username { get; set; }

        [Required(ErrorMessage = "Email is required")]
        [EmailAddress(ErrorMessage = "Invalid Email Address")]
        public string Email { get; set; }

        [Required(ErrorMessage = "Birth Date is required")]
        public DateTime BirthDate { get; set; }

        [Range(18, 100, ErrorMessage = "Age must be between 18 and 100")]
        public int Age { get; set; }

Sanitize User Input

Alongside validation, sanitizing user input is crucial to remove or encode potentially dangerous characters, preventing injection attacks and Cross-Site Scripting (XSS) vulnerabilities. Employ appropriate sanitization techniques based on the input’s intended use.

HTML Encoding: When displaying user input within HTML content, apply HTML encoding to escape special characters like <, >, ", ', and &, preventing it from being interpreted as HTML or JavaScript code.

    string encodedInput = System.Web.HttpUtility.HtmlEncode(userInput);

URL Encoding: For input used in constructing URLs or query parameters, use URL encoding to encode special characters like spaces, question marks, and ampersands to ensure proper formatting and avoid unintended behavior or security risks.

    string encodedUrl = System.Web.HttpUtility.UrlEncode(inputUrl);

Parameterized Queries/Prepared Statements: When dealing with databases, use parameterized queries or prepared statements instead of directly concatenating user input into SQL statements. This prevents SQL injection attacks.

string sqlQuery = "SELECT * FROM Users WHERE Username = @username";          
using (SqlCommand command = new SqlCommand(sqlQuery, connection))
	command.Parameters.AddWithValue("@username", username);

File Upload Validation: When accepting file uploads from users, validate and sanitize file names and content, ensuring they are free from malicious characters. Additionally, restrict accepted file types, sizes, and extensions, and scan uploaded files for malware.

Access Control and Least Privilege

Follow the principle of least privilege, granting users only the necessary access to perform their tasks. Implement robust access control mechanisms to ensure that users and processes have appropriate permissions and access only what they need.

Secure Data at Rest

Choose a Strong Encryption Algorithm: Select a robust encryption algorithm that meets your security requirements, such as AES or RSA, to encrypt sensitive data like passwords and card details stored in the database.

Securely Store Encryption Keys: Utilize a secure key management mechanism like Azure Key Vault or an HSM to store and manage encryption keys, restricting access to authorized personnel only.

Enable Transparent Data Encryption (TDE): For supported database management systems, consider using TDE, which automatically encrypts the entire database file, including data files, log files, and backups, without altering the application code.

Configure Secure Database Connections: Ensure that the connection string uses a secure protocol like SSL/TLS to establish an encrypted channel between the application and the database server, protecting data during transit.

Data Integrity Monitoring

Use checksums to monitor data integrity regularly, checking for changes in vulnerable data and generating security alerts. Focus on monitoring the most sensitive data, such as user credentials and encryption key stores.

Authentication and Authorization

Implement secure session management techniques, including the use of random session tokens, session expiration enforcement, and avoiding session fixation vulnerabilities, to protect user sessions from unauthorized access and session hijacking.

Secure Configuration and Error Handling

Configure your web application securely, minimizing default settings and disabling unnecessary services. Promptly apply security patches, follow secure configuration guidelines for servers and databases, and implement proper error handling to prevent exposing sensitive information in error messages.

Regular Updates

Regularly update software, libraries, and the operating system to patch known vulnerabilities and enhance overall security.


Log and handle validation errors and exceptions appropriately, providing clear error messages to users while avoiding disclosure of sensitive information exploitable by attackers.

This Post Has 4 Comments

  1. Bosun

    Wow! So insightful

  2. Emmanuel

    Very insightful.

Leave a Reply