Skip to content

Instantly share code, notes, and snippets.

@mehmetkurt
Last active January 16, 2024 17:57
Show Gist options
  • Save mehmetkurt/1a5ef36151a3f3263ede2813a0a680d3 to your computer and use it in GitHub Desktop.
Save mehmetkurt/1a5ef36151a3f3263ede2813a0a680d3 to your computer and use it in GitHub Desktop.
C# Create Jwt Token
using Microsoft.IdentityModel.Tokens;
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
namespace JwtTestConsoleApp
{
class Program
{
static void Main(string[] args)
{
var username = Console.ReadLine();
var password = Console.ReadLine();
Console.WriteLine("User name:{0}", username);
Console.WriteLine("Password:{0}", password);
if (ValidateUserNamePassword(username, password))
Console.WriteLine(GenerateToken(username));
}
public static string GenerateToken(string username)
{
var someClaims = new Claim[]{
new Claim(JwtRegisteredClaimNames.UniqueName,username),
new Claim(JwtRegisteredClaimNames.NameId,Guid.NewGuid().ToString())
};
SecurityKey securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("test test test test test"));
var token = new JwtSecurityToken(
issuer: "test.test.com",
audience: "test.test.com",
claims: someClaims,
expires: DateTime.Now.AddMinutes(3),
signingCredentials: new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256)
);
return new JwtSecurityTokenHandler().WriteToken(token);
}
private static bool ValidateUserNamePassword(string userName, string password)
{
return true;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment