Simple JWT Token Example in C#
Understanding JWT Tokens
JWTs are composed of three parts: the header, payload, and signature. The header typically consists of the token type (JWT) and the hashing algorithm (e.g., HMAC SHA256). The payload contains the claims, which can be information about the user and additional metadata. The signature ensures that the token has not been tampered with.
Setting Up Your C# Project
Before diving into the code, ensure you have a .NET project set up. If you're using Visual Studio, you can create a new console application or a web API project.
Install Necessary Packages
Use NuGet Package Manager to install the
System.IdentityModel.Tokens.Jwt
package, which simplifies working with JWT in .NET.bashInstall-Package System.IdentityModel.Tokens.Jwt
Creating JWT Tokens
Here's a simple example of generating a JWT token in C#:
csharpusing System; using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; using Microsoft.IdentityModel.Tokens; public class JwtTokenGenerator { private const string SecretKey = "your-256-bit-secret"; // You should use a secure key in production private static readonly SymmetricSecurityKey SigninKey = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(SecretKey)); public static string GenerateToken(string username) { var tokenHandler = new JwtSecurityTokenHandler(); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, username) }), Expires = DateTime.UtcNow.AddHours(1), SigningCredentials = new SigningCredentials(SigninKey, SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); return tokenHandler.WriteToken(token); } }
In this code snippet,
GenerateToken
creates a JWT with a username claim and a 1-hour expiration. TheSigningCredentials
are used to sign the token using HMAC SHA256.Validating JWT Tokens
Validating JWTs is crucial for ensuring their authenticity and integrity. Here’s an example of how to validate a JWT:
csharppublic class JwtTokenValidator { private const string SecretKey = "your-256-bit-secret"; // Same key used for signing public static bool ValidateToken(string token) { var tokenHandler = new JwtSecurityTokenHandler(); var validationParameters = new TokenValidationParameters { ValidateIssuer = false, ValidateAudience = false, ValidateLifetime = true, IssuerSigningKey = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(SecretKey)), ValidateIssuerSigningKey = true }; try { var principal = tokenHandler.ValidateToken(token, validationParameters, out SecurityToken validatedToken); return validatedToken != null; } catch { // Token validation failed return false; } } }
The
ValidateToken
method checks the validity of the JWT using the same secret key. It ensures the token’s expiration and signing integrity.
Putting It All Together
Integrate these classes into your application to secure endpoints. For example, in an ASP.NET Core web API, you might use middleware to check the validity of JWTs in HTTP requests.
Conclusion
This example provides a foundational understanding of working with JWTs in C#. By creating and validating tokens, you can ensure secure communication between your server and clients. Remember, the key to successful JWT implementation is a secure secret key and proper validation.
Top Comments
No Comments Yet