What is JWT?

 

🔹 What is JWT?

JWT (JSON Web Token) is a secure, compact way to transmit information between two parties (like client ↔ server).

  • Server generates a JWT token after login.

  • Client stores it (usually in localStorage/sessionStorage).

  • For each API request, client sends the token in the Authorization header.

  • Server validates the token before giving access.


🔹 Why use JWT in WebAPI?

✅ Stateless (no session stored in server memory)
✅ Works well in distributed/microservices systems
✅ Compact and secure (signed with secret key)
✅ Easy to pass in HTTP headers


🔹 JWT Token Structure

A JWT has 3 parts (separated by .):

xxxxx.yyyyy.zzzzz
  1. Header – algorithm & token type

  2. Payload – claims (user info, roles, expiry)

  3. Signature – hash of header+payload+secret

Example:

{ "sub": "chandan", "role": "admin", "exp": 1735765200 }

🔹 Steps in .NET WebAPI with JWT

1. Install Package

dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer

2. Add JWT Settings in appsettings.json

"Jwt": { "Key": "ThisIsASecretKeyForJwtDemo123!", "Issuer": "MyApp", "Audience": "MyAppUsers", "ExpireMinutes": 30 }

3. Configure JWT in Program.cs

using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.IdentityModel.Tokens; using System.Text; var builder = WebApplication.CreateBuilder(args); // Add Authentication 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 = builder.Configuration["Jwt:Issuer"], ValidAudience = builder.Configuration["Jwt:Audience"], IssuerSigningKey = new SymmetricSecurityKey( Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"])) }; }); builder.Services.AddControllers(); var app = builder.Build(); app.UseAuthentication(); // must come before Authorization app.UseAuthorization(); app.MapControllers(); app.Run();

4. Create a Login Controller to Generate Token

using Microsoft.AspNetCore.Mvc; using Microsoft.IdentityModel.Tokens; using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; using System.Text; [ApiController] [Route("api/[controller]")] public class AuthController : ControllerBase { private readonly IConfiguration _config; public AuthController(IConfiguration config) { _config = config; } [HttpPost("login")] public IActionResult Login([FromBody] LoginModel login) { if (login.Username == "admin" && login.Password == "password123") // demo only { var token = GenerateJwtToken(login.Username, "Admin"); return Ok(new { token }); } return Unauthorized(); } private string GenerateJwtToken(string username, string role) { var claims = new[] { new Claim(JwtRegisteredClaimNames.Sub, username), new Claim(ClaimTypes.Role, role), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()) }; var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"])); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var token = new JwtSecurityToken( issuer: _config["Jwt:Issuer"], audience: _config["Jwt:Audience"], claims: claims, expires: DateTime.UtcNow.AddMinutes(Convert.ToDouble(_config["Jwt:ExpireMinutes"])), signingCredentials: creds ); return new JwtSecurityTokenHandler().WriteToken(token); } } public class LoginModel { public string Username { get; set; } public string Password { get; set; } }

5. Protect API Endpoints with [Authorize]

using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; [ApiController] [Route("api/[controller]")] public class ProductsController : ControllerBase { [HttpGet("public")] public IActionResult PublicEndpoint() { return Ok("Anyone can see this"); } [Authorize] [HttpGet("private")] public IActionResult PrivateEndpoint() { return Ok("Only logged-in users with a valid token can see this"); } [Authorize(Roles = "Admin")] [HttpGet("admin")] public IActionResult AdminEndpoint() { return Ok("Only Admins can see this"); } }

🔹 Flow

  1. Client calls POST /api/auth/login with username & password.

  2. Server responds with JWT token.

  3. Client saves token.

  4. For protected APIs, client sends:

Authorization: Bearer <JWT_TOKEN>
  1. Server validates token → If valid, access granted.


🔹 Example Request in Postman

POST /api/auth/login
Body (JSON):

{ "username": "admin", "password": "password123" }

Response:

{ "token": "eyJhbGciOiJIUzI1NiIsInR..." }

✅ Now you have JWT Authentication working in .NET WebAPI.

  • Easy to integrate with Angular/React or even mobile apps.

  • Secure since the token is signed and can include roles/claims.

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