LESSON 18 OF 18

18. Security Hardening, Performance, and Production Readiness

Harden an ASP.NET Core REST API for security, performance, testing, and reliable production operation.

50 dk 93

Introduction

An API that works in development is not automatically ready for production. A production API requires secure network communication, controlled secret management, safe data access, predictable latency, observability, and automated tests. In this final lesson, we will strengthen the REST API built throughout the course with practical security and performance techniques.

We will cover HTTPS enforcement, HSTS, CORS, secure configuration, SQL injection prevention, removing sensitive data from responses and logs, security headers, EF Core query optimization, indexes, prevention of N+1 queries, and integration testing. The goal is not to add one isolated security setting, but to establish a repeatable production-readiness process.

1. HTTPS, HSTS, and secure network communication

Credentials, access tokens, and business data must be transmitted over HTTPS. The UseHttpsRedirection middleware can redirect HTTP requests to HTTPS. In production, HSTS can tell browsers to use HTTPS for subsequent requests.

var builder = WebApplication.CreateBuilder(args); builder.Services.AddControllers(); builder.Services.AddHttpsRedirection(options => {    options.HttpsPort = 443; }); var app = builder.Build(); if (!app.Environment.IsDevelopment()) {    app.UseHsts(); } app.UseHttpsRedirection(); app.MapControllers(); app.Run();

If a reverse proxy or cloud load balancer terminates HTTPS, forwarded headers must be configured correctly. Otherwise, the application may interpret the request as HTTP, generate incorrect redirects, or read the client IP address incorrectly. Enable HSTS only after HTTPS is correctly configured and only in the production environment.

2. Configure CORS narrowly and explicitly

CORS is not a firewall. It controls how browsers evaluate requests from different origins. Therefore, using AllowAnyOrigin, AllowAnyMethod, and AllowAnyHeader as the default production configuration is usually inappropriate.

const string FrontendPolicy = "FrontendPolicy"; builder.Services.AddCors(options => {    options.AddPolicy(FrontendPolicy, policy =>    {        policy.WithOrigins("https://app.example.com")              .WithMethods("GET", "POST", "PUT", "DELETE")              .WithHeaders("Content-Type", "Authorization")              .AllowCredentials();    }); }); var app = builder.Build(); app.UseRouting(); app.UseCors(FrontendPolicy); app.UseAuthentication(); app.UseAuthorization(); app.MapControllers();

When cookie-based authentication is used, wildcard origins cannot be combined with AllowCredentials. Configure the origin list per environment and test details such as trailing slash differences. Remember that CORS affects browser behavior only. It does not block server-to-server requests or direct HTTP clients.

3. Secret and configuration management

Connection strings, JWT signing keys, third-party API keys, and passwords must not be stored in source code or committed to Git. During development, use .NET User Secrets. In production, use environment variables or a dedicated secret manager.

var connectionString = builder.Configuration.GetConnectionString("Default")    ?? throw new InvalidOperationException("Database connection is not configured."); var signingKey = builder.Configuration["Jwt:SigningKey"]    ?? throw new InvalidOperationException("JWT signing key is not configured.");

Apply the following rules to secret management:

  • Do not place secrets in repositories, Docker images, or log files.
  • Use different keys for production, staging, and test environments.
  • Rotate secrets regularly and define a recovery process.
  • Grant the application only the minimum permissions it needs.
  • Fail fast at startup when a critical setting is missing.

Do not combine configuration values blindly with user input. Values that affect SQL structure, such as connection targets, table names, or sort fields, must be restricted with an allow-list.

4. SQL injection and safe data access

SQL injection occurs when user input is interpreted as part of a SQL command. EF Core LINQ queries normally generate parameterized SQL. However, building dynamic SQL by concatenating strings is dangerous.

// Safe: LINQ generates parameters. var products = await db.Products    .Where(p => p.Name.Contains(searchTerm))    .Select(p => new ProductListItemDto(p.Id, p.Name, p.Price))    .ToListAsync(cancellationToken); // Safe: interpolation preserves parameterization. var result = await db.Products    .FromSqlInterpolated($"SELECT * FROM Products WHERE Name = {searchTerm}")    .ToListAsync(cancellationToken); // Dangerous: user input is inserted into SQL text. var sql = $"SELECT * FROM Products WHERE Name = '{searchTerm}'";

If a dynamic column or sort direction is required, do not insert the user value directly into SQL. Use an allow-list instead:

var sortColumn = sort?.ToLowerInvariant() switch {    "price" => "price",    "name" => "name",    _ => "name" }; query = sortColumn == "price"    ? query.OrderBy(p => p.Price)    : query.OrderBy(p => p.Name);

Also apply least privilege to the database account. An application account with administrator permissions increases the impact of a successful compromise.

5. Sensitive data and security headers

Returning entity objects directly can accidentally expose internal identifiers, audit fields, password hashes, or supplier costs. Response DTOs should contain only the fields that clients are allowed to see. Passwords must never be stored in plain text or returned in a response.

public sealed record UserResponseDto(    Guid Id,    string DisplayName,    string Email);

Mask access tokens, passwords, connection strings, payment data, and personal information in logs. Stack traces should be exposed only in development. Production errors should use the centralized ProblemDetails strategy established earlier in the course.

A small middleware can add basic security response headers:

app.Use(async (context, next) => {    context.Response.Headers["X-Content-Type-Options"] = "nosniff";    context.Response.Headers["X-Frame-Options"] = "DENY";    context.Response.Headers["Referrer-Policy"] = "no-referrer";    if (context.Request.Path.StartsWithSegments("/api"))    {        context.Response.Headers["Cache-Control"] = "no-store";    }    await next(); });

Choose headers according to the client and data classification. Adding no-store to every response may be unnecessary for a public catalog, but it can be appropriate for responses containing tokens or personal data.

6. Query performance with EF Core

AsNoTracking and projection

For read-only queries, AsNoTracking can remove the cost of change tracking. Projection selects only the required columns, reducing database, memory, and network costs.

var items = await db.Products    .AsNoTracking()    .Where(p => p.IsActive)    .OrderBy(p => p.Name)    .Select(p => new ProductListItemDto(        p.Id,        p.Name,        p.Price))    .ToListAsync(cancellationToken);

Entities that will be updated may require tracking. Therefore, do not add AsNoTracking mechanically to every query. Decide based on the purpose of each query.

Asynchronous queries and bounded results

Use asynchronous APIs such as ToListAsync, SingleOrDefaultAsync, and AnyAsync for database calls. Avoid loading unbounded tables into memory; use pagination instead. Also enforce a reasonable maximum page size rather than trusting the client’s value.

Indexes

Evaluate indexes for columns frequently used in filtering, joins, and ordering. For example, an index may help an endpoint that lists active products by category and name:

protected override void OnModelCreating(ModelBuilder modelBuilder) {    modelBuilder.Entity<Product>()        .HasIndex(p => new { p.CategoryId, p.IsActive, p.Name }); }

Adding an index to every column is not a solution. Indexes increase write and storage costs. Use real query plans and measurements close to production data before deciding.

Preventing N+1 queries

Loading a product list and then executing a separate category query for every product creates the N+1 problem. Lazy loading can introduce this issue without making it obvious. Prefer projection or carefully controlled eager loading:

var products = await db.Products    .AsNoTracking()    .Select(p => new ProductListItemDto(        p.Id,        p.Name,        p.Price,        p.Category.Name))    .ToListAsync(cancellationToken);

Inspect SQL logs, query counts, and query durations. Performance optimization should be based on measurements rather than assumptions.

7. Integration testing

Unit tests verify the behavior of one class. Integration tests verify the real HTTP pipeline, routing, authorization, serialization, and data access together. In ASP.NET Core, use WebApplicationFactory<Program> to create a test server and an HttpClient.

public class ProductsApiTests : IClassFixture<WebApplicationFactory<Program>> {    private readonly HttpClient client;    public ProductsApiTests(WebApplicationFactory<Program> factory)    {        client = factory.CreateClient(new WebApplicationFactoryClientOptions        {            BaseAddress = new Uri("https://localhost")        });    }    [Fact]    public async Task Get_products_returns_success_and_expected_content_type()    {        using var response = await client.GetAsync("/api/v1/products");        response.EnsureSuccessStatusCode();        Assert.Equal("application/json",            response.Content.Headers.ContentType?.MediaType);    } }

Cover important scenarios: unauthorized access, invalid validation, missing resources, pagination limits, CORS behavior, and ensuring that sensitive fields are absent from responses. Keep the test database separate from production data and make tests independent of execution order.

8. Production-readiness checklist

  • Are HTTPS and, where appropriate, HSTS enabled?
  • Have forwarded headers and proxy settings been verified?
  • Does CORS accept only the required origins, methods, and headers?
  • Are secrets absent from source code and logs?
  • Are SQL queries parameterized and dynamic fields restricted by an allow-list?
  • Are safe DTOs used instead of exposing entities?
  • Are sensitive responses protected by an appropriate cache policy?
  • Have projection, AsNoTracking, and pagination been considered for read queries?
  • Are indexes based on real query plans?
  • Have N+1 queries and unnecessary lazy loading been checked?
  • Do integration tests run in the CI pipeline?
  • Are health checks, logs, metrics, backups, and rollback plans ready?

Practice exercise

Select the product endpoint from the previous lessons and complete these tasks:

  1. Add HTTPS and HSTS configuration that is active only in production.
  2. Define an allow-list-based CORS policy for the frontend origin.
  3. Move a connection string to User Secrets or an environment variable.
  4. Rewrite the product listing query to use projection and AsNoTracking.
  5. Write a projection that returns product and category data in one query.
  6. Add two integration tests: one for successful listing and one for unauthorized access.
  7. Mark the production checklist in the project README.

Inspect SQL logs during the exercise and record the number of queries. Then measure the endpoint again without unnecessary Include, lazy loading, or entity serialization.

Conclusion

A production-ready REST API is more than a collection of correct endpoints. Secure transport, controlled origin policies, protected secrets, parameterized queries, limited response models, appropriate security headers, and measured database performance must be designed together.

In this lesson, we hardened the API with HTTPS and CORS, improved secret and sensitive-data handling, reduced SQL injection risk, optimized EF Core queries, and verified important behavior with integration tests. As a result, the API developed throughout the course is more readable, maintainable, secure, observable, and ready for production operations.

Sources