Introduction
In this hands-on guide, you’ll learn how to build a RESTful Web API in ASP.NET MVC using C# with JWT (JSON Web Token) Authentication. This is a modern and secure method for handling user authentication and protecting your endpoints.
By the end of this tutorial, you’ll be able to.
- Generate JWT tokens on login
- Authenticate API calls using tokens
- Secure endpoints so only logged-in users can access them
Tools Required
- Visual Studio 2019/2022
- .NET Framework (4.7 or later)
- NuGet Package: System.IdentityModel.Tokens.Jwt
Step 1. Create a New ASP.NET Web API Project
- Open Visual Studio
- File → New → Project
- Select ASP.NET Web Application (.NET Framework)
- Name it JwtStudentAPI
- Choose the Web API template and click Create
Step 2. Install Required NuGet Package
Open the Package Manager Console and run.
Install-Package System.IdentityModel.Tokens.Jwt
Step 3. Create Student Model
File: Models/Student.cs.
using System;
namespace JwtStudentAPI.Models
{
public class Student
{
public string StudentId { get; set; }
public string Name { get; set; }
public DateTime DateOfBirth { get; set; }
public string ZipCode { get; set; }
public string Major { get; set; }
}
}
Step 4. Create Login Model
File: Models/UserCredential.cs.
namespace JwtStudentAPI.Models
{
public class UserCredential
{
public string Username { get; set; }
public string Password { get; set; }
}
}
This is a simple model for a login payload.
Step 5. Add Token Generation Logic
File: Controllers/AuthController.cs.
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using System.Web.Http;
using JwtStudentAPI.Models;
using Microsoft.IdentityModel.Tokens;
namespace JwtStudentAPI.Controllers
{
public class AuthController : ApiController
{
[HttpPost]
[Route("api/auth/login")]
public IHttpActionResult Login(UserCredential login)
{
if (login.Username == "admin" && login.Password == "pass123")
{
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes("MySuperSecretKey12345");
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new[]
{
new Claim(ClaimTypes.Name, login.Username)
}),
Expires = DateTime.UtcNow.AddMinutes(30),
SigningCredentials = new SigningCredentials(
new SymmetricSecurityKey(key),
SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
var tokenString = tokenHandler.WriteToken(token);
return Ok(new { token = tokenString });
}
return Unauthorized();
}
}
}
Explanation
- Validates the hardcoded user (for demo).
- Generates a JWT using a secret key.
- Returns the token to the client.
Step 6. Create a Token Validation Handler
File: Handlers/JwtValidationHandler.cs.

Hung Phan BaPosted Oct 19, 2025, 2:26 PM
I got: Message": "Authorization has been denied for this request." Pls help me