.NET ProgrammingUnit 1014 min read

Deployment & Security in .NET: IIS, Containers, HTTPS, OWASP, and Encryption

Unit 10 of .NET Programming covers deploying ASP.NET Core apps (IIS, Docker, Azure), securing web apps (HTTPS, authentication, OWASP Top 10), and protecting data (encryption, hashing). Learn real-world configurations, security threats, and best practices with code examples and visual traces.

TAKEAWAYS:

  • Deploy ASP.NET Core apps via IIS, Docker containers, or cloud platforms (Azure/AWS) using web.config or Dockerfile.
  • Secure web apps with HTTPS (SSL/TLS), authentication (JWT/OAuth), and OWASP Top 10 mitigations (e.g., SQL injection, XSS).
  • Encrypt data using AES (symmetric) or RSA (asymmetric) in C# with System.Security.Cryptography.
  • Compare deployment methods (IIS vs. Docker vs. Azure) using a feature matrix (scalability, cost, ease of use).
  • Trace security attacks (e.g., CSRF, session hijacking) with Mermaid diagrams showing exploit flows and fixes.
  • Apply security in real apps: Use HTTPS in eSewa (payment security), JWT in Daraz (user auth), and AES in Ncell (data encryption).

1. Deployment Methods for ASP.NET Core Apps

Deploying a .NET app makes it accessible to users. Three common methods are IIS (Windows Server), Docker containers, and cloud platforms (Azure/AWS). Each has trade-offs in cost, scalability, and maintenance.

1.1 IIS (Internet Information Services) Deployment

IIS is Microsoft’s web server for Windows. To deploy an ASP.NET Core app:

  1. Publish the app to a folder using dotnet publish.
  2. Configure web.config for IIS hosting.
  3. Set up a binding (HTTP/HTTPS) in IIS Manager.
flowchart TD
    A["1. Publish App"] --> B["dotnet publish -o \\\\server\\folder"]
    B --> C["2. Configure web.config"]
    C --> D["3. Add Site in IIS Manager"]
    D --> E["4. Bind to Port 80/443"]
    E --> F["App Live at http://yourdomain.com"]

Worked Example: Deploying a Simple API to IIS

  1. Publish the app:
    dotnet publish -c Release -o C:\inetpub\wwwroot\MyApi
    
  2. Edit web.config (auto-generated) to include:
    <aspNetCore processPath="dotnet" arguments=".\MyApi.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" />
    
  3. In IIS Manager, add a new site pointing to C:\inetpub\wwwroot\MyApi.

Real-World Use:

  • eSewa uses IIS for its backend services in Nepal to ensure compatibility with Windows-based payment gateways.
  • NTC’s online services (e.g., bill payments) rely on IIS for secure government-grade deployments.

2. Docker Container Deployment

Docker containers package apps with dependencies, ensuring consistency across environments.

2.1 Dockerfile for ASP.NET Core

A Dockerfile defines the container’s environment:

# Use official .NET SDK image
FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
WORKDIR /src
COPY . .
RUN dotnet publish -c Release -o /app

# Runtime image
FROM mcr.microsoft.com/dotnet/aspnet:6.0
WORKDIR /app
COPY --from=build /app .
ENTRYPOINT ["dotnet", "MyApi.dll"]

Key Commands:

  • FROM: Base image (e.g., dotnet/aspnet:6.0).
  • COPY: Copies app files into the container.
  • ENTRYPOINT: Command to run the app.

Worked Example: Running the API in Docker

  1. Build the image:
    docker build -t myapi .
    
  2. Run the container:
    docker run -p 8080:80 -d myapi
    
    • -p 8080:80: Maps host port 8080 to container port 80.
    • -d: Runs in detached mode.

Visual: Docker Container Lifecycle

sequenceDiagram
    participant User
    participant Docker
    participant Container
    User->>Docker: docker build -t myapi .
    Docker->>Container: Creates image layer by layer
    User->>Docker: docker run -p 8080:80 myapi
    Docker->>Container: Starts container
    Container->>User: Exposes port 80

Real-World Use:

  • Pathao’s backend services use Docker to scale microservices across global servers without environment mismatches.
  • Khalti’s payment API containers ensure identical behavior in staging and production.

3. Cloud Deployment (Azure App Service)

Azure App Service simplifies cloud hosting with auto-scaling and managed services.

3.1 Deploying to Azure

  1. Create an App Service:
    • Go to Azure Portal.
    • Navigate to App Services → Add.
    • Choose Windows Container or ASP.NET Core.
  2. Publish:
    • Use az webapp up (CLI) or GitHub Actions.
    • Example CLI command:
      az webapp up --name MyApi --resource-group MyGroup --runtime "DOTNETCORE:6.0"
      

Comparison Table: Deployment Methods

Feature IIS Docker Azure App Service
OS Dependency Windows-only Cross-platform Cross-platform
Scalability Manual (vertical scaling) Easy (horizontal scaling) Auto-scaling
Cost High (server licensing) Medium (hosting fees) Pay-as-you-go
Ease of Use Moderate (IIS config) High (containerized) Very High (managed)
Use Case Enterprise Windows apps Microservices, CI/CD Startups, global apps

4. Security in .NET Applications

Security is critical to protect data and users. Key threats include SQL injection, XSS, CSRF, and session hijacking.

4.1 HTTPS and SSL/TLS

HTTPS encrypts data in transit using SSL/TLS certificates.

  • How it works:
    1. Client requests https://example.com.
    2. Server sends its certificate (signed by a CA like Let’s Encrypt).
    3. Client verifies the certificate and establishes an encrypted session.

Worked Example: Enabling HTTPS in ASP.NET Core

  1. Add Microsoft.AspNetCore.Mvc.Core and Microsoft.AspNetCore.Diagnostics.Entity.
  2. Configure in Program.cs:
    builder.Services.AddHttpsRedirection(options =>
    {
        options.RedirectStatusCode = StatusCodes.Status307TemporaryRedirect;
        options.HttpsPort = 443;
    });
    
  3. Use Let’s Encrypt for free certificates:
    dotnet tool install --global dotnet-certificates
    dotnet-certificates new mycert.pfx
    

Visual: HTTPS Handshake

sequenceDiagram
    participant Client
    participant Server
    Client->>Server: Request https://example.com
    Server->>Client: Send Certificate (CA-signed)
    Client->>Client: Verify Certificate
    Client->>Server: Symmetric Key Exchange (RSA)
    Client->>Server: Encrypted Data
    Server->>Client: Encrypted Response

Real-World Use:

  • eSewa uses HTTPS to encrypt payment transactions between users and banks.
  • Ncell’s myNcell app enforces HTTPS for all API calls to prevent MITM attacks.

4.2 Authentication and Authorization

Common methods:

  • JWT (JSON Web Tokens): Stateless auth for APIs.
  • OAuth 2.0: Delegated auth (e.g., "Login with Google").
  • Windows Authentication: For intranet apps.

Worked Example: JWT Authentication

  1. Install Microsoft.AspNetCore.Authentication.JwtBearer.
  2. Configure in Program.cs:
    builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer(options =>
        {
            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = true,
                ValidateAudience = true,
                ValidateLifetime = true,
                ValidIssuer = "https://yourdomain.com",
                ValidAudience = "https://yourdomain.com",
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("your-secret-key"))
            };
        });
    
  3. Generate a token in the login endpoint:
    var token = new JwtSecurityToken(
        issuer: "https://yourdomain.com",
        audience: "https://yourdomain.com",
        claims: new[] { new Claim(ClaimTypes.Name, userName) },
        expires: DateTime.UtcNow.AddHours(1),
        signingCredentials: new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes("your-secret-key")), SecurityAlgorithms.HmacSha256)
    );
    return new { token = new JwtSecurityTokenHandler().WriteToken(token) };
    

Visual: JWT Flow

sequenceDiagram
    participant User
    participant Client
    participant Server
    User->>Client: Login (username/password)
    Client->>Server: Send credentials
    Server->>Server: Validate user
    Server->>Client: Return JWT
    Client->>Server: Include JWT in API requests
    Server->>Server: Verify JWT
    Server->>Client: Authorized response

Real-World Use:

  • Daraz uses JWT for user sessions across its web and mobile apps.
  • Khalti implements OAuth 2.0 for third-party app integrations (e.g., e-commerce sites).

4.3 OWASP Top 10 Threats and Mitigations

Threat Description Mitigation in .NET
Injection SQL, OS commands via user input Use Parameterized Queries (SqlParameter).
Broken Auth Weak passwords, session hijacking Enforce JWT/OAuth, use AntiForgeryToken.
Sensitive Data Unencrypted PII (e.g., passwords) Use AES encryption (Aes.Create()).
XML External Entities (XXE) File read via malicious XML Disable XXE in XmlReaderSettings.
Broken Access Control Unauthorized API access Use [Authorize] attributes.
Security Misconfig Default credentials, open ports Scan with OWASP ZAP, harden web.config.

Worked Example: SQL Injection Prevention ❌ Vulnerable Code:

string query = $"SELECT * FROM Users WHERE Username = '{userInput}'";

✅ Fixed Code:

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

5. Data Encryption in .NET

Protect sensitive data (passwords, API keys) with symmetric (AES) or asymmetric (RSA) encryption.

5.1 AES Encryption (Symmetric)

using System.Security.Cryptography;
using System.Text;

// Encrypt
public static string Encrypt(string plainText, string key)
{
    using (Aes aes = Aes.Create())
    {
        aes.Key = Encoding.UTF8.GetBytes(key);
        aes.IV = new byte[16]; // Use a fixed IV in production
        ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
        using (MemoryStream ms = new MemoryStream())
        {
            using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
            {
                using (StreamWriter sw = new StreamWriter(cs))
                    sw.Write(plainText);
            }
            return Convert.ToBase64String(ms.ToArray());
        }
    }
}

// Decrypt
public static string Decrypt(string cipherText, string key)
{
    using (Aes aes = Aes.Create())
    {
        aes.Key = Encoding.UTF8.GetBytes(key);
        aes.IV = new byte[16];
        ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);
        using (MemoryStream ms = new MemoryStream(Convert.FromBase64String(cipherText)))
        using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
        using (StreamReader sr = new StreamReader(cs))
            return sr.ReadToEnd();
    }
}

Visual: AES Encryption Process

flowchart TD
    A["Plaintext (e.g., 'password123')"] --> B["AES Key (256-bit)"]
    A --> C["IV (Initialization Vector)"]
    B & C --> D["Encryptor"]
    D --> E["Ciphertext (Base64)"]
    E --> F["Store/Transmit"]
    F --> G["Decryptor"]
    G --> H["Plaintext"]

Real-World Use:

  • Ncell encrypts customer data (e.g., SIM registration details) using AES before storage.
  • Nepal Rastra Bank uses AES to secure inter-bank transaction logs.

5.2 RSA Encryption (Asymmetric)

RSA is slower but useful for key exchange (e.g., HTTPS).

using System.Security.Cryptography;

// Generate Key Pair
public static (RSA, RSA) GenerateKeyPair()
{
    using (RSA rsa = RSA.Create(2048))
    {
        return (rsa, rsa); // Public and private keys
    }
}

// Encrypt with Public Key
public static byte[] EncryptRSA(RSA rsa, string plainText)
{
    return rsa.Encrypt(Encoding.UTF8.GetBytes(plainText), RSAEncryptionPadding.OaepSHA256);
}

// Decrypt with Private Key
public static string DecryptRSA(RSA rsa, byte[] cipherText)
{
    return Encoding.UTF8.GetString(rsa.Decrypt(cipherText, RSAEncryptionPadding.OaepSHA256));
}

Visual: RSA Key Exchange

sequenceDiagram
    participant Client
    participant Server
    Server->>Client: Send Public Key (RSA)
    Client->>Server: Encrypt Data with Public Key
    Server->>Server: Decrypt with Private Key

6. Secure Coding Practices

  1. Validate all inputs (use ModelState.IsValid in MVC).
  2. Use dependency injection for secure services (e.g., IUserService).
  3. Sanitize outputs (prevent XSS with HtmlEncoder).
  4. Log securely (avoid logging passwords; use ILogger).
  5. Regularly update dependencies (dotnet list package --outdated).

Worked Example: Input Validation

[HttpPost]
public IActionResult Login([FromBody] LoginModel model)
{
    if (!ModelState.IsValid)
        return BadRequest(ModelState);

    // Proceed with auth...
}

In the Real World

  1. eSewa:

    • HTTPS: Encrypts all transactions between users and banks.
    • JWT: Secures API calls for merchant integrations.
    • AES: Encrypts stored payment card details (PCI-DSS compliant).
  2. Daraz:

    • OWASP Mitigations: Uses parameterized queries to block SQL injection in product searches.
    • Docker: Containers ensure consistent performance during Black Friday sales spikes.
    • Azure App Service: Auto-scales during traffic surges (e.g., Dashain sales).
  3. Ncell:

    • RSA: Secures SIM registration data during OTP verification.
    • IIS: Hosts internal tools for network monitoring (Windows-only legacy systems).
    • Session Hijacking Protection: Uses SameSite cookies and Secure flags.
  4. Nepal Stock Exchange (NEPSE):

    • HTTPS: Mandatory for all trading API endpoints.
    • JWT: Authenticates brokerage firms accessing market data.

Exam Tip

  1. Deployment Questions:

    • Expect short-answer questions on web.config vs. Dockerfile vs. Azure CLI commands.
    • Long-answer: Compare IIS, Docker, and Azure for a given scenario (e.g., "Deploy a high-traffic e-commerce API").
  2. Security Questions:

    • Define: HTTPS handshake, JWT, SQL injection, OWASP Top 10.
    • Code Fixes: Given vulnerable code, write the secure version (e.g., fix SQLi or XSS).
    • Diagrams: Draw the flow of a CSRF attack and its mitigation (e.g., AntiForgeryToken).
  3. Encryption Questions:

    • Explain: Symmetric vs. asymmetric encryption (AES vs. RSA).
    • Code: Write a method to encrypt/decrypt a string using AES (include key/IV handling).
    • Real-World: "How would you secure a bank’s loan application form?" (Answer: HTTPS + JWT + input validation).
  4. Common Pitfalls:

    • Forgetting to bind HTTPS in IIS (only HTTP works by default).
    • Using plain SQL strings instead of parameters.
    • Hardcoding secrets in Program.cs (use appsettings.json with user secrets).

Pro Tip: For practicals, always:

  • Use dotnet publish before deploying to IIS.
  • Test HTTPS locally with dotnet dev-certs:
    dotnet dev-certs https --trust
    

Based on the TU BITM syllabus for .NET Programming (IT275), unit 10.

Discussion

Loading…