Hi Friends,
Getting errors at Jwt Builder and HMACSHA256Algorithm does not exist.I tried to install JWT through nuget and package console in our .net core 2.1 project but not installing.
string apiKey = "32a4ef";
string secretKey = "qloDZF";
int currtime = 163068;
var payload = new Dictionary
{
{ "iss", apiKey },
{ "iat", currtime },
{ "jti", Guid.NewGuid().ToString() }
};
try
{
string token = new JwtBuilder()
.WithAlgorithm(new HMACSHA256Algorithm()) // symmetric
.WithSecret(secretKey)
.AddClaims(payload)
.Build();
Console.WriteLine(token);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Is there any other way to get the token similar to this code.

Jithu ThomasRank #437 · 5.7K reputationPosted Feb 10, 2024, 3:09 AM EST
It seems like you're trying to use JWT (JSON Web Token) in a .NET Core 2.1 project, and you're facing issues with the JwtBuilder and HMACSHA256Algorithm. The error you're encountering could be due to the absence of required packages or changes in the library structure.
In more recent versions of .NET Core, the JWT library has undergone some changes, and you may need to use a different library. Here's an example using the
System.IdentityModel.Tokens.Jwtnamespace, which is commonly used for JWT in .NET Core:Firstly, you need to install the necessary NuGet package. Open your Package Manager Console and run:
Now, you can create a JWT token using the following code:
using System; using System.Collections.Generic; using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; using Microsoft.IdentityModel.Tokens; class Program { static void Main() { string apiKey = "32a4ef"; string secretKey = "qloDZF"; int currtime = 163068; var claims = new List { new Claim("iss", apiKey), new Claim("iat", currtime.ToString()), new Claim("jti", Guid.NewGuid().ToString()) }; var key = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(secretKey)); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var token = new JwtSecurityToken( claims: claims, expires: DateTime.Now.AddMinutes(30), // Set expiration as needed signingCredentials: creds ); var tokenHandler = new JwtSecurityTokenHandler(); var tokenString = tokenHandler.WriteToken(token); Console.WriteLine(tokenString); } }In this example, we use
System.IdentityModel.Tokens.Jwtto create the JWT token. Ensure that you have the correct version of the library installed. If you encounter issues with missing packages, check the version compatibility.Note: Always use the latest library versions when possible, as there might be security updates and improvements in newer releases.