.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.configorDockerfile. - 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:
- Publish the app to a folder using
dotnet publish. - Configure
web.configfor IIS hosting. - 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
- Publish the app:
dotnet publish -c Release -o C:\inetpub\wwwroot\MyApi - Edit
web.config(auto-generated) to include:<aspNetCore processPath="dotnet" arguments=".\MyApi.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" /> - 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
- Build the image:
docker build -t myapi . - 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 80Real-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
- Create an App Service:
- Go to Azure Portal.
- Navigate to App Services → Add.
- Choose Windows Container or ASP.NET Core.
- Publish:
- Use
az webapp up(CLI) or GitHub Actions. - Example CLI command:
az webapp up --name MyApi --resource-group MyGroup --runtime "DOTNETCORE:6.0"
- Use
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:
- Client requests
https://example.com. - Server sends its certificate (signed by a CA like Let’s Encrypt).
- Client verifies the certificate and establishes an encrypted session.
- Client requests
Worked Example: Enabling HTTPS in ASP.NET Core
- Add
Microsoft.AspNetCore.Mvc.CoreandMicrosoft.AspNetCore.Diagnostics.Entity. - Configure in
Program.cs:builder.Services.AddHttpsRedirection(options => { options.RedirectStatusCode = StatusCodes.Status307TemporaryRedirect; options.HttpsPort = 443; }); - 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 ResponseReal-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
- Install
Microsoft.AspNetCore.Authentication.JwtBearer. - 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")) }; }); - 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 responseReal-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 Key6. Secure Coding Practices
- Validate all inputs (use
ModelState.IsValidin MVC). - Use dependency injection for secure services (e.g.,
IUserService). - Sanitize outputs (prevent XSS with
HtmlEncoder). - Log securely (avoid logging passwords; use
ILogger). - 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
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).
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).
Ncell:
- RSA: Secures SIM registration data during OTP verification.
- IIS: Hosts internal tools for network monitoring (Windows-only legacy systems).
- Session Hijacking Protection: Uses
SameSitecookies andSecureflags.
Nepal Stock Exchange (NEPSE):
- HTTPS: Mandatory for all trading API endpoints.
- JWT: Authenticates brokerage firms accessing market data.
Exam Tip
Deployment Questions:
- Expect short-answer questions on
web.configvs.Dockerfilevs. Azure CLI commands. - Long-answer: Compare IIS, Docker, and Azure for a given scenario (e.g., "Deploy a high-traffic e-commerce API").
- Expect short-answer questions on
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).
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).
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(useappsettings.jsonwith user secrets).
Pro Tip: For practicals, always:
- Use
dotnet publishbefore 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…