Skip to content

Instantly share code, notes, and snippets.

@cecchisandrone
Created December 12, 2019 16:37
Show Gist options
  • Save cecchisandrone/50a3ba272fb5d61657805bca5d5b378f to your computer and use it in GitHub Desktop.
Save cecchisandrone/50a3ba272fb5d61657805bca5d5b378f to your computer and use it in GitHub Desktop.
.NET JWT token generation
using Microsoft.IdentityModel.Tokens;
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string secret = "thisismyjwtsecret";
byte[] key = Encoding.UTF8.GetBytes(secret);
SymmetricSecurityKey securityKey = new SymmetricSecurityKey(key);
SecurityTokenDescriptor descriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new[] {
new Claim(ClaimTypes.Name, "pippo")}),
Expires = DateTime.UtcNow.AddMinutes(30),
SigningCredentials = new SigningCredentials(securityKey,
SecurityAlgorithms.HmacSha256Signature)
};
JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();
JwtSecurityToken token = handler.CreateJwtSecurityToken(descriptor);
string tokenString = handler.WriteToken(token);
Console.WriteLine(tokenString);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment