What is JWT Authentication | How to apply in API in .NET Core

 This tutorial assumes you’re building an MVC app that also exposes APIs or wants token-based login.





🔹 Step 1: Create ASP.NET Core MVC Project

dotnet new mvc -n JwtAuthDemo cd JwtAuthDemo

🔹 Step 2: Install Required NuGet Packages

dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer dotnet add package System.IdentityModel.Tokens.Jwt

🔹 Step 3: Add JWT Settings in appsettings.json

{ "Jwt": { "Key": "ThisIsMySecretKeyForJwt123!", "Issuer": "https://yourdomain.com", "Audience": "https://yourdomain.com", "ExpireMinutes": 30 }, "Logging": { "LogLevel": { "Default": "Information" } }, "AllowedHosts": "*" }

⚠️ Use a long, secure key (store it in User Secrets or Azure Key Vault in production).


🔹 Step 4: Configure JWT in Program.cs

using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.IdentityModel.Tokens; using System.Text; var builder = WebApplication.CreateBuilder(args); // 1. Add Controllers with Views builder.Services.AddControllersWithViews(); // 2. JWT Authentication Configuration var jwtSettings = builder.Configuration.GetSection("Jwt"); var key = Encoding.UTF8.GetBytes(jwtSettings["Key"]); 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 = jwtSettings["Issuer"], ValidAudience = jwtSettings["Audience"], IssuerSigningKey = new SymmetricSecurityKey(key) }; }); var app = builder.Build(); // Middlewares app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); // Authentication & Authorization app.UseAuthentication(); app.UseAuthorization(); app.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); app.Run();

🔹 Step 5: Create a Model for Login

Models/LoginModel.cs

namespace JwtAuthDemo.Models { public class LoginModel { public string Username { get; set; } public string Password { get; set; } } }

🔹 Step 6: Create Token Service

Services/TokenService.cs

using Microsoft.Extensions.Configuration; using Microsoft.IdentityModel.Tokens; using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; using System.Text; namespace JwtAuthDemo.Services { public class TokenService { private readonly IConfiguration _config; public TokenService(IConfiguration config) { _config = config; } public string GenerateToken(string username, string role) { var jwtSettings = _config.GetSection("Jwt"); var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings["Key"])); var claims = new[] { new Claim(ClaimTypes.Name, username), new Claim(ClaimTypes.Role, role) }; var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var token = new JwtSecurityToken( issuer: jwtSettings["Issuer"], audience: jwtSettings["Audience"], claims: claims, expires: DateTime.Now.AddMinutes(Convert.ToDouble(jwtSettings["ExpireMinutes"])), signingCredentials: creds ); return new JwtSecurityTokenHandler().WriteToken(token); } } }

🔹 Step 7: Create Authentication Controller

Controllers/AuthController.cs

using JwtAuthDemo.Models; using JwtAuthDemo.Services; using Microsoft.AspNetCore.Mvc; namespace JwtAuthDemo.Controllers { [ApiController] [Route("api/[controller]")] public class AuthController : ControllerBase { private readonly TokenService _tokenService; public AuthController(TokenService tokenService) { _tokenService = tokenService; } [HttpPost("login")] public IActionResult Login([FromBody] LoginModel login) { // ⚠️ Replace with real user validation (DB/Identity) if (login.Username == "admin" && login.Password == "123") { var token = _tokenService.GenerateToken(login.Username, "Admin"); return Ok(new { Token = token }); } return Unauthorized("Invalid credentials"); } } }

🔹 Step 8: Protect Your MVC Controllers

Example: Controllers/HomeController.cs

using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; namespace JwtAuthDemo.Controllers { public class HomeController : Controller { [Authorize] public IActionResult Index() { return Content("Welcome! You are authenticated with JWT."); } [Authorize(Roles = "Admin")] public IActionResult AdminOnly() { return Content("Hello Admin! You have access."); } } }

🔹 Step 9: Test the Flow

  1. Run the project → https://localhost:5001/api/auth/login
    Send POST request with:

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

    Response:

    { "token": "eyJhbGciOi..." }
  2. Use this token in Authorization Header:

    Authorization: Bearer eyJhbGciOi...
  3. Access https://localhost:5001/home/index → works only with valid JWT.
    Access https://localhost:5001/home/adminonly → works only if role is "Admin".

Post a Comment

0 Comments