-
-
Save RobinHerbots/5eda12d1921c9c8bcd7737aec327ec9a to your computer and use it in GitHub Desktop.
Generating and validating JWT tokens using JWTSecurityTokenHandler
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
[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