After some research it looks like for security and maybe other reasons Microsoft's libraries incapsulate for as a lot of details that potential user (who is not always a security expert) wouldn't cause himself/herself a harm.
With that said, take this as an example the following straight forward code snippets of
1. issuing an access token
2. reading the claims from it
1. Issuing an access token.
Note that I use here Microsoft.IdentityModel.JsonWebTokens.JwtRegisteredClaimNames
class with it's constants. Eventually it will be converted to
"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress"
standard, doesn't matter if you hardcode "email"
or use JwtRegisteredClaimNames.Email
as a claim type.
string GenerateJWTAccessToken()
{
var claims = new[]
{
new Claim(Microsoft.IdentityModel.JsonWebTokens.JwtRegisteredClaimNames.Sub, userName),
new Claim(Microsoft.IdentityModel.JsonWebTokens.JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new Claim(Microsoft.IdentityModel.JsonWebTokens.JwtRegisteredClaimNames.Email, userEmail),
new Claim(Microsoft.IdentityModel.JsonWebTokens.JwtRegisteredClaimNames.Exp, DateTime.UtcNow.AddMinutes(_jwt.AccessTokenLifeTime_Minutes).ToString())
};
var key = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes("YOUR_KEY"));
var cred = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
issuer: "YOUR_ISSUER",
audience: "YOUR_AUDIENCE",
claims: claims,
expires: DateTime.UtcNow.AddMinutes(15),
signingCredentials: cred
);
return new JwtSecurityTokenHandler().WriteToken(token);
}
Shortcut to get what you need. Consider following example with JwtRegisteredClaimNames.Email claim.
2. Reading the claims
Reading previously issued JWT token and getting info from the Payload (the claims).
var principals = new JwtSecurityTokenHandler()
.ValidateToken
(
accessToken, // paste here JWT token
new TokenValidationParameters
{
ValidIssuer = "YOUR_ISSUER",
ValidAudience = "YOUR_AUDIENCE",
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("YOUR_KEY")),
ValidateLifetime = false
}, out _
);
// Here straight forward way to get the value form the claim
var emailClaimValue = principals.Claims.FirstOrDefault(x => x.Properties.FirstOrDefault().Value == "email").Value; // please handle probable exceptions
Done. So we got the value needed.
Please fill free to alter and handle potential exceptions, here I just quickly briefly share my research results, not going to much into details.
If something new I will come up with updates.
Thanks.