2015-09-07 47 views
5

我试图实现JWT令牌但保持运行进入以下例外:IDX10640:不支持算法:'http://www.w3.org/2001/04/xmldsig-more#hmac-sha256'当试图将令牌写入紧凑的json字符串时。DNX核心5.0 JwtSecurityTokenHandler“IDX10640:算法不支持:'http://www.w3.org/2001/04/xmldsig-more#hmac-sha256''

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); 

解决此问题的任何想法?

更新1:

上述错误发生时用 “System.IdentityModel.Tokens.Jwt”: “5.0.0-beta7-208241120”

更新2:

更新代码

+0

我做遇到同样的问题。您是否使用'System.IdentityModel.Tokens.Jwt'库的'5.0.0-beta7-208241120'版本? –

+0

是的,很高兴听到我不是唯一一个...... – sboulema

+0

1)为什么要使用'System.Random'创建加密密钥? 2)128字节密钥没有意义。你想要128位密钥(16字节)吗? 256位/ 32字节也是一个理智的选择。 3)使用当地时间也很奇怪。 – CodesInChaos

回答

2

我们目前不支持对称密钥。希望很快得到。

2

支持将在RC2版本中发布。 与夜间的NuGet包测试从得到的一切需要http://myget.org/gallery/azureadwebstacknightly

只有轻微的代码更改工作

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); 

验证令牌可以用代码的下位

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);