Created
December 12, 2019 16:37
-
-
Save cecchisandrone/50a3ba272fb5d61657805bca5d5b378f to your computer and use it in GitHub Desktop.
.NET JWT token generation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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