Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Generating and validating JWT tokens using JWTSecurityTokenHandler
[Fact]
public void First()
{
var tokenHandler = new JWTSecurityTokenHandler();
var symmetricKey = GetRandomBytes(256/8);
var now = DateTime.UtcNow;
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new Claim[]
{
new Claim(ClaimTypes.Name, "Pedro"),
new Claim(ClaimTypes.Role, "Author"),
}),
TokenIssuerName = "self",
AppliesToAddress = "http://www.example.com",
Lifetime = new Lifetime(now, now.AddMinutes(2)),
SigningCredentials = new SigningCredentials(
new InMemorySymmetricSecurityKey(symmetricKey),
"http://www.w3.org/2001/04/xmldsig-more#hmac-sha256",
"http://www.w3.org/2001/04/xmlenc#sha256"),
};
var token = tokenHandler.CreateToken(tokenDescriptor);
var tokenString = tokenHandler.WriteToken(token);
Console.WriteLine(tokenString);
var validationParameters = new TokenValidationParameters()
{
AllowedAudience = "http://www.example.com",
SigningToken = new BinarySecretSecurityToken(symmetricKey),
ValidIssuer = "self"
};
var principal = tokenHandler.ValidateToken(tokenString, validationParameters);
Assert.True(principal.Identities.First().Claims
.Any(c => c.Type == ClaimTypes.Name && c.Value == "Pedro"));
Assert.True(principal.Identities.First().Claims
.Any(c => c.Type == ClaimTypes.Role && c.Value == "Author"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.