Skip to content

Instantly share code, notes, and snippets.

@pmhsfelix
Created November 26, 2012 23:33
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save pmhsfelix/4151369 to your computer and use it in GitHub Desktop.
Save pmhsfelix/4151369 to your computer and use it in GitHub Desktop.
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"));
}
}
@385
Copy link

385 commented Oct 26, 2018

please do this: var symmetricKey = (byte[]) GetRandomBytes(256 / 8);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment