Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DNX Core 5.0 JwtSecurityTokenHandler "IDX10640: Algorithm is not supported: 'http://www.w3.org/2001/04/xmldsig-more#hmac-sha256'"

Tags:

json

c#

jwt

adal

I'm trying to implement JWT tokens but keep running into the following exception: IDX10640: Algorithm is not supported: 'http://www.w3.org/2001/04/xmldsig-more#hmac-sha256' when trying to write the token to compact json string.

const string issuer = "issuer";
const string audience = "audience";
byte[] keyForHmacSha256 = new byte[32];
new Random().NextBytes(keyForHmacSha256);

var claims = new List<Claim> { new Claim("deviceId", "12") };
var now = DateTime.UtcNow;
var expires = now.AddHours(1);
var signingCredentials = new SigningCredentials(
    new SymmetricSecurityKey(keyForHmacSha256), 
    SecurityAlgorithms.HmacSha256Signature, SecurityAlgorithms.Sha256Digest);

var token = new JwtSecurityToken(issuer, audience, claims, now, expires, signingCredentials);
return _tokenHandler.WriteToken(token);

Any ideas on solving this?

Update 1:

The error above occurs with "System.IdentityModel.Tokens.Jwt": "5.0.0-beta7-208241120"

Update 2:

Updated code

like image 658
sboulema Avatar asked Sep 07 '15 12:09

sboulema


2 Answers

Support will be in the RC2 release. Tested with the nightly nuget packages from http://myget.org/gallery/azureadwebstacknightly

Only slight code changes needed to get everything to work

const string issuer = "issuer";
const string audience = "audience";
var keyForHmacSha256 = Encoding.ASCII.GetBytes("<tokenSecret>");
var key = new SymmetricSecurityKey(keyForHmacSha256);
var claims = new List<Claim> { new Claim("deviceId", "12") };
var now = DateTime.UtcNow;
var expires = now.AddHours(1);
var signingCredentials = new SigningCredentials(key, SecurityAlgorithms.HMAC_SHA256);

var token = new JwtSecurityToken(issuer, audience, claims, now, expires, signingCredentials);
return _tokenHandler.WriteToken(token);

Validating the token can be done with the next bit of code

SecurityToken securityToken;
var validationParameters = new TokenValidationParameters
{
    ValidateLifetime = true,
    ValidateAudience = true,
    ValidateIssuer = true,
    RequireExpirationTime = true,
    ValidateSignature = true,
    ValidAudience = audience,
    ValidIssuer = issuer,
    IssuerSigningKey = key,
    RequireSignedTokens = true,
    ValidateIssuerSigningKey = true               
};

tokenHandler.ValidateToken(token, validationParameters, out securityToken);
like image 83
sboulema Avatar answered Nov 17 '22 19:11

sboulema


We don't have support for symmetric keys right now. Hope to get that in soon.

like image 33
Brent Schmaltz Avatar answered Nov 17 '22 18:11

Brent Schmaltz