'JwtSecurityToken understanding and exception
I'm fairly new to JwtSecurityTokens, and I try to understand the different aspects of it and furhtermore the whole claimsidentity and claimprincipal, but that's another story.
I try to generate a token in C# by using the following code:
private const string SECRET_KEY = "abcdef";
private static readonly SymmetricSecurityKey SIGNING_KEY = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(SECRET_KEY));
public static string GenerateToken(string someName)
{
var token = new JwtSecurityToken(
claims: new Claim[]
{
new Claim(ClaimTypes.Name, someName),
},
notBefore: new DateTimeOffset(DateTime.Now).DateTime,
expires: new DateTimeOffset(DateTime.Now.AddMinutes(60)).DateTime,
signingCredentials: new SigningCredentials(SIGNING_KEY, SecurityAlgorithms.HmacSha256)
);
return new JwtSecurityTokenHandler().WriteToken(token);
}
I followed a tutorial on Youtube, but I'm not sure I understand the different parts in the JwtSecurityToken. In addition, when I execute the code through a controller just to try to return a token, it returns an error, saying: "IDX10603: Decryption failed. Keys tried: '[PII is hidden]'".
Any help is appreciated.
Solution 1:[1]
The algorithm HS256 requires the SecurityKey.KeySize to be greater than 128 bits and your key has just 48. Extend it by adding at least 10 more symbols.
As for "PII is hidden" part, it was done as a part of GDPR compliance effort to hide any stack or variable info in logs. You should enable additional details with:
IdentityModelEventSource.ShowPII = true;
Solution 2:[2]
You should add enough characters to your secret key, when you set your secret key here,
//your SECRET_KEY = "abcdef"
new SymmetricSecurityKey(Encoding.UTF8.GetBytes(SECRET_KEY));
change it to
new SymmetricSecurityKey(Encoding.UTF8.GetBytes("somethingyouwantwhichissecurewillworkk"));
this should work.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |
