Why Securing Your Web API Matters?
APIs are often the backbone of modern apps, especially in microservice and cloud-based architectures. If left unsecured, your API is vulnerable to attacks like data leaks, unauthorized access, and impersonation.
That’s where JWT (JSON Web Tokens), OAuth 2.0, and ASP.NET Core Identity come into play, providing a complete toolkit to authenticate and authorize users safely.
Overview of Key Security Concepts
| Term | What It Means |
|---|---|
| Authentication | Verifying who the user is (e.g., login) |
| Authorization | Controlling what the user can do (e.g., access certain endpoints) |
| JWT | A secure, compact token used to carry claims about the user |
| OAuth 2.0 | An open standard for delegated authorization |
| ASP.NET Core Identity | Framework for managing users, roles, and credentials |
1. JWT Authentication in ASP.NET Core Web API
JWT (JSON Web Token) is the most common way to secure APIs in a stateless way.
Step-by-Step: Add JWT Authentication
Step 1. Add Required NuGet Packages.
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
Step 2. Configure JWT Authentication in Program.cs.
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddAuthentication("Bearer")
.AddJwtBearer("Bearer", options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = "yourapp.com",
ValidAudience = "yourapp.com",
IssuerSigningKey = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes("super_secret_key_12345"))
};
});
builder.Services.AddAuthorization();
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
Step 3. Secure Your Endpoints.
[Authorize]
[HttpGet("secure-data")]
public IActionResult GetSecureData()
{
return Ok("You are authorized!");
}
Step 4. Issue a JWT Token on Login.
[HttpPost("login")]
public IActionResult Login([FromBody] LoginModel login)
{
// Dummy check
if (login.Username == "admin" && login.Password == "password")
{
var claims = new[]
{
new Claim(ClaimTypes.Name, login.Username)
};
var key = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes("super_secret_key_12345"));
var creds = new SigningCredentials(
key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
issuer: "yourapp.com",
audience: "yourapp.com",
claims: claims,
expires: DateTime.Now.AddMinutes(30),
signingCredentials: creds);
return Ok(new
{
token = new JwtSecurityTokenHandler().WriteToken(token)
});
}
return Unauthorized();
}
2. OAuth 2.0 Authorization
OAuth 2.0 is an authorization framework used to grant access to third-party apps without sharing passwords. It’s used widely in login with Google, Facebook, Microsoft, etc.
Join the conversation! Your thoughts help the community grow.