التخطي إلى المحتوى الرئيسي

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".

تعليقات

المشاركات الشائعة من هذه المدونة

DSA in C# | Data Structure and Algorithm using C#

  DSA in C# |  Data Structure and Algorithm using C#: Lecture 1: Introduction to Data Structures and Algorithms (1 Hour) 1.1 What are Data Structures? Data Structures are ways to store and organize data so it can be used efficiently. Think of data structures as containers that hold data in a specific format. Types of Data Structures: Primitive Data Structures : These are basic structures built into the language. Example: int , float , char , bool in C#. Example : csharp int age = 25;  // 'age' stores an integer value. bool isStudent = true;  // 'isStudent' stores a boolean value. Non-Primitive Data Structures : These are more complex and are built using primitive types. They are divided into: Linear : Arrays, Lists, Queues, Stacks (data is arranged in a sequence). Non-Linear : Trees, Graphs (data is connected in more complex ways). Example : // Array is a simple linear data structure int[] number...

JSP Page design using Internal CSS

  JSP is used to design the user interface of an application, CSS is used to provide set of properties. Jsp provide proper page template to create user interface of dynamic web application. We can write CSS using three different ways 1)  inline CSS:-   we will write CSS tag under HTML elements <div style="width:200px; height:100px; background-color:green;"></div> 2)  Internal CSS:-  we will write CSS under <style> block. <style type="text/css"> #abc { width:200px;  height:100px;  background-color:green; } </style> <div id="abc"></div> 3) External CSS:-  we will write CSS to create a separate file and link it into HTML Web pages. create a separate file and named it style.css #abc { width:200px;  height:100px;  background-color:green; } go into Jsp page and link style.css <link href="style.css"  type="text/css" rel="stylesheet"   /> <div id="abc"> </div> Exam...

Top 50 Most Asked MERN Stack Interview Questions and Answers for 2025

 Top 50 Most Asked MERN Stack Interview Questions and Answers for 2025 Now a days most of the IT Company asked NODE JS Question mostly in interview. I am creating this article to provide help to all MERN Stack developer , who is in doubt that which type of question can be asked in MERN Stack  then they can learn from this article. I am Shiva Gautam,  I have 15 Years of experience in Multiple IT Technology, I am Founder of Shiva Concept Solution Best Programming Institute with 100% Job placement guarantee. for more information visit  Shiva Concept Solution 1. What is the MERN Stack? Answer : MERN Stack is a full-stack JavaScript framework using MongoDB (database), Express.js (backend framework), React (frontend library), and Node.js (server runtime). It’s popular for building fast, scalable web apps with one language—JavaScript. 2. What is MongoDB, and why use it in MERN? Answer : MongoDB is a NoSQL database that stores data in flexible, JSON-like documents. It...