API security is one of the most important parts of modern software development. If your API is not secure, attackers can steal data, access sensitive information, manipulate systems, or even crash your application.

In this article, we will learn multiple security methods used in ASP.NET Core Web API with easy explanations, real examples, and advanced techniques.

What Is API Security?

API Security means protecting your API from:

Why API Security Is Important?

Without security:

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

LevelSecurity Type
BeginnerHTTPS, Authentication
IntermediateJWT, API Keys, Validation
AdvancedRate Limiting, IP Whitelisting
EnterpriseOAuth2, Zero Trust, WAF

1. HTTPS Security (Basic Level)

HTTPS encrypts data between the client and server.

Without HTTPS:

With HTTPS:

Enable HTTPS in ASP.NET Core

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

3. Authorization Security

Authorization checks:

"What are you allowed to access?"

Example

4. JWT Token Authentication

JWT (JSON Web Token) is a secure token system used for API authentication.

JWT Flow

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

An 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

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 the number of requests.

Protects from:

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 the 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:

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:

Used in enterprise systems.

16. Refresh Token Security

Why Needed?

JWT expires quickly.

A refresh token helps generate a new token without requiring the user to log in again.

17. Data Encryption

Encrypt sensitive data.

Example

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 PracticeDescription
Use HTTPSEncrypt communication
Use JWTSecure authentication
Use HashingProtect passwords
Validate InputsStop invalid data
Use Parameterized QueriesStop SQL Injection
Use Rate LimitingPrevent abuse
Enable LoggingDetect attacks
Restrict SwaggerProtect API docs
Use CORSRestrict domains
Use IP WhitelistRestrict 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

AttackSolution
SQL InjectionParameterized Query
XSSEncode Output
Brute ForceRate Limiting
Token TheftHTTPS
DDoSFirewall + Rate Limit
CSRFAnti-Forgery Token

22. Example of a 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:

Device Tracking

Track:

Audit Trail

Store:

24. Recommended Security Packages

PackageUse
Microsoft.AspNetCore.Authentication.JwtBearerJWT
BCrypt.NetPassword Hashing
SerilogLogging
FluentValidationValidation
AspNetCoreRateLimitRate Limiting

25. Final Recommended Secure Setup

For a production ASP.NET Core API:

Conclusion

API security is not a single feature.

It is a combination of:

A secure ASP.NET Core API should always follow layered security architecture.

Even if one layer fails, another layer should protect the system.

Real-World Example

A Banking API may use:

All together for maximum protection.

Interview Questions

Q1. What is JWT?

JWT is a token-based authentication mechanism used to securely transfer user identity between the client and server.

Q2. Difference Between Authentication and Authorization?

AuthenticationAuthorization
Who are you?What can you access?

Q3. How to Prevent SQL Injection?

Use:

Q4. Why Is HTTPS Important?

HTTPS encrypts communication and protects data from attackers.

End Result

After implementing these methods, your ASP.NET Core API becomes:

Summary

API security in ASP.NET Core Web API requires multiple layers of protection rather than a single security mechanism. By combining HTTPS, authentication, authorization, JWT, API keys, input validation, SQL injection prevention, password hashing, rate limiting, CORS, secure headers, logging, encryption, and other enterprise security practices, you can build APIs that are secure, scalable, and ready for production deployments.