【发布时间】:2016-03-08 01:58:05
【问题描述】:
我正在开始一项新任务,我必须处理来自 JWT 的指纹。我们为 Microsoft .Net 框架使用 JSON Web 令牌处理程序。已经有一个在测试中使用的实现,它生成 JWT,而在标头中没有 x5t 文件。它看起来像这样:
var handler = new JwtSecurityTokenHandler();
var securityKey = new InMemorySymmetricSecurityKey(Any.Array<byte>(1024));
var desc = new SecurityTokenDescriptor
{
TokenIssuerName = "MSI",
Lifetime = new Lifetime(null, DateTime.UtcNow.AddDays(10)),
SigningCredentials = new SigningCredentials(securityKey, "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256", "http://www.w3.org/2001/04/xmlenc#sha256"),
};
var identity = new ClaimsIdentity();
identity.AddClaim(new Claim("scope", "msi_unsapi_presence.watch"));
identity.AddClaim(new Claim("scope", "msi_unsapi_location.watch"));
identity.AddClaim(new Claim("scope", "msi_unsapi_groupmgt.read"));
identity.AddClaim(new Claim("scope", "msi_unsapi_groupmgt.write"));
var jwtToken = handler.CreateToken(desc);
return jwtToken;
它产生的令牌:{"typ":"JWT","alg":"HS256"}.{"scope":["msi_unsapi_presence.watch","msi_unsapi_location.watch","msi_unsapi_groupmgt.read","msi_unsapi_groupmgt.write"]} 我尝试将 SecurityTokenDescriptor 的 AttachedReference 属性设置为以下AttachedReference = new X509ThumbprintKeyIdentifierClause(Any.Array<byte>(1024)) 以在令牌中填充 x5t 字段(我不关心确切的值,我只需要它出于测试目的存在于令牌中)但生成的令牌仍然没有设置此字段。如何在标头中生成非空 x5t 的令牌,最好修改现有代码?
【问题讨论】:
-
我不熟悉您的 JwtSecurityTokenHandler 类,但我在实现中所做的是创建自己的 jsonWebTokenFormat 来实现 ISecureDataFormat
(实现保护/取消保护方法),诀窍在于您需要调用 JwtPayload() 类,它是 Dictionary () 的超类,因此您可以将 x5t 字段添加到您想要的任何值,只要它是 json 格式。那么您将需要配置您的 JwtSecurityTokenHandler 以使用您的新 JwtFormat 然后继续您的身份和声明。 -
我无法修改 JwtSecurityTokenHandler 类,因为它是一个库类 (nuget.org/packages/System.IdentityModel.Tokens.Jwt) 而且我真的找不到可以根据需要配置它的方式。
-
好的,我很快就会向您展示一个实现。