【问题标题】:Custom Claim with Boolean type布尔类型的自定义声明
【发布时间】:2017-06-21 13:38:13
【问题描述】:

我正在使用 Visual Studio 2015 创建一个 ASP.NET MVC 5 应用程序。我正在使用身份框架在身份验证后向用户添加声明。基于内置 ClaimTypes 添加声明很容易,但我在添加布尔的自定义声明时遇到了挑战。

我创建了这个静态类来保存我的自定义声明类型:

public static class CustomClaimTypes
{
    public static readonly string IsEmployee = "http://example.com/claims/isemployee";
}

然后我尝试向ClaimsIdentity 对象添加自定义声明:

userIdentity.AddClaim(new Claim(CustomClaimTypes.IsEmployee, isEmployee));

它在上面一行给出了这个错误:

无法从 'bool?' 转换到“System.Security.Claims.ClaimsIdentity”

我发现的所有示例都是添加字符串。如何添加 bool、int 或其他类型?谢谢。

【问题讨论】:

    标签: c# asp.net


    【解决方案1】:

    您也可以将 valueType 作为第三个参数传递。

    userIdentity.AddClaim(
        new Claim(CustomClaimTypes.IsEmployee, 
        isEmployee.ToString(), 
        ClaimValueTypes.Boolean));
    

    所以在前端你会得到布尔类型的值而不是字符串。

    【讨论】:

      【解决方案2】:

      声明只能表示为字符串。任何数字、布尔值、guid 等在添加到声明集合时都必须是字符串。所以ToString()它。

      userIdentity.AddClaim(
          new Claim(CustomClaimTypes.IsEmployee, 
          isEmployee.GetValueOrDefault(false).ToString()));
      

      【讨论】:

      • 谢谢,@艾米。是否可以在自定义声明中存储复杂对象?一直在看这篇文章:docs.microsoft.com/en-us/dotnet/framework/wcf/extending/…
      • 您必须将它们序列化为字符串。
      • 如果我在解码有效载荷时想要 "myType": true 而不是 "myType":"true" 怎么办?因为如果我使用 ToString() 我将收到第二个选项。
      • @BlackShawarna 任何数字、布尔值、guid 等在添加到声明集合时都必须是字符串。必须是字符串。
      • 是的,我同意你的看法,没有其他选择。要有 "myToken": false 使用 ClaimValueTypes.Boolean 否则你将有 "myToken": "false" 作为字符串格式。
      【解决方案3】:

      要在响应中得到你想要的正确类型,你需要重载TokenEndpointResponse

      public override Task TokenEndpointResponse(OAuthTokenEndpointResponseContext context)
              {
                  foreach (var item in context.Identity.Claims)
                  {
                      object value;
      
                      if (item.ValueType.Contains("boolean"))
                          value = bool.Parse(item.Value);
                      else
                          value = item.Value;
      
                      context.AdditionalResponseParameters.Add(item.Type, value);
                  }
      
                  return base.TokenEndpointResponse(context);
              }
      

      当然是在指定前面的答案中提到的ClaimValueTypes之后,否则它会将所有字段识别为字符串类型。

      【讨论】:

        猜你喜欢
        • 2012-01-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-09-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多