Building a secure API is one of the most important tasks in modern web development. When you create APIs using ASP.NET Core, you must ensure that your API is protected from unauthorized access, data leaks, and attacks like SQL Injection, XSS, and brute force login attempts.
In this blog, we will learn how to write secure API in .NET Core with practical steps and best practices.
1. Use HTTPS Always
- The first rule of API security is to use HTTPS instead of HTTP.
- HTTPS encrypts data between client and server.
Enable HTTPS in ASP.NET Core
app.UseHttpsRedirection();
In launchSettings.json
"applicationUrl": "https://localhost:5001"
Benefit
- Data encryption
- Prevent man-in-the-middle attack
- Secure login & tokens
2. Use Authentication (JWT Token)
- Authentication is required to verify the user.
- Best way in .NET Core API → JWT Authentication
Use package:
Microsoft.AspNetCore.Authentication.JwtBearer
Configure JWT
builder.Services.AddAuthentication("Bearer")
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true
};
});
Use Authorize
[Authorize]
[HttpGet]
public IActionResult GetData()
{
return Ok("Secure Data");
}
Benefit
- Only logged users can access API
- Secure token based login
- Used in production systems
3. Use Authorization (Role Based)
- Authentication = Who are you
- Authorization = What you can do
[Authorize(Roles = "Admin")]
public IActionResult DeleteUser()
{
}
You can also use policy:
builder.Services.AddAuthorization(options =>
{
options.AddPolicy("AdminOnly",
policy => policy.RequireRole("Admin"));
});
4. Validate Input Data
- Never trust user input.
- Use Model Validation.
public class UserModel
{
[Required]
public string Name { get; set; }
[EmailAddress]
public string Email { get; set; }
}
In Controller:
if (!ModelState.IsValid)
return BadRequest(ModelState);
Prevents
- SQL Injection
- Invalid data
- Crash errors
5. Use Exception Handling Middleware
- Never show real error to user.
- Create global exception handler.
app.UseExceptionHandler("/error");
Custom middleware:
app.Use(async (context, next) =>
{
try
{
await next();
}
catch (Exception ex)
{
context.Response.StatusCode = 500;
await context.Response.WriteAsync("Error");
}
});
Benefit
- Hide server details
- Prevent hacking info leak
6. Use Logging
- Use logging to track errors and attacks.
- Built-in logging in ASP.NET Core
ILogger<HomeController> _logger;
_logger.LogError("Error occurred");
You can use:
- Serilog
- NLog
- File logging
- Database logging
Benefit
- Debug issues
- Track hackers
- Monitor API
7. Use Rate Limiting
Prevent too many requests.
Install:
AspNetCoreRateLimit
Example:
services.AddInMemoryRateLimiting();
Limit requests per minute.
Prevents
- DDOS
- Brute force
- API abuse
8. Use CORS Properly
Allow only trusted domains.
builder.Services.AddCors(options =>
{
options.AddPolicy("MyPolicy",
policy =>
{
policy.WithOrigins("https://mindstick.com")
.AllowAnyHeader()
.AllowAnyMethod();
});
});
Use:
app.UseCors("MyPolicy");
Prevents unauthorized calls
9. Use Stored Procedure / Parameterized Query
Never write raw SQL.
Bad
"select * from user where id=" + id
Good
command.Parameters.AddWithValue("@id", id);
Prevents SQL Injection.
10. Use API Versioning
Secure and maintain API versions.
Install:
Microsoft.AspNetCore.Mvc.Versioning
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/user")]
Benefit
- Safe updates
- No breaking changes
- Production ready
Conclusion
To write secure API in .NET Core, always follow:
- Use HTTPS
- Use JWT Authentication
- Use Authorization
- Validate Input
- Handle Exceptions
- Use Logging
- Rate Limiting
- CORS
- Parameterized Query
- API Versioning