| Integration Testing WebApplicationFactory :👈 | 👉:Kestrel Web Server Architecture: Connection Handling and Performance |
ASP.NET Core Secure API Design |
ASP.NET Core Secure API Design
1. What Is Secure API Design?
Secure API design means building APIs that allow only authorized users and applications to access the resources they are permitted to use.
Important security areas include:
- Authentication – Who are you?
- Authorization – What are you allowed to access?
- Input validation – Is the incoming data valid?
- Data protection – Is sensitive information protected?
- Rate limiting – Are clients sending too many requests?
- Logging and monitoring – Can suspicious activities be detected?
- Transport security – Is communication encrypted?
2. Secure API Architecture
A typical secure ASP.NET Core API architecture looks like this:
3. Authentication
Authentication verifies the identity of the client or user accessing the API.
Common Authentication Methods
| Method | Usage |
|---|---|
| JWT Bearer Token | Common for APIs and distributed applications. |
| OAuth 2.0 | Delegated authorization and access tokens. |
| OpenID Connect | User authentication built on OAuth 2.0. |
| API Key | Identifying application clients; not a replacement for user authentication. |
| Client Certificates | Strong service-to-service authentication using mutual TLS. |
JWT Authentication Flow
Configure JWT Authentication
Install the required package:
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
Program.cs:
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.Authority =
builder.Configuration["Authentication:Authority"];
options.Audience =
builder.Configuration["Authentication:Audience"];
options.RequireHttpsMetadata = true;
});
builder.Services.AddAuthorization();
var app = builder.Build();
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
This example assumes an external identity provider that exposes the required OpenID Connect metadata and signing keys. For production, configure issuer, audience, and token validation according to that provider.
4. Authorization: Role-Based and Policy-Based
Authentication confirms identity. Authorization decides what the authenticated identity can do.
Role-Based Authorization
[Authorize(Roles = "Admin")]
[HttpDelete("{id}")]
public IActionResult DeleteProduct(int id)
{
return Ok("Product deleted");
}
Only users with the Admin role can access this endpoint.
Policy-Based Authorization
builder.Services.AddAuthorization(options =>
{
options.AddPolicy("CanManageProducts", policy =>
{
policy.RequireClaim("permission", "products.manage");
});
});
[Authorize(Policy = "CanManageProducts")]
[HttpPost]
public IActionResult CreateProduct()
{
return Ok();
}
Policy-based authorization is useful when permissions are more detailed than simple user roles.
Resource-Based Authorization
Check whether the current user owns or has permission to access a particular resource. For example, a user should not access another customer's order simply by changing the order ID in the URL.
var order = await dbContext.Orders.FindAsync(id);
if (order == null)
return NotFound();
if (order.CustomerId != currentUserId)
return Forbid();
return Ok(order);
In production, use a resource-based authorization handler when this permission check needs to be shared across multiple endpoints.
5. Input Validation
Never trust incoming API data. Validate request fields before processing or storing them.
Using Data Annotations
using System.ComponentModel.DataAnnotations;
public class CreateUserRequest
{
[Required]
[StringLength(100, MinimumLength = 2)]
public string Name { get; set; } = string.Empty;
[Required]
[EmailAddress]
public string Email { get; set; } = string.Empty;
[Range(1, 120)]
public int Age { get; set; }
}
With [ApiController], ASP.NET Core automatically returns a validation response when model validation fails.
Best Practices
- Validate required fields and data types.
- Apply maximum length restrictions.
- Validate numeric ranges and business rules.
- Reject unexpected or malformed input.
- Use request DTOs instead of directly binding database entities.
- Never trust client-supplied user IDs or permission values.
6. Prevent SQL Injection
SQL Injection happens when untrusted input is incorrectly combined with SQL statements.
Unsafe SQL Example
// Avoid concatenating user input into SQL.
var sql = "SELECT * FROM Users WHERE Name = '" + userName + "'";
Safe SQL Example Using EF Core
var user = await dbContext.Users
.FirstOrDefaultAsync(u => u.Name == userName);
Safe SQL Example Using Dapper
var user = await connection.QueryFirstOrDefaultAsync<User>(
"SELECT * FROM Users WHERE Name = @Name",
new { Name = userName });
Always use parameterized queries. Avoid constructing SQL statements by concatenating untrusted input.
7. HTTPS and TLS Security
HTTPS encrypts communication between the client and API using TLS. It helps prevent attackers from reading or modifying data in transit.
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.UseHttpsRedirection();
app.MapControllers();
app.Run();
Best practices:
- Use HTTPS for all production API communication.
- Use valid certificates from trusted certificate authorities.
- Keep TLS configuration up to date.
- Do not transmit passwords or access tokens over plain HTTP.
- Configure HSTS for production HTTPS deployments where appropriate.
8. Rate Limiting and Throttling
Rate limiting controls how many requests a client can send within a specified period.
It helps protect APIs against:
- Excessive traffic.
- Brute-force login attempts.
- Resource exhaustion.
- Accidental client request loops.
Configure Rate Limiting
using System.Threading.RateLimiting;
builder.Services.AddRateLimiter(options =>
{
options.RejectionStatusCode = 429;
options.AddFixedWindowLimiter("api-policy", limiter =>
{
limiter.PermitLimit = 100;
limiter.Window = TimeSpan.FromMinutes(1);
limiter.QueueLimit = 0;
limiter.AutoReplenishment = true;
});
});
Apply the policy:
app.UseRateLimiter();
app.MapControllers()
.RequireRateLimiting("api-policy");
This example permits up to 100 requests per minute per limiter instance. For distributed APIs, consider gateway-level or distributed rate limiting when limits must be shared across multiple application instances.
9. CORS Security
Cross-Origin Resource Sharing (CORS) controls which browser origins can access an API.
Configure trusted origins instead of allowing every origin.
builder.Services.AddCors(options =>
{
options.AddPolicy("TrustedFrontend", policy =>
{
policy
.WithOrigins("https://example.com")
.AllowAnyHeader()
.AllowAnyMethod();
});
});
Apply the policy:
app.UseCors("TrustedFrontend");
Important:
- Avoid AllowAnyOrigin() for APIs that should be restricted.
- Do not combine wildcard origins with credentialed requests.
- CORS is a browser security mechanism, not an authentication mechanism.
- Non-browser clients can call APIs regardless of browser CORS restrictions.
10. Secure API Error Handling
Never expose internal exceptions, SQL queries, connection strings, stack traces, or secrets in production API responses.
Use ProblemDetails
builder.Services.AddProblemDetails();
var app = builder.Build();
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler();
}
app.MapControllers();
Example error response:
{
"type": "https://example.com/errors/validation",
"title": "Validation failed",
"status": 400,
"detail": "One or more validation errors occurred."
}
Return useful error information without revealing internal implementation details. Log detailed exceptions securely on the server.
11. Protect Sensitive Information
Never store secrets directly in source code.
Examples of sensitive information:
- Database passwords.
- JWT signing keys.
- API keys.
- Client secrets.
- Cloud access credentials.
Use appropriate secret-management solutions:
- Azure Key Vault.
- AWS Secrets Manager.
- Environment-based configuration.
- Managed Identity or workload identity where supported.
Do not log access tokens, passwords, secret keys, or sensitive personal information. Mask or remove sensitive values before logging.
12. API Versioning
API versioning helps introduce changes without unexpectedly breaking existing clients.
Common versioning approaches include:
- URL versioning: /api/v1/products
- Query string versioning: /api/products?api-version=1.0
- Header-based versioning.
Install the versioning packages:
dotnet add package Asp.Versioning.Mvc
dotnet add package Asp.Versioning.Mvc.ApiExplorer
Configure versioning:
builder.Services.AddApiVersioning(options =>
{
options.DefaultApiVersion =
new Asp.Versioning.ApiVersion(1, 0);
options.AssumeDefaultVersionWhenUnspecified = true;
options.ReportApiVersions = true;
});
Versioning is not itself a security control, but it supports safe API evolution and controlled retirement of old endpoints.
13. Prevent Mass Assignment
Mass assignment occurs when an API allows clients to update fields they should not control.
For example, a client should not be allowed to change its own Admin role or account approval status through a general profile update endpoint.
Use Separate Request DTOs
public class UpdateProfileRequest
{
public string DisplayName { get; set; } = string.Empty;
public string Email { get; set; } = string.Empty;
}
[HttpPut("profile")]
public async Task<IActionResult> UpdateProfile(
UpdateProfileRequest request)
{
var user = await dbContext.Users.FindAsync(currentUserId);
if (user == null)
return NotFound();
user.DisplayName = request.DisplayName;
user.Email = request.Email;
await dbContext.SaveChangesAsync();
return NoContent();
}
Explicitly map permitted fields instead of binding request data directly to database entities.
14. Secure File Uploads
File upload endpoints require additional security checks.
- Set maximum upload size.
- Allow only required file types.
- Validate file content, not just the supplied extension.
- Generate server-side file names.
- Store uploaded files outside the application execution directory.
- Prevent uploaded files from being executed.
- Use malware scanning where appropriate.
- Restrict access to uploaded files.
15. Logging, Monitoring and Auditing
Security logging helps detect suspicious behavior and investigate security incidents.
Important events to monitor:
- Repeated failed login attempts.
- Unauthorized access attempts.
- Unexpected privilege changes.
- Rate-limit violations.
- Unusual API request patterns.
- Unexpected administrative operations.
Use structured logging and centralized monitoring. Ensure logs do not contain passwords, tokens, or unnecessary sensitive information.
16. Important Security Headers
| Header | Purpose |
|---|---|
| Strict-Transport-Security | Instructs browsers to use HTTPS for the configured period. |
| X-Content-Type-Options | Prevents MIME-type sniffing. |
| Content-Security-Policy | Controls permitted content sources, mainly for browser-rendered content. |
| Referrer-Policy | Controls referrer information sent by browsers. |
| Cache-Control | Controls caching of sensitive responses. |
Configure headers according to the application's needs. Browser-oriented headers such as CSP are especially relevant when an API also serves HTML or browser content.
17. Recommended Middleware Order
A typical ASP.NET Core API pipeline might look like this:
var app = builder.Build();
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler();
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors("TrustedFrontend");
app.UseAuthentication();
app.UseRateLimiter();
app.UseAuthorization();
app.MapControllers();
app.Run();
Middleware ordering matters. For example, authentication must run before authorization. CORS should be applied at the appropriate point in the routing pipeline. Rate limiting should be configured and applied according to whether it uses endpoint metadata or global policies.
18. OWASP API Security Risks
The OWASP API Security Top 10 provides a useful checklist for API security.
| Risk | Meaning | Protection |
|---|---|---|
| Broken Object Level Authorization | Users access another user's resources. | Check ownership and resource permissions. |
| Broken Authentication | Weak identity verification. | Use secure identity providers and token validation. |
| Broken Object Property Level Authorization | Users access or modify restricted object properties. | Use DTOs and property-level authorization. |
| Unrestricted Resource Consumption | Excessive requests consume resources. | Apply rate limits, quotas and payload limits. |
| Broken Function Level Authorization | Users access administrative operations. | Enforce role and policy checks. |
| Unrestricted Access to Sensitive Business Flows | Automated abuse of business operations. | Apply business limits and abuse detection. |
| SSRF | Server is tricked into accessing unintended resources. | Validate outbound destinations and restrict network access. |
| Security Misconfiguration | Unsafe application or infrastructure settings. | Harden configuration and review deployments. |
| Improper Inventory Management | Unmanaged or outdated API endpoints. | Maintain API inventory and retire old versions. |
| Unsafe Consumption of APIs | Untrusted external API responses are accepted. | Validate external responses and secure integrations. |
19. Secure API Design Checklist
- Use HTTPS everywhere.
- Use a trusted identity provider for authentication.
- Validate access-token issuer, audience, signature and expiry.
- Apply role, policy and resource-based authorization.
- Validate all incoming data.
- Use parameterized SQL queries.
- Prevent mass assignment with DTOs.
- Configure rate limiting and request-size limits.
- Restrict CORS to trusted browser origins.
- Protect secrets using a secret manager.
- Return safe error responses.
- Use secure logging and monitoring.
- Keep .NET and NuGet dependencies updated.
- Perform security testing before production deployment.
20. Interview Questions
Q1. What is the difference between authentication and authorization?
Authentication identifies the user. Authorization determines which resources and operations that user is allowed to access.
Q2. What is JWT?
JSON Web Token is a compact token format commonly used to carry claims between parties. APIs validate its signature and relevant claims before accepting it.
Q3. What is the difference between OAuth 2.0 and OpenID Connect?
OAuth 2.0 is an authorization framework. OpenID Connect adds an identity layer on top of OAuth 2.0 for user authentication.
Q4. What is CORS?
CORS is a browser mechanism that controls whether web pages from one origin can access resources from another origin.
Q5. What is SQL Injection?
SQL Injection is an attack in which untrusted input changes the intended SQL command. Parameterized queries help prevent it.
Q6. What is rate limiting?
Rate limiting restricts the number of requests a client can make within a defined period.
Q7. What is Broken Object Level Authorization?
It occurs when an API does not verify whether the current user has permission to access a specific object, such as another customer's order.
Q8. Why should we use DTOs?
DTOs control which fields clients can send or receive. They help prevent accidental exposure of internal data and mass assignment vulnerabilities.
Q9. Why should sensitive information not be logged?
Logs may be accessible to multiple systems and users. Logging passwords, tokens, or personal data can expose sensitive information.
Q10. What is HSTS?
HTTP Strict Transport Security tells supported browsers to communicate with a website using HTTPS for a specified period.
Conclusion
Secure API design is not achieved by adding JWT authentication alone. It requires multiple layers of protection: authentication, authorization, input validation, secure database access, HTTPS, rate limiting, safe error handling, secret management, and monitoring.
Key principle: Never trust the client. Validate every request, authorize every protected operation, and expose only the data the caller is permitted to access.
| Integration Testing WebApplicationFactory :👈 | 👉:Kestrel Web Server Architecture: Connection Handling and Performance |