JWT Tokens in C# (.NET): Complete Guide with Examples

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

JWT Tokens in C# (.NET): Creation, Verification, and Validation



JSON Web Token (JWT) is an open standard (RFC 7519) for creating access tokens based on the JSON format. JWT is widely used in modern web applications for authentication and information exchange between client and server. In this article, we will take a detailed look at how to work with JWT tokens in the C# (.NET) ecosystem, including token creation, signing, verification, and validation.



Basic Components of JWT



JWT consists of three parts separated by dots:

  • Header — contains information about the token type and signing algorithm
  • Payload — contains data (claims)
  • Signature — ensures token integrity


Example of a JWT token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c



Installing Required Packages



To work with JWT in .NET, you need to install the System.IdentityModel.Tokens.Jwt package. This can be done via NuGet Package Manager or using .NET CLI:



dotnet add package System.IdentityModel.Tokens.Jwt


You may also need to install Microsoft.AspNetCore.Authentication.JwtBearer for integration with ASP.NET Core:



dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer


Creating a JWT Token in C#



Let's look at a complete example of creating a JWT token using a symmetric key (HMAC SHA256):



using System;using System.IdentityModel.Tokens.Jwt;using System.Security.Claims;using System.Text;using Microsoft.IdentityModel.Tokens;

public class JwtService{ private readonly string _secretKey; private readonly string _issuer; private readonly string _audience;

public JwtService(string secretKey, string issuer, string audience) { _secretKey = secretKey; _issuer = issuer; _audience = audience; }

public string GenerateToken(string userId, string userName, string role) { var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_secretKey)); var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

var claims = new[] { new Claim(ClaimTypes.NameIdentifier, userId), new Claim(ClaimTypes.Name, userName), new Claim(ClaimTypes.Role, role), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), new Claim(JwtRegisteredClaimNames.Iat, new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds().ToString()) };

var token = new JwtSecurityToken( issuer: _issuer, audience: _audience, claims: claims, expires: DateTime.UtcNow.AddHours(1), signingCredentials: credentials );

return new JwtSecurityTokenHandler().WriteToken(token); }}


Verifying and Validating a JWT Token



To verify authenticity and extract data from the token, use the ValidateToken method:



public ClaimsPrincipal ValidateToken(string token){    var tokenHandler = new JwtSecurityTokenHandler();    var key = Encoding.UTF8.GetBytes(_secretKey);

try { var principal = tokenHandler.ValidateToken(token, new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(key), ValidateIssuer = true, ValidIssuer = _issuer, ValidateAudience = true, ValidAudience = _audience, ValidateLifetime = true, ClockSkew = TimeSpan.Zero\

Recommendations