ASP.NET Core  

Complete Guide to ASP.NET Core API Security

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:

  • Unauthorized access

  • Data theft

  • SQL Injection

  • Cross-site attacks

  • Brute-force attacks

  • Token hijacking

  • Server misuse

  • Fake requests

  • DDoS attacks

Why API Security is Important?

Without security:

  • Hackers can access private data

  • Anyone can call your APIs

  • Database can be hacked

  • Users’ passwords can leak

  • System performance can be destroyed

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 client and server.

Without HTTPS:

  • Data travels as plain text.

With HTTPS:

  • Data becomes encrypted.

Enable HTTPS in ASP.NET Core

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

  • Username + Password

  • WT Token

  • OAuth Login

3. Authorization Security

Authorization checks:

“What are you allowed to access?”

Example:

  • Admin can delete users

  • User can only view profile

4. JWT Token Authentication

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

JWT Flow

  • User logs in

  • Server validates credentials

  • Server generates token

  • Client sends token in every request

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

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:

  • Government APIs

  • Banking APIs

  • Internal APIs

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

Protects from:

  • DDoS

  • Spam

  • Brute-force attacks

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

  • Hacking attempts

  • Failed logins

  • Suspicious activities

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:

  • Google

  • Microsoft

  • Facebook

  • GitHub

Used in enterprise systems.

16. Refresh Token Security

Why Needed?

JWT expires quickly.

Refresh Token helps generate new token without login.

17. Data Encryption

Encrypt Sensitive Data

Example:

  • Aadhaar Number

  • PAN Number

  • Bank Details

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

  • OTP

  • Email verification

  • Authenticator apps

Device Tracking

Track:

  • IP

  • Browser

  • Device ID

Audit Trail

Store:

  • Login history

  • User actions

  • Data changes

24. Recommended Security Packages

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

25. Final Recommended Secure Setup

For production ASP.NET Core API:

✅ HTTPS
✅ JWT Authentication
✅ API Key
✅ IP Whitelist
✅ Rate Limiting
✅ Logging
✅ SQL Injection Protection
✅ Password Hashing
✅ CORS
✅ Secure Headers
✅ Audit Logs
✅ Encryption

Conclusion

API security is not a single feature.

It is a combination of:

  • Authentication

  • Authorization

  • Encryption

  • Validation

  • Monitoring

  • Network protection

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:

  • HTTPS

  • JWT

  • API Key

  • IP Whitelist

  • Rate Limiting

  • Encryption

  • MFA

  • Audit Logs

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 client and server.

Q2. Difference between Authentication and Authorization?

AuthenticationAuthorization
Who are you?What can you access?

Q3. How to prevent SQL Injection?

Use:

  • Parameterized queries

  • ORM frameworks

  • Input validation

Q4. Why HTTPS is important?

HTTPS encrypts communication and protects data from attackers.

End Result

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

✅ Secure

✅ Scalable

✅ Enterprise Ready

✅ Production Ready