c#序列化JWT负载输出错误的数据



在验证JWT后,我需要将其有效负载作为JSON获取,并通过将其作为消息发送到另一个服务来对JSON输出本身执行一些后令牌验证处理,问题是scope字段的输出是不正确的。序列化库是Newtonsoft

它应该被序列化为"scope":["scope1","scope2"],但它的输出是"scope":[[],[]],我检查了令牌本身,它确实包含字符串值,并且具有正确的数据类型代码:

services.AddAuthentication(opt =>
{
opt.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
opt.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}
).AddJwtBearer(opt =>
{
var validationParams = TokenValidatorHandler.ValidationParameters();

//opt.Authority = "http://localhost";
opt.RequireHttpsMetadata = false;
opt.TokenValidationParameters = validationParams;
opt.SecurityTokenValidators.Clear(); // clear all existing token validators
opt.SecurityTokenValidators.Add(new JwtSecurityTokenHandler()); // add JwtSecurityTokenHandler as the only token validator

opt.Events = new JwtBearerEvents
{
OnTokenValidated = context =>
{
string token = ((JwtSecurityToken)context.SecurityToken).RawData;
TokenValidatorHandler.ParseToken(token);
return Task.CompletedTask;
}
};
});`

解析令牌:

public static void ParseToken(string token)
{
try
{

var tokenHandler = new JwtSecurityTokenHandler();

var validatedToken = tokenHandler.ReadJwtToken(token);

var payloadJSON = JsonConvert.SerializeObject(validatedToken.Payload);
// perform sending the token and other operations

}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.WriteLine(e.StackTrace);
}
}`

对于使用Microsoft.IdentityModel.Tokens的任何人,我已经解决了这个问题问题出在"作用域"内的数据类型。数组,不管什么原因,它没有被解析为字符串,而是其他数据类型,解决方案是手动将其转换为字符串数组:

//read the token using the tokenHandler 
var clms = validatedToken.Claims.Where(x => x.Type == "scope").ToList();
validatedToken.Payload["scope"] =  clms.Select(x => x.Value).ToArray();

修复了不正确的数据类型并输出预期的数组

最新更新