Security in ConnectSoft Microservice Template¶
Purpose & Overview¶
Security is a fundamental cross-cutting concern in the ConnectSoft Microservice Template, implemented through a defense-in-depth strategy that protects the microservice at multiple layers. The template incorporates security best practices, industry standards, and Azure-specific security features to ensure that microservices are secure by default, protecting against common vulnerabilities and threats.
Security in the template provides:
- Defense in Depth: Multiple layers of security controls
- Zero Trust Architecture: Verify and authenticate all requests
- Secure by Default: Security features enabled out of the box
- Input Validation: Comprehensive validation at all boundaries
- Data Protection: Encryption at rest and in transit
- Secret Management: Secure storage and retrieval of sensitive data
- Audit Logging: Complete audit trail for security events
- Compliance Ready: Support for regulatory requirements (GDPR, CCPA, SOC 2)
Security Philosophy
Security is not an afterthought—it's embedded in every layer of the microservice architecture. The template follows a security-first approach where security controls are enabled by default, validated at startup, and enforced throughout the application lifecycle. We assume that threats exist at every layer and implement appropriate controls to mitigate risks, following the principle of least privilege and defense in depth.
Architecture Overview¶
Security Layers¶
The template implements security at multiple layers:
Perimeter Security
├── HTTPS/TLS Enforcement
├── Rate Limiting
├── CORS Configuration
└── Firewall Rules
↓
Transport Security
├── TLS 1.2/1.3
├── Certificate Validation
└── HSTS (HTTP Strict Transport Security)
↓
Application Security
├── Authentication
├── Authorization
├── Input Validation
├── Output Encoding
└── Session Management
↓
Data Security
├── Encryption at Rest
├── Encryption in Transit
├── Secret Management
└── Data Redaction
↓
Infrastructure Security
├── Managed Identity
├── Network Isolation
├── Access Controls
└── Security Monitoring
Security Components¶
Security Features
├── Authentication & Authorization
│ ├── JWT/OAuth2/OIDC
│ ├── API Keys
│ └── Policy-Based Authorization
├── Transport Security
│ ├── HTTPS Redirection
│ ├── HSTS
│ └── TLS Configuration
├── Input Validation
│ ├── FluentValidation
│ ├── DataAnnotations
│ └── Model Binding Validation
├── Rate Limiting
│ ├── Global Rate Limiter
│ ├── Per-IP Limits
│ └── Endpoint-Specific Limits
├── CORS Configuration
│ ├── Origin Whitelisting
│ ├── Method Restrictions
│ └── Credential Handling
├── Secrets Management
│ ├── Azure Key Vault
│ ├── User Secrets (Local)
│ └── Environment Variables
├── Data Redaction
│ ├── Automatic PII Redaction
│ ├── Secret Redaction
│ └── Custom Redactors
└── Security Headers
├── HSTS
├── X-Content-Type-Options
└── X-Frame-Options
Transport Security¶
HTTPS Enforcement¶
Purpose: Ensure all communications are encrypted using TLS.
Configuration:
Configuration Options:
Characteristics:
- Redirect Status Code: 308 (Permanent Redirect) preserves request method
- HTTPS Port: Port for HTTPS redirection
- Automatic: Redirects HTTP requests to HTTPS
Middleware Order:
application.UseForwardedHeaders();
application.UseMicroserviceSerilogRequestLogging();
application.UseDeveloperExceptionPage(); // or UseHsts()
application.UseConversationId();
application.UseMicroserviceHttpLogging(configuration);
application.UseLatencyTelemetryCollection();
application.UseDefaultFiles();
application.UseStaticFiles();
application.UseWebSockets();
application.UseWebApiCommunication();
application.UseCors();
application.UseHttpsRedirection(); // ← HTTPS enforcement
application.UseRouting();
HSTS (HTTP Strict Transport Security)¶
Purpose: Force browsers to use HTTPS for all future requests.
Configuration:
HSTS Headers:
Strict-Transport-Security: max-age=31536000; includeSubDomains; preloadmax-age: Duration in seconds (1 year = 31536000)includeSubDomains: Applies to all subdomainspreload: Enables HSTS preload list
Benefits:
- Prevents man-in-the-middle attacks
- Forces HTTPS for all future requests
- Protects against protocol downgrade attacks
Configuration Options:
services.Configure<HstsOptions>(options =>
{
options.Preload = true;
options.IncludeSubDomains = true;
options.MaxAge = TimeSpan.FromDays(365);
options.ExcludedHosts.Add("localhost"); // Exclude localhost
});
TLS Configuration¶
Kestrel TLS Configuration:
{
"Kestrel": {
"Endpoints": {
"Https": {
"Url": "https://localhost:5001",
"Certificate": {
"Path": "/https/aspnetapp.pfx",
"Password": "Password123!"
}
}
}
}
}
Production TLS:
- Use certificates from Azure Key Vault or certificate store
- Enable TLS 1.2 minimum (TLS 1.3 preferred)
- Disable weak ciphers
- Use strong certificate validation
Authentication & Authorization¶
Authentication¶
Authentication verifies the identity of users and services making requests.
Supported Authentication Methods:
-
JWT (JSON Web Tokens)
- Bearer token authentication
- Token validation and expiration
- Claims-based identity
-
OAuth2/OIDC
- Authorization code flow
- Client credentials flow
- Resource owner password flow (not recommended)
-
API Keys
- Custom header authentication
- Query parameter authentication (not recommended)
-
Managed Identity (Azure)
- System-assigned managed identity
- User-assigned managed identity
- No credentials required
Authentication Middleware:
Middleware Order:
- Authentication must be after routing
- Authorization must be after authentication
Authorization¶
Authorization determines what authenticated users and services can do.
Authorization Policies:
services.AddAuthorizationBuilder()
.AddPolicy("RequireAdmin", policy =>
{
policy.RequireRole("Admin");
policy.RequireAuthenticatedUser();
})
.AddPolicy("RequireManager", policy =>
{
policy.RequireRole("Admin", "Manager");
policy.RequireAuthenticatedUser();
});
Policy-Based Authorization:
[Authorize(Policy = "RequireAdmin")]
public class AdminController : ControllerBase
{
// Only admins can access
}
[Authorize(Policy = "RequireManager")]
[HttpGet("reports")]
public IActionResult GetReports()
{
// Managers and admins can access
}
Role-Based Authorization:
[Authorize(Roles = "Admin,Manager")]
public class ReportsController : ControllerBase
{
// Admins and managers can access
}
Claims-Based Authorization:
services.AddAuthorizationBuilder()
.AddPolicy("CanEdit", policy =>
{
policy.RequireClaim("permission", "edit");
});
For detailed information on authentication and authorization, see:
- Authentication (when available)
- Authorization (when available)
Input Validation¶
Purpose¶
Input validation is the first line of defense against malicious input, ensuring that all data entering the system is well-formed, semantically valid, and safe.
Validation Layers:
API Layer (REST/gRPC)
├── Model Binding Validation (DataAnnotations)
└── FluentValidation (Request DTOs)
↓
Application Layer (Processors/Use Cases)
├── Input Validation (FluentValidation)
└── Pre-execution Checks
↓
Domain Layer (Aggregates/Entities)
├── Invariant Enforcement
└── Business Rule Validation
Validation Technologies¶
FluentValidation:
- Complex input validation
- DTOs and commands
- Rule chaining and conditional logic
- Async validation support
DataAnnotations:
- Simple structure validation
- Options and service models
- Attribute-based validation
- Built-in ASP.NET support
Example:
public class CreateUserRequest
{
[Required]
[EmailAddress]
[StringLength(100)]
public string Email { get; set; }
[Required]
[StringLength(50, MinimumLength = 8)]
[RegularExpression(@"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).+$")]
public string Password { get; set; }
}
// FluentValidation
public class CreateUserRequestValidator : AbstractValidator<CreateUserRequest>
{
public CreateUserRequestValidator()
{
RuleFor(x => x.Email)
.NotEmpty()
.EmailAddress()
.MaximumLength(100);
RuleFor(x => x.Password)
.NotEmpty()
.MinimumLength(8)
.Matches(@"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).+$")
.WithMessage("Password must contain uppercase, lowercase, and digit");
}
}
For detailed information on validation, see Validation.
Rate Limiting¶
Purpose¶
Rate limiting protects the microservice from abuse, ensures fair resource allocation, and maintains system stability under load.
Rate Limiting Features:
- Global Rate Limiter: Fixed window rate limiter for all requests
- Per-IP Partitioning: Rate limits per client IP address
- Configurable Limits: Permit limit and time window configuration
- 429 Status Code: Standard "Too Many Requests" response
- Endpoint Exemptions: Health checks and other endpoints can bypass limits
Configuration:
{
"RateLimiting": {
"EnableRateLimiting": true,
"GlobalLimiter": {
"Window": "00:01:00",
"PermitLimit": 100,
"AutoReplenishment": true,
"QueueLimit": 10
}
}
}
Implementation:
Bypassing Rate Limiting:
For detailed information on rate limiting, see Rate Limiting.
CORS Configuration¶
Purpose¶
CORS (Cross-Origin Resource Sharing) controls which origins can access the API, preventing unauthorized cross-origin requests.
CORS Policies:
services.AddCors(options =>
{
// Default policy
options.AddDefaultPolicy(policyBuilder =>
policyBuilder
.WithOrigins("http://localhost:62111", "https://localhost:7279")
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials());
// Named policy: AllowAny (for public APIs)
options.AddPolicy("AllowAny", policyBuilder =>
policyBuilder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
});
Security Best Practices:
-
Specify Explicit Origins (Production):
-
Restrict Methods:
-
Restrict Headers:
-
Use HTTPS Origins:
⚠️ Important: Never use AllowAnyOrigin() with AllowCredentials()—this is incompatible and will throw an exception.
For detailed information on CORS, see CORS.
Secrets Management¶
Purpose¶
Secrets management ensures that sensitive information (connection strings, API keys, passwords, tokens) is stored securely and never exposed in source control or logs.
Secrets Storage:
- Production: Azure Key Vault with Managed Identity
- Local Development: User Secrets (dotnet user-secrets)
- Containers: Environment variables or Kubernetes secrets
Key Vault References:
{
"ConnectionStrings": {
"DefaultConnection": "@Microsoft.KeyVault(SecretUri=https://vault.vault.azure.net/secrets/DbConnectionString)"
}
}
Best Practices:
-
Never Commit Secrets:
-
Use Managed Identity:
-
Rotate Secrets Regularly:
- Set expiration dates
- Rotate on schedule
- Test rotation process
For detailed information on secrets management, see Secrets Management.
Data Redaction¶
Purpose¶
Data redaction automatically masks or removes sensitive information from logs, telemetry, and responses to protect PII and credentials.
Redaction Features:
- Automatic Redaction: Classified data automatically redacted in logs
- Taxonomy-Based: Classification system for data types
- Custom Redactors: Email, phone, JWT, credit card, etc.
- Compliance Ready: GDPR, CCPA support
Classification:
public class UserDto
{
[EmailData]
public string Email { get; set; }
[PhoneData]
public string PhoneNumber { get; set; }
[SecretData]
public string ApiKey { get; set; }
}
Logging with Redaction:
Redaction Output:
For detailed information on data redaction, see Data Redaction.
Security Headers¶
Security Headers Configuration¶
HSTS (HTTP Strict Transport Security):
Custom Security Headers Middleware:
application.Use(async (context, next) =>
{
context.Response.Headers.Append("X-Content-Type-Options", "nosniff");
context.Response.Headers.Append("X-Frame-Options", "DENY");
context.Response.Headers.Append("X-XSS-Protection", "1; mode=block");
context.Response.Headers.Append("Referrer-Policy", "strict-origin-when-cross-origin");
context.Response.Headers.Append("Content-Security-Policy", "default-src 'self'");
await next();
});
Common Security Headers:
| Header | Purpose | Value |
|---|---|---|
Strict-Transport-Security |
Force HTTPS | max-age=31536000; includeSubDomains; preload |
X-Content-Type-Options |
Prevent MIME sniffing | nosniff |
X-Frame-Options |
Prevent clickjacking | DENY or SAMEORIGIN |
X-XSS-Protection |
XSS protection | 1; mode=block |
Referrer-Policy |
Control referrer information | strict-origin-when-cross-origin |
Content-Security-Policy |
Control resource loading | default-src 'self' |
Secure Coding Practices¶
Do's¶
-
Validate All Inputs
-
Use Parameterized Queries
-
Use HTTPS Everywhere
-
Implement Least Privilege
-
Log Security Events
-
Use Strong Cryptography
-
Sanitize Output
Don'ts¶
-
Don't Trust Client Input
-
Don't Log Secrets
-
Don't Use Weak Passwords
-
Don't Expose Sensitive Errors
-
Don't Use Hardcoded Secrets
-
Don't Skip Authentication
Security Monitoring¶
Audit Logging¶
Security Events to Log:
- Authentication attempts (success and failure)
- Authorization failures
- Rate limit violations
- Input validation failures
- Security policy violations
- Secret access (via Key Vault audit logs)
- Configuration changes
Logging Security Events:
logger.LogWarning("Failed authentication attempt for {Email} from {IpAddress}",
email, ipAddress);
logger.LogInformation("User {UserId} authenticated successfully", userId);
logger.LogWarning("Authorization denied for user {UserId} accessing {Resource}",
userId, resource);
logger.LogWarning("Rate limit exceeded for IP {IpAddress}", ipAddress);
Security Metrics¶
Key Security Metrics:
- Failed authentication attempts
- Authorization denials
- Rate limit violations
- Input validation failures
- Security exceptions
- Secret access patterns
Example Metrics:
private readonly Counter<long> _failedAuthAttempts =
Metrics.CreateCounter<long>("security_auth_failures_total", "Failed authentication attempts");
_failedAuthAttempts.Add(1, new KeyValuePair<string, object?>("email", email));
Alerting¶
Security Alerts:
- Multiple failed authentication attempts (potential brute force)
- Unusual access patterns
- Rate limit violations
- Security policy violations
- Configuration changes
Compliance¶
GDPR (General Data Protection Regulation)¶
Requirements:
- Data minimization
- Right to access
- Right to deletion
- Data portability
- Privacy by design
Implementation:
- Data redaction for PII
- Audit logging
- Data retention policies
- Consent management
CCPA (California Consumer Privacy Act)¶
Requirements:
- Right to know
- Right to delete
- Right to opt-out
- Non-discrimination
Implementation:
- Data classification and redaction
- Access logging
- Data deletion capabilities
SOC 2¶
Requirements:
- Access controls
- Encryption
- Monitoring and logging
- Change management
Implementation:
- Managed Identity for access
- Encryption at rest and in transit
- Comprehensive audit logging
- Configuration management
Testing Security¶
Security Testing¶
Unit Tests:
[TestMethod]
public void ValidateInput_WithMaliciousInput_ShouldReject()
{
// Arrange
var validator = new CreateUserRequestValidator();
var request = new CreateUserRequest
{
Email = "<script>alert('xss')</script>",
Password = "weak"
};
// Act
var result = validator.Validate(request);
// Assert
Assert.IsFalse(result.IsValid);
}
Integration Tests:
[TestMethod]
public async Task GetUser_WithoutAuthentication_ShouldReturn401()
{
// Arrange
var client = factory.CreateClient();
// Act
var response = await client.GetAsync("/api/users/123");
// Assert
Assert.AreEqual(HttpStatusCode.Unauthorized, response.StatusCode);
}
Penetration Testing:
- OWASP Top 10 vulnerabilities
- SQL injection testing
- XSS testing
- CSRF testing
- Authentication bypass testing
Troubleshooting¶
Issue: HTTPS Not Enforcing¶
Symptoms: HTTP requests not redirecting to HTTPS.
Solutions:
- Verify
UseHttpsRedirection()is in middleware pipeline - Check
HttpsPortconfiguration - Verify reverse proxy configuration (if behind proxy)
- Check forwarded headers configuration
Issue: CORS Errors¶
Symptoms: Browser console shows CORS errors.
Solutions:
- Verify CORS middleware is registered
- Check origin is in allowed list
- Verify credentials configuration
- Check middleware order
Issue: Rate Limiting Too Restrictive¶
Symptoms: Legitimate requests being rate limited.
Solutions:
- Increase
PermitLimitin configuration - Adjust
Windowtime period - Exempt specific endpoints
- Review IP-based partitioning
Issue: Secrets Not Loading¶
Symptoms: Key Vault references not resolving.
Solutions:
- Verify Managed Identity is assigned
- Check Key Vault access policy
- Verify secret URI format
- Check connection string configuration
Related Documentation¶
- Authentication: Authentication mechanisms and configuration
- Authorization: Authorization policies and patterns
- Validation: Input validation and sanitization
- Rate Limiting: Rate limiting configuration
- CORS: Cross-Origin Resource Sharing configuration
- Secrets Management: Secure secret storage and retrieval
- Data Redaction: Automatic PII and secret redaction
- Configuration: Secure configuration management
Summary¶
Security in the ConnectSoft Microservice Template provides:
- ✅ Defense in Depth: Multiple layers of security controls
- ✅ Transport Security: HTTPS enforcement and HSTS
- ✅ Authentication & Authorization: JWT, OAuth2, and policy-based authorization
- ✅ Input Validation: Comprehensive validation at all boundaries
- ✅ Rate Limiting: Protection against abuse and DDoS
- ✅ CORS Configuration: Controlled cross-origin access
- ✅ Secrets Management: Secure storage and retrieval
- ✅ Data Redaction: Automatic PII and secret protection
- ✅ Security Headers: Additional browser security controls
- ✅ Audit Logging: Complete security event tracking
- ✅ Compliance Ready: GDPR, CCPA, SOC 2 support
By following these security patterns, teams can:
- Protect Against Threats: Multiple layers of defense mitigate various attack vectors
- Ensure Compliance: Built-in support for regulatory requirements
- Maintain Trust: Security-first approach builds user and stakeholder confidence
- Reduce Risk: Comprehensive security controls minimize security vulnerabilities
- Enable Monitoring: Audit logging and metrics support security operations
Security is an ongoing process that requires constant vigilance, regular updates, and continuous improvement. The template provides a solid foundation, but teams must also implement security monitoring, conduct regular security assessments, and stay informed about emerging threats and best practices.