ASP.NET Core Security ([Authorize], CORS, HTTPS & Rate Limiting) Masterclass

โšก C# 12 & .NET 8 ๐ŸŸข Chapter 40 of 35 ๐Ÿ“‚ Phase 14: Authentication & Security ๐Ÿ“… 2026 Edition
๐Ÿ“Œ Covered in this chapter: [Authorize] ยท Role-Based Auth ยท Policy-Based Auth ยท CORS ยท HTTPS ยท HSTS ยท Secret Management ยท Input Validation ยท SQL Injection Prevention ยท Rate Limiting

Welcome to Phase 14 (Chapter 40): ASP.NET Core Security โ€” [Authorize], CORS, HTTPS, Input Validation & Rate Limiting Masterclass! A secure web API goes far beyond authentication. In this chapter, we implement Role-Based Authorization with [Authorize], Policy-Based Authorization, CORS configuration, HTTPS enforcement, Secret management with User Secrets and Azure Key Vault, Input validation, SQL injection prevention (EF Core handles this), XSS prevention, CSRF basics, and API Rate Limiting.

1[Authorize] โ€” Role-Based & Policy-Based Authorization
C# โ€” Role & Policy Authorization โ–ถ Run in Compiler
// 1. Role-based authorization
[Authorize]                              // Any authenticated user
[Authorize(Roles = "Admin")]             // Admin role only
[Authorize(Roles = "Admin,Manager")]     // Admin OR Manager
[AllowAnonymous]                         // Bypass auth for public endpoints

// 2. Register Policy-Based Authorization
builder.Services.AddAuthorization(options =>
{
    options.AddPolicy("AdminOnly", policy =>
        policy.RequireRole("Admin"));

    options.AddPolicy("MinimumAge18", policy =>
        policy.RequireClaim("DateOfBirth")
              .RequireAssertion(ctx =>
              {
                  var dob = DateTime.Parse(ctx.User.FindFirst("DateOfBirth")!.Value);
                  return (DateTime.Today - dob).TotalDays / 365 >= 18;
              }));
});

// 3. Apply policy on controller
[Authorize(Policy = "AdminOnly")]
[HttpDelete("{id:int}")]
public IActionResult DeleteProduct(int id) { /* only admins reach here */ }
2CORS, HTTPS & Secret Management
C# โ€” CORS & HTTPS Configuration โ–ถ Run in Compiler
// CORS โ€” Allow only specific frontend origins
builder.Services.AddCors(options =>
{
    options.AddPolicy("FrontendPolicy", policy =>
        policy.WithOrigins("https://myapp.com", "http://localhost:3000")
              .AllowAnyMethod()
              .AllowAnyHeader()
              .AllowCredentials());
});

// Middleware order matters!
app.UseCors("FrontendPolicy");
app.UseHttpsRedirection();    // Force HTTPS
app.UseHsts();                // HTTP Strict Transport Security header
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
3Rate Limiting & Input Validation
C# โ€” Rate Limiting (.NET 7+) โ–ถ Run in Compiler
// Built-in Rate Limiting (.NET 7+)
builder.Services.AddRateLimiter(options =>
{
    options.AddFixedWindowLimiter("ApiLimit", opt =>
    {
        opt.PermitLimit   = 100;             // Max 100 requests
        opt.Window        = TimeSpan.FromMinutes(1); // per minute
        opt.QueueLimit    = 0;               // No queuing, reject immediately
    });
    options.RejectionStatusCode = 429;       // Too Many Requests
});

app.UseRateLimiter();

// Apply to all endpoints
app.MapControllers().RequireRateLimiting("ApiLimit");
4Technical FAQs

Q1: Does EF Core prevent SQL Injection automatically?

Yes! EF Core always uses parameterized queries when translating LINQ expressions to SQL. Parameterized queries treat user input as data values โ€” never executable SQL code โ€” completely preventing SQL injection. Never use raw SQL string concatenation with user input.

Q2: What is CORS and why is it needed?

Cross-Origin Resource Sharing (CORS) is a browser security feature that blocks JavaScript from making API calls to a different origin (domain, port, or protocol) unless the server explicitly allows it. Your API needs CORS configuration to allow frontend apps (e.g., React on localhost:3000) to make requests.