One of the most crucial aspects of contemporary software development is API security. Attackers may steal data, gain access to private information, alter systems, or even cause your program to fail if your API is not secure. This post will teach us several security measures for the ASP.NET Core Web API with clear explanations, practical examples, and sophisticated methods.
What is API Security?
API Security means protecting your API from:
- Unauthorized access
- Data theft
- SQL Injection
- Cross-site attacks
- Brute-force attacks
- Token hijacking
- Server misuse
- Fake requests
- DDoS attacks
Why API Security is Important?
Without security:
- Hackers can access private data
- Anyone can call your APIs
- Database can be hacked
- Users’ passwords can leak
- System performance can be destroyed
Example:
Imagine your banking API has no authentication.
Anyone can call:
GET /api/account/balance?id=1
Then all customer data becomes public.
Security Levels in ASP.NET Core API
| Level | Security Type |
|
Beginner
|
HTTPS, Authentication
|
|
Intermediate
|
JWT, API Keys, Validation
|
|
Advanced
|
Rate Limiting, IP Whitelisting
|
|
Enterprise
|
OAuth2, Zero Trust, WAF
|
1. HTTPS Security (Basic Level)
HTTPS encrypts data between client and server.
Without HTTPS:
- Data travels as plain text.
With HTTPS:
Enable HTTPS in ASP.NET Core
In Program.cs:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddHttpsRedirection(options =>
{
options.HttpsPort = 443;
});
var app = builder.Build();
app.UseHttpsRedirection();
app.Run();
2. Authentication Security
Authentication checks:
“Who are you?”
Example:
- Username + Password
- WT Token
- OAuth Login
3. Authorization Security
Authorization checks:
“What are you allowed to access?”
Example:
- Admin can delete users
- User can only view profile
4. JWT Token Authentication
JWT (JSON Web Token) is a secure token system used for API authentication.
JWT Flow
- User logs in
- Server validates credentials
- Server generates token
- Client sends token in every request
Install JWT Package
Install-Package Microsoft.AspNetCore.Authentication.JwtBearer
JWT Configuration
Program.cs
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = "MyAPI",
ValidAudience = "MyAPIUser",
IssuerSigningKey = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes("THIS_IS_SECRET_KEY_123456"))
};
});
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.Run();
Generate JWT Token
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using Microsoft.IdentityModel.Tokens;
using System.Text;
public string GenerateToken(string username)
{
var claims = new[]
{
new Claim(ClaimTypes.Name, username)
};
var key = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes("THIS_IS_SECRET_KEY_123456"));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
issuer: "MyAPI",
audience: "MyAPIUser",
claims: claims,
expires: DateTime.Now.AddHours(1),
signingCredentials: creds);
return new JwtSecurityTokenHandler().WriteToken(token);
}
Secure API Controller
[Authorize]
[ApiController]
[Route("api/[controller]")]
public class UserController : ControllerBase
{
[HttpGet]
public IActionResult GetData()
{
return Ok("Secure Data");
}
}
5. API Key Security
API Key is a secret key sent in request headers.
Example:
x-api-key: ABC123XYZ
Middleware Example
public class ApiKeyMiddleware
{
private readonly RequestDelegate _next;
private const string APIKEY = "MY_SECRET_KEY";
public ApiKeyMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
if (!context.Request.Headers.TryGetValue("x-api-key", out var extractedApiKey))
{
context.Response.StatusCode = 401;
await context.Response.WriteAsync("API Key Missing");
return;
}
if (!APIKEY.Equals(extractedApiKey))
{
context.Response.StatusCode = 403;
await context.Response.WriteAsync("Invalid API Key");
return;
}
await _next(context);
}
}
Register Middleware
app.UseMiddleware<ApiKeyMiddleware>();
6. IP Whitelisting Security
Only allowed IP addresses can access APIs.
Example:
- Government APIs
- Banking APIs
- Internal APIs
Middleware Example
public class IPWhitelistMiddleware
{
private readonly RequestDelegate _next;
private readonly List<string> allowedIPs = new()
{
"127.0.0.1",
"192.168.1.10"
};
public IPWhitelistMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
var remoteIp = context.Connection.RemoteIpAddress?.ToString();
if (!allowedIPs.Contains(remoteIp))
{
context.Response.StatusCode = 403;
await context.Response.WriteAsync("IP Not Allowed");
return;
}
await _next(context);
}
}
7. SQL Injection Protection
Dangerous Code
Wrong:
string query = "SELECT * FROM Users WHERE Name='" + username + "'";
Attacker Input:
' OR 1=1 --
This can expose all records.
Secure Code
Correct:
SqlCommand cmd = new SqlCommand(
"SELECT * FROM Users WHERE Name=@Name", conn);
cmd.Parameters.AddWithValue("@Name", username);
8. Password Hashing Security
Never Store Plain Passwords
Wrong:
Password = 123456
Correct:
Password = Hashed Value
Password Hashing Example
using BCrypt.Net;
string hash = BCrypt.Net.BCrypt.HashPassword("123456");
bool verify = BCrypt.Net.BCrypt.Verify("123456", hash);
9. Rate Limiting Protection
Limits number of requests.
Protects from:
- DDoS
- Spam
- Brute-force attacks
ASP.NET Core Rate Limiting
Program.cs
builder.Services.AddRateLimiter(options =>
{
options.AddFixedWindowLimiter("fixed", opt =>
{
opt.PermitLimit = 10;
opt.Window = TimeSpan.FromMinutes(1);
});
});
app.UseRateLimiter();
Apply Rate Limit
[EnableRateLimiting("fixed")]
[HttpGet]
public IActionResult Get()
{
return Ok();
}
10. CORS Security
CORS controls which frontend domains can access API.
Enable Secure CORS
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowMyApp",
policy =>
{
policy.WithOrigins("https://myapp.com")
.AllowAnyHeader()
.AllowAnyMethod();
});
});
app.UseCors("AllowMyApp");
11. Request Validation Security
Validate incoming data.
Example
public class LoginModel
{
[Required]
public string Username { get; set; }
[Required]
[MinLength(6)]
public string Password { get; set; }
}
12. Secure Headers
Add Security Headers
app.Use(async (context, next) =>
{
context.Response.Headers.Add("X-Frame-Options", "DENY");
context.Response.Headers.Add("X-XSS-Protection", "1; mode=block");
context.Response.Headers.Add("X-Content-Type-Options", "nosniff");
await next();
});
13. Logging and Monitoring
Why Important?
Detect:
- Hacking attempts
- Failed logins
- Suspicious activities
Example
try
{
// code
}
catch(Exception ex)
{
_logger.LogError(ex.Message);
}
14. Swagger Security
Protect Swagger in Production
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
15. OAuth2 Security (Advanced)
OAuth2 allows login using:
- Google
- Microsoft
- Facebook
- GitHub
Used in enterprise systems.
16. Refresh Token Security
Why Needed?
JWT expires quickly.
Refresh Token helps generate new token without login.
17. Data Encryption
Encrypt Sensitive Data
Example:
- Aadhaar Number
- PAN Number
- Bank Details
AES Encryption Example
using System.Security.Cryptography;
Use AES encryption for highly sensitive data.
18. CSRF Protection
Stops fake requests from external websites.
Mostly important in cookie-based authentication.
19. Security Best Practices
| Best Practice | Description |
|
Use HTTPS
|
Encrypt communication
|
|
Use JWT
|
Secure authentication
|
|
Use Hashing
|
Protect passwords
|
|
Validate Inputs
|
Stop invalid data
|
|
Use Parameterized Queries
|
Stop SQL Injection
|
|
Use Rate Limiting
|
Prevent abuse
|
|
Enable Logging
|
Detect attacks
|
|
Restrict Swagger
|
Protect API docs
|
|
Use CORS
|
Restrict domains
|
|
Use IP Whitelist
|
Restrict access
|
20. Enterprise-Level Security Architecture
Recommended Flow
Client App
↓
API Gateway
↓
WAF Firewall
↓
Rate Limiter
↓
JWT Authentication
↓
Authorization
↓
Controller
↓
Database
21. Common API Attacks
| Attack | Solution |
|
SQL Injection
|
Parameterized Query
|
|
XSS
|
Encode Output
|
|
Brute Force
|
Rate Limiting
|
|
Token Theft
|
HTTPS
|
|
DDoS
|
Firewall + Rate Limit
|
|
CSRF
|
Anti-Forgery Token
|
22. Example of Fully Secure API Request
POST /api/user/profile
Host: example.com
Authorization: Bearer TOKEN
x-api-key: APIKEY123
Content-Type: application/json
23. Advanced Enterprise Security Features
Multi-Factor Authentication (MFA)
Extra security layer:
- OTP
- Email verification
- Authenticator apps
Device Tracking
Track:
Audit Trail
Store:
- Login history
- User actions
- Data changes
24. Recommended Security Packages
| Package | Use |
| Microsoft.AspNetCore.Authentication.JwtBearer |
JWT |
| BCrypt.Net |
Password Hashing |
| Serilog |
Logging |
| FluentValidation |
Validation |
| AspNetCoreRateLimit |
Rate Limiting |
25. Final Recommended Secure Setup
For production ASP.NET Core API:
- HTTPS
- JWT Authentication
- API Key
- IP Whitelist
- Rate Limiting
- Logging
- SQL Injection Protection
- Password Hashing
- CORS
- Secure Headers
- Audit Logs
- Encryption
HostForLIFE.eu ASP.NET Core 10.0 Hosting
European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.
