6 security best practices for ASP.NET Core

Today’s web applications are vulnerable to a variety of security threats. Hence, you should have your strategies in place to safeguard your data and protect your application against attacks. Securing your application requires a proactive approach combined with implementation of the recommended best practices as discussed in this article.

This article examines six strategies you can adopt to secure your web applications, taking advantage of protections available in ASP.NET Core. To use the illustrative code examples provided in this article, you should have Visual Studio 2022 installed in your system. If you don’t already have a copy, you can download Visual Studio 2022 here.

Create an ASP.NET Core Web App MVC project in Visual Studio 2022

To create an ASP.NET Core Web API project in Visual Studio 2022, follow the steps outlined below.

  1. Launch the Visual Studio 2022 IDE.
  2. Click on “Create new project.”
  3. In the “Create new project” window, select “ASP.NET Core Web App (Model-View-Controller)” from the list of templates displayed.
  4. Click Next.
  5. In the “Configure your new project” window, specify the name and location for the new project. Optionally check the “Place solution and project in the same directory” check box, depending on your preferences.
  6. Click Next.
  7. In the “Additional Information” window shown next, select “.NET 8.0 (Long Term Support)” as the framework version and uncheck the check box that says “Use controllers,” as we’ll be using minimal APIs in this project.
  8. Elsewhere in the “Additional Information” window, leave the “Authentication Type” set to “None” (the default) and make sure the check boxes “Enable Open API Support,” “Configure for HTTPS,” “Do not use top-level statements” and “Enable Docker” remain unchecked. We won’t be using any of those features here.
  9. Click Create.

We’ll use this ASP.NET Core Web App MVC project to illustrate the use of ASP.NET Core’s built-in security features in the sections below.

Enforce HTTPS in ASP.NET Core

SSL, or Secure Sockets Layer, is a protocol that facilitates safe and secure communication between clients and servers over a network by enabling the communication to be encrypted. You can enforce the use of HTTPS to secure your application by redirecting HTTP requests to HTTPS.

The following code snippet shows how you can configure HTTPS security for your application in the Program.cs file.

builder.Services.AddHttpsRedirection(options =>
    options.RedirectStatusCode = StatusCodes.Status307TemporaryRedirect;
    options.HttpsPort = 443;

Use HTTP Strict Transport Security in ASP.NET Core

HTTP Strict Transport Security, or HSTS, prevents downgrade protocol attacks and cookie hijacking by ensuring that the web server communicates using an HTTPS connection and by blocking all insecure HTTP connections. Note that the ASP.NET Core runtime engine adds the HSTS middleware by default.

The following code snippet illustrates how we can take advantage of this middleware to impose this security restriction.

services.AddHsts(options =>
   options.IncludeSubDomains = true;
   options.MaxAge = TimeSpan.FromDays(7);

Prevent cross-site request forgery attacks in ASP.NET Core

Cross-site request forgery attacks (CSRF) trick a user into performing malicious activities while the user is logged into an application. These attacks are most commonly performed by tricking users with phishing emails to lure them to malicious websites, where they use an authenticated user’s privileges to steal funds from a victim’s bank account, for example, or make online purchases using the victim’s credit card.

You can protect users of your ASP.NET Core application from CSRF attacks by using anti-forgery tokens. When you include anti-forgery tokens in your application, two different values are sent to the server with each POST. One of the values is sent as a browser cookie, and one is submitted as form data. Unless the server receives both values, it will refuse to allow the request to proceed.

To use anti-forgery tokens in your ASP.NET Core application, include them in the Program.cs file as shown in the code snippet given below.

builder.Services.AddAntiforgery(options =>
    options.FormFieldName = "ThisIsAnAntiForgeryField";
    options.HeaderName = "ThisIsAnAntiForgeryHeader";
    options.Cookie.Name = "ThisIsAnAntiForgeryCookie";

Prevent cross-site scripting in ASP.NET Core

Cross-site scripting (XSS) refers to the act of injecting a malicious script using input or form fields of a web page in your application, with the intent of stealing sensitive data such as login credentials or cookies. When an attacker wants to launch an XSS attack, they often send a malicious link to a user and then attempt to entice the person to click on the link. You can thwart cross-site scripting using URL encoding, HTML encoding, and regular expressions to validate and sanitize inputs.

Prevent SQL injection in ASP.NET Core

SQL injection is a major security concern. SQL injection occurs when an attacker inserts malicious SQL commands within your dynamically created SQL queries. Such attacks are enabled by security vulnerabilities in database queries, leading to exposure of sensitive information. You can thwart SQL injection by using stored procedures and parameterized queries in lieu of dynamic SQL queries, and by validating user input to remove potentially malicious characters.

Create custom error pages in ASP.NET Core

If you don’t implement proper error handling code in your application, you might inadvertently expose sensitive information such as configuration data, table names, or even social security numbers. To avoid this, you can implement a custom error web page in your application so that whenever an error occurs, the custom page will display safe error messages instead of the potentially compromising error messages that your application might generate.

In addition to the custom error web page, you should create a custom exception filter by extending the ExceptionFilterAttribute class and overriding the OnException method. The code snippet below shows how to redirect the route to the custom error web page when an error occurs.

var result = new RedirectToRouteResult(
new RouteValueDictionary
    {"controller", "Error"}, {"action", "MyCustomError"}

Finally, write the following piece of code in the Program.cs file to register the exception handler with the request processing pipeline.

if (!app.Environment.IsDevelopment())

Securing applications involves everything from ensuring proper configurations to preventing sensitive data from being exposed. The six best practices outlined above are only a start. To avoid exposing sensitive data, you should use not only HTTPS but also encrypt the data at rest, and refrain from storing sensitive data in an unencrypted form in a database or anywhere in the application.

You should also routinely monitor the activity logs generated by your application. Examining the logs can give you insights into security, performance, and other issues in your application.

Copyright © 2024 IDG Communications, Inc.

Leave a Comment