5 Ways to Secure a REST API

🔐 5 Ways to Secure a REST API


1️⃣ Authentication (Who are you?)

Ensure only valid users can access the API.

Common methods:

  • JWT Token (most popular)

  • OAuth2 / OpenID Connect

  • API Keys (for system-to-system)

Example (.NET Core – JWT):

[Authorize] [HttpGet("products")] public IActionResult GetProducts() { return Ok(); }

📌 Client sends token:

Authorization: Bearer <JWT_TOKEN>

2️⃣ Authorization (What are you allowed to do?)

Control who can access which endpoint.

Example: Role-based authorization

[Authorize(Roles = "Admin")] [HttpDelete("products/{id}")] public IActionResult Delete(int id) { return Ok(); }

📌 Only users with Admin role can delete.


3️⃣ Use HTTPS Everywhere

Encrypt data in transit to prevent attacks (Man-in-the-middle).

In .NET Core:

app.UseHttpsRedirection();

In Azure App Service:

  • Enforce HTTPS Only (ON)

📌 Protects passwords, tokens, sensitive data.


4️⃣ Input Validation & Protection Against Attacks

Prevent:

  • SQL Injection

  • XSS

  • Overposting

  • Invalid data

Example:

public class ProductDto { [Required] [StringLength(100)] public string Name { get; set; } [Range(1, 100000)] public decimal Price { get; set; } }

📌 Always validate DTOs, not entities.


5️⃣ Rate Limiting & Throttling

Protect API from abuse & DDoS.

Example (.NET 7+):

builder.Services.AddRateLimiter(options => { options.AddFixedWindowLimiter("fixed", opt => { opt.PermitLimit = 100; opt.Window = TimeSpan.FromMinutes(1); }); }); app.UseRateLimiter();

📌 Limits requests per user/IP.


⭐ Bonus Security Practices (Mention if asked)

  • Store secrets in Azure Key Vault

  • Use CORS properly

  • Log & monitor suspicious activity

  • Don’t expose stack traces in production

  • Use Refresh Tokens for JWT


🎯 Interview 1-Line Answer

“I secure APIs using authentication with JWT, role-based authorization, HTTPS, proper input validation, and rate limiting to prevent abuse.”

Comments

Popular posts from this blog

.NET Core Interview Questions and Answers for 10+ Years Experienced Professionals

What are SOLID Principles?

.NET Core Senior Interview Q&A