REST APIs are the backbone of modern applications, powering everything from mobile apps to enterprise integrations. But with this power comes responsibility; if APIs aren’t secure, they become an easy target for attackers.
In this article, we’ll walk through how to build secure REST APIs with ASP.NET Core , covering authentication, authorization, data protection, and real-world code samples .
Step 1: Start with HTTPS Everywhere
APIs must never be exposed over plain HTTP. Use HTTPS to encrypt communication.
In Program.cs :
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.UseHttpsRedirection(); // Force HTTPS
app.MapControllers();
app.Run();
Step 2: Implement Authentication with JWT
Most secure APIs rely on JWT (JSON Web Tokens) for authentication.
Configure JWT in Program.cs :
builder.Services.AddAuthentication("Bearer")
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = builder.Configuration["Jwt:Issuer"],
ValidAudience = builder.Configuration["Jwt:Audience"],
IssuerSigningKey = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]))
};
});
Secure Controller with [Authorize] :
[ApiController]
[Route("api/[controller]")]
public class OrdersController : ControllerBase
{
[HttpGet]
[Authorize]
public IActionResult GetOrders()
{
return Ok(new { Message = "Secure orders retrieved!" });
}
}
Step 3: Role-Based Authorization
Control who can access what using roles or policies.
[HttpPost]
[Authorize(Roles = "Admin")]
public IActionResult CreateOrder()
{
return Ok("Order created by Admin");
}
For more granular control, use policy-based authorization :
builder.Services.AddAuthorization(options =>
{
options.AddPolicy("RequireManager", policy => policy.RequireRole("Manager"));
});
Step 4: Input Validation & Model Binding
Never trust user input—validate it.
public class OrderModel
{
[Required]
public string Product { get; set; }
[Range(1, 100)]
public int Quantity { get; set; }
}
[HttpPost]
public IActionResult PlaceOrder([FromBody] OrderModel model)
{
if (!ModelState.IsValid)
return BadRequest(ModelState);
return Ok("Order placed securely");
}

Comments
Join the conversation! Your thoughts help the community grow.