Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
magiboys opened this issue Oct 7, 2023 · 0 comments
Assignees
Labels
Milestone

Comments

@magiboys
Copy link

magiboys commented Oct 7, 2023

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

@magiboys magiboys changed the title 使用Masa.Contrib.Authentication.Identity是用户Claim是集合时解析异常 使用Masa.Contrib.Authentication.Identity时用户Claim是集合时解析异常 Oct 7, 2023
@MayueCif MayueCif self-assigned this Oct 12, 2023
@duiapro duiapro self-assigned this Apr 3, 2024
@duiapro duiapro added this to the 1.2.0 milestone Apr 3, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

5 participants