### ✅ JWT Tokens in .
NET Core API – Explained Clearly
**JWT (JSON Web Token)** is a compact, URL-safe token used for securely
transmitting information between parties as a JSON object. In a .NET Core API, JWT
is commonly used for **authentication and authorization**.
### 🧱 Structure of a JWT
A JWT consists of **three parts**:
* **Header**: Type of the token (JWT) + signing algorithm (e.g., HS256)
* **Payload**: Claims (user info, roles, expiration, etc.)
* **Signature**: Created using a secret key (for verifying the token’s
authenticity)
### 🔐 How JWT Authentication Works in .NET Core API
#### 1. **User Logs In**
* The user sends their **username/password** to `/login`.
* If valid, the server creates a **JWT token** with user claims and sends it to the
client.
#### 2. **Client Stores Token**
* Usually stored in **localStorage** or **sessionStorage** in a browser.
* Sent on every API call using `Authorization: Bearer <token>` header.
#### 3. **Server Validates Token**
* Middleware checks for a valid token in the request.
* If valid, the request is allowed; else it returns `401 Unauthorized`.
### Example: Setting Up JWT in .NET Core API
#### **1. Add NuGet Package**
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
#### **2. Configure JWT Authentication (in `Program.cs` / `Startup.cs`)**
builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = "myapi.com",
ValidAudience = "myapi.com",
IssuerSigningKey = new
SymmetricSecurityKey(Encoding.UTF8.GetBytes("MySuperSecretKey"))
};
});
#### **3. Enable Authentication Middleware**
app.UseAuthentication();
app.UseAuthorization();
#### **4. Generate Token (e.g., in `AuthController`)**
[HttpPost("login")]
public IActionResult Login([FromBody] LoginModel user)
{
if (user.Username == "admin" && user.Password == "pass123")
{
var claims = new[]
{
new Claim(ClaimTypes.Name, user.Username),
new Claim(ClaimTypes.Role, "Admin")
};
var key = new
SymmetricSecurityKey(Encoding.UTF8.GetBytes("MySuperSecretKey"));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
issuer: "myapi.com",
audience: "myapi.com",
claims: claims,
expires: DateTime.Now.AddHours(1),
signingCredentials: creds);
return Ok(new { token = new JwtSecurityTokenHandler().WriteToken(token) });
}
return Unauthorized();
}
### ✅ Example Secured Endpoint
[Authorize(Roles = "Admin")]
[HttpGet("secure-data")]
public IActionResult GetSecureData()
{
return Ok("This is protected data");
}
### 🔍 Summary
| Step | Purpose |
| ------------ | -------------------------------- |
| Login | User gets a JWT token |
| Store Token | Saved on client side |
| Use Token | Sent in request headers |
| Middleware | Validates and sets user context |
| \[Authorize] | Restricts access based on claims |