Generate Jason Web Token (JWT) In C#

JSON Web Tokens (JWT) are a compact, URL-safe means of representing claims to be transferred between two parties. They're commonly used for authentication and authorization in web applications and APIs.

In this pot, you'll learn how to generate a JWT in C# using the popular System.IdentityModel.Tokens.Jwt package.

Generate Jason Web Token (JWT) In C#

Getting Started

A JSON Web Token (JWT) is a compact, URL-safe way of representing claims or data between two parties. It's often used for authentication and authorization in web applications.

How JWT Works in Authentication

  1. Login: User logs in with username/password.
  2. Token Issued: Server validates credentials and returns a JWT.
  3. Client Stores Token: Usually in local storage or a cookie.
  4. Subsequent Requests: The client sends the JWT in the Authorization header:
    Authorization: Bearer <token>
  5. Server Verifies: Server checks the signature and payload to authorize the request.

A JWT has three parts, separated by dots(.0) and Each part is:
  1. Header: Contains metadata, usually the token type (JWT) and signing algorithm (e.g., HS256).
  2. Payload: Contains the actual data (claims), like user ID, roles, or expiration time.
  3. Signature: Used to verify that the token hasn't been tampered with. It's created using the header, payload, and a secret key.

Example of JWT Header
{  
  "alg": "HS256",  
  "typ": "JWT"  
 }  

Example of JWT Payload
{  
  "sub": "1234567890",  
  "name": "Kailash's Blogs",  
  "iat": 1620000000,  
  "exp": 1620003600  
 }  

Prerequisites

To generate a JWT Token make sure you have the following:
  • .NET SDK (6.0 or later recommended)
  • A C# project (e.g., ASP.NET Core Web API or Console App)
  • NuGet package:
     dotnet add package System.IdentityModel.Tokens.Jwt  
    

Generate JWT Token (JWT)

Here’s a simple example to create a JWT token in C#.
Required Namespaces
 using System;  
 using System.IdentityModel.Tokens.Jwt;  
 using System.Security.Claims;  
 using System.Text;  
 using Microsoft.IdentityModel.Tokens;  

JWT Generator Class
public class JwtTokenGenerator  
 {  
   private const string SecretKey = "your-256-bit-secret"; // Use a secure key in production  
   private const string Issuer = "your-app";  
   private const string Audience = "your-audience";  
   public static string GenerateJWTToken(string username)  
   {  
     int expireMinutes = 20;
     var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(SecretKey));  
     var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);  
     var claims = new[]  
     {  
       new Claim(JwtRegisteredClaimNames.Sub, username),  
       new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),  
       new Claim(JwtRegisteredClaimNames.Iat, DateTime.UtcNow.ToString())  
     };  
     var token = new JwtSecurityToken(  
       issuer: Issuer,  
       audience: Audience,  
       claims: claims,  
       expires: DateTime.UtcNow.AddMinutes(expireMinutes),  
       signingCredentials: credentials  
     );  
     return new JwtSecurityTokenHandler().WriteToken(token);  
   }  
 }  

Usage Example of JWT Token
 class Program  
 {  
   static void Main()  
   {  
     var token = JwtTokenGenerator.GenerateToken("Kailashs.blogs");  
     Console.WriteLine("Generated JWT:\n" + token);  
   }  
 }  

Summary

If you're building a secure API or working with authentication flows, JWT is a modern and scalable solution to consider., generating JWTs in C# is straightforward with the right tools. You can securely generate, sign, and use tokens for user authentication in your application with namespace System.IdentityModel.Tokens.Jwt.

Thanks

Kailash Chandra Behera

An IT professional with over 13 years of experience in the full software development life cycle for Windows, services, and web-based applications using Microsoft .NET technologies. Demonstrated expertise in delivering all phases of project development—from initiation to closure—while aligning with business objectives to drive process improvements, competitive advantage, and measurable bottom-line gains. Proven ability to work independently and manage multiple projects successfully. Committed to the efficient and effective development of projects in fast-paced, deadline-driven environments. Skills: Proficient in designing and developing applications using various Microsoft technologies. Total IT Experience: 13+ years

Previous Post Next Post

نموذج الاتصال