【问题标题】:Encoding JWT Token Using System.IdentityModel.Tokens.Jwt in ASP.NET 5在 ASP.NET 5 中使用 System.IdentityModel.Tokens.Jwt 编码 JWT 令牌
【发布时间】:2015-11-06 04:19:05
【问题描述】:

我有一个用例,我希望我的新应用程序(它是身份验证的来源)为旧应用程序提供 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)}");

如果我不签署令牌,一切正常。但是,只要我添加签名凭据,就会收到不支持 HMAC 的错误消息。我确实找到了另一个 SO 帖子,上面写着support for symmetric keys does not yet exist。但是,在我的搜索中,我看到了该库的广泛使用。特别是,我看到了InMemorySymmetricSecurityKey 的使用。但是,当我自己尝试使用它时,在任何命名空间中都找不到它,所以我有点困惑我从哪里开始。

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

【问题讨论】:

    标签: c# asp.net-core adal


    【解决方案1】:

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

    抱歉,麻烦您了。您可以添加自己的 SignatureProvider 或等待几周。

    【讨论】:

    • 感谢您的快速回复。我怀疑这样的事情,但想确认一下。我将暂时使用另一个实现,并在 RC2 之后回到这个。再次感谢!
    猜你喜欢
    • 2013-09-11
    • 2019-10-08
    • 1970-01-01
    • 1970-01-01
    • 2021-01-09
    • 2020-09-23
    • 2016-12-28
    • 2019-06-19
    • 2018-08-01
    相关资源
    最近更新 更多