how to implement jwt token in asp.net mvc4.5 c# with clear explaination
Loading
how to implement jwt token in asp.net mvc4.5 c# with clear explaination
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Sarthak VarshneyRank #46 · 32K reputationPosted Jun 13, 2024, 2:08 AM EDT
Implementing JWT (JSON Web Token) in ASP.NET MVC 4.5 involves configuring your application to issue and validate JWT tokens. Here's a clear, step-by-step guide to help you implement JWT authentication in your ASP.NET MVC 4.5 application:
Step 1: Install Necessary Packages
First, you need to install the necessary NuGet packages for JWT. In this case, we will use the
System.IdentityModel.Tokens.Jwtpackage.Step 2: Create a JWT Helper Class
Create a helper class to handle the creation and validation of JWT tokens.
using System; using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; using System.Security.Cryptography; using Microsoft.IdentityModel.Tokens; public static class JwtHelper { private static readonly string SecretKey = "YourSecretKeyHere"; // Ensure this is a secure key private static readonly SymmetricSecurityKey SigningKey = new SymmetricSecurityKey(Convert.FromBase64String(SecretKey)); public static string GenerateToken(string username, int expireMinutes = 30) { var tokenHandler = new JwtSecurityTokenHandler(); var now = DateTime.UtcNow; var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, username) }), Expires = now.AddMinutes(expireMinutes), SigningCredentials = new SigningCredentials(SigningKey, SecurityAlgorithms.HmacSha256Signature) }; var stoken = tokenHandler.CreateToken(tokenDescriptor); var token = tokenHandler.WriteToken(stoken); return token; } public static ClaimsPrincipal GetPrincipal(string token) { try { var tokenHandler = new JwtSecurityTokenHandler(); var validationParameters = new TokenValidationParameters { ValidateIssuer = false, ValidateAudience = false, ValidateLifetime = true, ValidateIssuerSigningKey = true, IssuerSigningKey = SigningKey }; var principal = tokenHandler.ValidateToken(token, validationParameters, out _); return principal; } catch (Exception) { return null; } } }Step 3: Implement Login Action
In your controller, implement a login action that issues a JWT token upon successful authentication.
using System.Web.Mvc; public class AccountController : Controller { [HttpPost] public ActionResult Login(string username, string password) { // Implement your user authentication logic here bool isAuthenticated = AuthenticateUser(username, password); if (isAuthenticated) { string token = JwtHelper.GenerateToken(username); return Json(new { token }); } else { return Json(new { error = "Invalid username or password" }); } } private bool AuthenticateUser(string username, string password) { // Replace with your user authentication logic return username == "testuser" && password == "testpassword"; } }Step 4: Secure Your Actions with JWT
To secure your controller actions with JWT, create an action filter that validates the JWT token.
using System.Linq; using System.Web.Mvc; public class JwtAuthorizeAttribute : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { var request = filterContext.HttpContext.Request; var authHeader = request.Headers["Authorization"]; if (authHeader != null && authHeader.StartsWith("Bearer")) { var token = authHeader.Substring("Bearer ".Length).Trim(); var principal = JwtHelper.GetPrincipal(token); if (principal == null) { filterContext.Result = new HttpUnauthorizedResult("Invalid token"); return; } // Set the current principal System.Threading.Thread.CurrentPrincipal = principal; base.OnActionExecuting(filterContext); } else { filterContext.Result = new HttpUnauthorizedResult("Missing token"); } } }Step 5: Apply the JwtAuthorize Attribute
Apply the JwtAuthorize attribute to the actions or controllers you want to secure.
public class SecureController : Controller { [JwtAuthorize] public ActionResult SecureAction() { return Content("This is a secure action"); } }Step 6: Testing
Test your implementation by: