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
- Login: User logs in with username/password.
- Token Issued: Server validates credentials and returns a JWT.
- Client Stores Token: Usually in local storage or a cookie.
- Subsequent Requests: The client sends the JWT in the
Authorization
header:Authorization: Bearer <token>
- Server Verifies: Server checks the signature and payload to authorize the request.
- Header: Contains metadata, usually the token type (
JWT
) and signing algorithm (e.g.,HS256
). - Payload: Contains the actual data (claims), like user ID, roles, or expiration time.
- Signature: Used to verify that the token hasn't been tampered with. It's created using the header, payload, and a secret key.
{
"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