使用ASP.NET 5中的System.IdentityModel.Tokens.Jwt编码JWT令牌

Jas*_*Cav 6 c# adal asp.net-core

我有一个用例,我希望我的新应用程序(它是身份验证的来源)为遗留应用程序提供JWT.

我正在尝试使用该包,System.IdentityModel.Tokens.Jwt 5.0.0-beta7(beta8如果有必要,我可以轻松移动).创建令牌很简单,但我在签名时遇到问题.这是我目前的代码:

Claim[] claims = {
    new Claim(ClaimTypes.Email, "test@example.net"),
    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)}");
Run Code Online (Sandbox Code Playgroud)

如果我没有签署令牌,一切正常.但是,只要我添加签名凭据,就会收到不支持HMAC的错误.我确实发现另一个SO帖子说支持对称密钥尚不存在.但是,在我的搜索中,我看到了图书馆的广泛使用.特别是,我看到了使用InMemorySymmetricSecurityKey.但是,当我尝试自己使用它时,它无法在任何命名空间中找到,所以我有点困惑,因为我从这里开始.

这是一个冗长的解释基本上要问 - 我如何用一个简单的秘密正确签署JWT?

Bre*_*ltz 3

当我们迁移到新版本的 CoreClr 时,我们不得不暂时放弃对 HMAC 的支持。我们选择在 RC1 中添加对 ECDSA 的支持,并计划在 RC2 中重新添加 HMAC。

抱歉给您带来麻烦。您可以添加自己的 SignatureProvider 或等待几周。