In implementing JWT in a personal application I see that there are two different ways of creating a token to return a string of JWT. My question is why are there two different ways of implementing and what are the benefits of implementing one over the other?
Technology .NET 8
private string GenerateToken(List<Claim> claims)
{
var authSigninKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JwtSettings:Key"]));
var tokenDescription = new SecurityTokenDescriptor
{
Issuer = _configuration["JwtSettings:Issuer"],
Audience = _configuration["JwtSettings:Audience"],
Expires = DateTime.UtcNow.AddMinutes(1),
SigningCredentials = new SigningCredentials(authSigninKey, SecurityAlgorithms.HmacSha256),
Subject = new ClaimsIdentity(claims)
};
var tokenHandler = new JwtSecurityTokenHandler();
var token = tokenHandler.CreateToken(tokenDescription);
return tokenHandler.WriteToken(token);
}
private string GenerateToken(List<Claim> claims)
{
var authSigninKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JwtSettings:Key"]));
var signingCred = new SigningCredentials(authSigninKey, SecurityAlgorithms.HmacSha256Signature);
var security = new JwtSecurityToken(
claims: claims,
expires: DateTime.UtcNow.AddMinutes(1),
signingCredentials: signingCred
);
string tokenString = new JwtSecurityTokenHandler().WriteToken(security);
return tokenString;
}
Example1: claims etc. -> tokenDescriptor -> security token -> token string
Example2: claims etc. -> security token -> token string
So it seems example2 is more simple. But token descriptor is designed to use more friendly. For example, security token is read only which means you couldn't change after it is created. But descriptor would allows you to modify properties.
//This is allowed
tokenDescription.Subject = new ClaimsIdentity(claims);
//security token is read only. This is not allowed
security.Claims= new ClaimsIdentity(claims);