我像这样创建了JwtToken:
X509Certificate2 cert = certificateStore.Certificate;
var now = DateTime.UtcNow;
var tokenHandler = new JwtSecurityTokenHandler();
var tokenDescriptor = new SecurityTokenDescriptor()
{
Subject = new ClaimsIdentity(new[]
{
new Claim(JwtClaimTypes.Subject, upn),
new Claim(REQUEST_TYPE_NAME, requestType),
new Claim(DOMAIN_NAME, domain),
}),
Lifetime = new Lifetime(now, now.AddMinutes(60)),
SigningCredentials = new X509SigningCredentials(cert),
TokenIssuerName = ISSUER
};
SecurityToken token = tokenHandler.CreateToken(tokenDescriptor);
这是对的。令牌已创建,其第一个声明被命名为" sub"这是JwtTokenTypes.Subject的内容。我通过jwt web检查了它。
问题是,我有这种解决索赔的方法:
if (string.IsNullOrWhiteSpace(token)) throw new MissingTokenException("Token should not be null.");
var tokenHandler = new JwtSecurityTokenHandler();
var securityToken = new X509SecurityToken(new X509Certificate2(new X509RawDataKeyIdentifierClause(certificateStore.Certificate).GetX509RawData()));
var validationParameters = new TokenValidationParameters()
{
IssuerSigningToken = securityToken,
ValidateAudience = false,
ValidateActor = false,
ValidIssuer = ISSUER
};
SecurityToken securedToken = new JwtSecurityToken();
ClaimsPrincipal claimsPrincipal = tokenHandler.ValidateToken(token, validationParameters, out securedToken);
Claim claim = claimsPrincipal.FindFirst(m => string.Equals(m.Type, REQUEST_TYPE_NAME, StringComparison.OrdinalIgnoreCase));
if (claim != null && !string.Equals(claim.Value, requestType, StringComparison.OrdinalIgnoreCase))
{
throw new MismatchedTokenException("Token is not of the proper type.");
}
upn = claimsPrincipal.Claims.FirstOrDefault(m => m.Type.Equals(JwtClaimTypes.Subject) || m.Type.Equals(ClaimTypes.NameIdentifier))?.Value;
domain = claimsPrincipal.Claims.FirstOrDefault(m => m.Type.Equals(DOMAIN_NAME))?.Value;
在方法的最后,您可以看到我检查JwtClaimTypes.Subject的声明名称,它应该是,以及它实际上是ClaimTypes.NameIdentifiew。
您是否知道为何会发生这种转变或如何预防这些转变?
答案 0 :(得分:5)
您需要先添加:
JwtSecurityTokenHandler.InboundClaimTypeMap.Clear();
清除jwt索赔的映射。
完成映射以使jwt声明适应.net类型的声明。 如果要避免映射,则需要为名称和角色设置声明类型,如果要使用Identity(IPrincipal.IsInRole或Identity.Name)中的声明类型。
您可以在创建ClaimsIdentity时执行此操作:
Subject = new ClaimsIdentity(new[]
{
new Claim(JwtClaimTypes.Subject, upn),
new Claim(REQUEST_TYPE_NAME, requestType),
new Claim(DOMAIN_NAME, domain),
}, "<auth type>", "name", "role"),
您必须将authType更改为类似Cookie的内容,名称和角色声明名称很可能就是这样。
另一种方法是在令牌验证参数上设置它:
var validationParameters = new TokenValidationParameters()
{
IssuerSigningToken = securityToken,
ValidateAudience = false,
ValidateActor = false,
ValidIssuer = ISSUER,
NameClaimType = "name",
RoleClaimType = "role"
};