.net C#序列化JWT有效负载输出不正确的数据

up9lanfz  于 2023-04-08  发布在  .NET
关注(0)|答案(1)|浏览(134)

在验证JWT后,我需要将其有效负载作为JSON获取,并通过将其作为消息发送到另一个服务来对JSON输出本身执行一些后令牌验证处理。问题是scope字段的输出不正确。序列化库是Newtonsoft
它应该被序列化为"scope":["scope1","scope2"],但它的输出是"scope":[[],[]],我检查了令牌本身,它确实包含字符串值,并且具有正确的数据类型Code:

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);
    }
}`
vyswwuz2

vyswwuz21#

我已经解决了这个问题,对于任何使用Microsoft.IdentityModel.Tokens的人来说,问题在于“scope”数组中的数据类型,无论出于何种原因,它都没有被解析为字符串,而是其他一些数据类型,解决方案是手动将其转换为字符串数组:

//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();

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

相关问题