Rui Taborda Rui Taborda - 8 months ago 62
C# Question

dnx451 RC1 What happened to InMemorySymmetricSecurityKey?

I've been trying to create and sign a JwtSecurityToken using a simple key. And after a lot of research it seems that all the examples I find use the InMemorySymmetricSecurityKey class but unfortunately this class doesn't seem to exist in the newest versions of the System.IdentityModel libraries.

These are the dependencies I'm using:

"System.IdentityModel.Tokens": "5.0.0-rc1-211161024",
"System.IdentityModel.Tokens.Jwt": "5.0.0-rc1-211161024"

I also tried using it's base class SymmetricSecurityKey but then I get the following exception when trying to create the token:

"Value cannot be null.\r\nParameter name: IDX10000: The parameter 'signatureProvider' cannot be a 'null' or an empty object."

This is the code that throws the exception:

public static string CreateTokenHMAC()
HMACSHA256 hmac = new HMACSHA256(Convert.FromBase64String("test"));

var key = new SymmetricSecurityKey(hmac.Key);

var signingCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256Signature);

JwtSecurityToken token = _tokenHandler.CreateJwtSecurityToken(new SecurityTokenDescriptor()
Audience = AUDIENCE,
Issuer = ISSUER,
Expires = DateTime.UtcNow.AddHours(6),
NotBefore = DateTime.Now,
Claims = new List<Claim>()
new Claim(ClaimTypes.Email, "")
SigningCredentials = signingCredentials

return _tokenHandler.WriteToken(token);

It's the first time I'm using JwtSecurityToken so my guess is that I'm probably missing a step somewhere


I managed to reach the exact same exception. I worked around the problem by generating the key another way:

RSAParameters keyParams;
using (var rsa = new RSACryptoServiceProvider(2048))
        keyParams = rsa.ExportParameters(true);
        rsa.PersistKeyInCsp = false;
RsaSecurityKey key = new RsaSecurityKey(keyParams);
var signingCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256Signature);

Here is a great post about token-based authentication on ASP.NET 5 RC1 by Mark Hughes