Skip to content

使用Masa.Contrib.Authentication.Identity时用户Claim是集合时解析异常 #671

Open
@magiboys

Description

@magiboys

Description

我的jwt token由IdentityServer4生成的,
当用户角色只有一个时,数据是这样的
{
"sub": "0f974b04-e32b-0210-f57b-3a0e1510e1ec",
"role": "admin",
}
多个角色时是
{
"sub": "0f974b04-e32b-0210-f57b-3a0e1510e1ec",
"role": ["admin","test"],
}
但是现在Masa.Contrib.Authentication.Identity解析角色时报异常,
原因是在DefaultUserContext中
foreach (var property in userType.GetProperties())
{
var claimType = _optionsMonitor.CurrentValue.GetClaimType(property.Name);
if (claimType == null)
continue;

        var claimValue = ClaimsPrincipal?.FindClaimValue(claimType);//这里只取了第一个声明,并且是字符串
        if (claimValue != null)
        {
            modelRelation.Setters[property]
                .Invoke(userModel, new[] { TypeConvertProvider.ConvertTo(claimValue, property.PropertyType) });//执行到这时,因为是字符串,不能反序列化成string[]而报错
        }
    }

我只有让token生成为
{
"sub": "0f974b04-e32b-0210-f57b-3a0e1510e1ec",
"role": "["admin","test"]",
}
才能正常运行,
但我觉得这不符合jwt规范

Reproduction Steps

No response

Expected behavior

当token 单角色是
{
"sub": "0f974b04-e32b-0210-f57b-3a0e1510e1ec",
"role": "admin",
}
多个角色时是
{
"sub": "0f974b04-e32b-0210-f57b-3a0e1510e1ec",
"role": ["admin","test"],
}
能正确解析role

Actual behavior

No response

Known Workarounds

我现在只能自定义DefaultUserContext,并替换下面代码使程序正常运行
string? claimValue=null;
if (typeof(IEnumerable).IsAssignableFrom(property.PropertyType) && property.PropertyType != typeof(string))
{
var values = ClaimsPrincipal?.Claims.Where(p => p.Type == claimType).Select(p => p.Value);
if (values != null && values.Count() > 0)
{
claimValue=JsonSerializer.Serialize(values);
}
}
else
{
claimValue=ClaimsPrincipal?.FindClaimValue(claimType);
}

.NET version

6.0

MASA Framework version

1.0.1

Other information

No response

Metadata

Metadata

Labels

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions