JasCav
JasCav

Reputation: 34632

Encoding JWT Token Using System.IdentityModel.Tokens.Jwt in ASP.NET 5

I have a use case where I want my new application (which is the source of authentication) to provide a JWT to legacy applications.

I am attempting to use the package, System.IdentityModel.Tokens.Jwt 5.0.0-beta7 (and I could easily move to beta8 if necessary). Creating the token was simple, but I am having issues properly signing it. Here is my current code:

Claim[] claims = {
    new Claim(ClaimTypes.Email, "[email protected]"),
    new Claim(ClaimTypes.Role, "admin"),
    new Claim(ClaimTypes.Uri, ""),
    new Claim(ClaimTypes.Expiration, DateTime.UtcNow.Add(TimeSpan.FromDays(1)).ToString()),
    new Claim("personId", personId.ToString())
};

var key = Convert.FromBase64String("my super secret key goes here");
var signingCredentials = new SigningCredentials(
    new SymmetricSecurityKey(key),
    SecurityAlgorithms.HMAC_SHA256,
    SecurityAlgorithms.Sha256Digest
);
var jwt = new JwtSecurityToken("localhost", "all", claims, 
    DateTime.UtcNow, DateTime.UtcNow.AddDays(1), signingCredentials);            

var handler = new JwtSecurityTokenHandler();
handler.WriteToken(jwt);

return Content($"{handler.WriteToken(jwt)}");

If I do not sign the token, everything works correctly. However, as soon as I add signing credentials, I receive an error that HMAC is not supported. I did find another SO post that says support for symmetric keys does not yet exist. However, in my search, I see extensive use of the library. In particular, I see the use of InMemorySymmetricSecurityKey. However, when I try to use it myself, it can't be found in any namespace, so I am a bit confused as where I go from here.

This is a long-winded explanation to basically ask - how do I properly sign the JWT with a simple secret?

Upvotes: 6

Views: 3795

Answers (1)

Brent Schmaltz
Brent Schmaltz

Reputation: 1161

When we moved to the new versions of CoreClr, we had to temporarily drop support for HMAC. We choose to add support for ECDSA in RC1 and plan on adding HMAC back in RC2.

Sorry for the hassle. You could add your own SignatureProvider OR wait a couple of weeks.

Upvotes: 3

Related Questions