【问题标题】:Check Owin based claim on MVC5检查基于 MVC5 的 Owin 声明
【发布时间】:2015-09-22 22:32:02
【问题描述】:

我的User.IsInRole("CanChangeData") 不起作用,但我可以在调试菜单中看到值CanChangeData 在用户的声明列表中。

如果用户无法更改布局中的数据,我想删除菜单,if 返回 false。 Request.IsAuthenticated 返回真。

这就是我在 AuthenticationController 上向用户添加声明的方式

var identity = new ClaimsIdentity(new[] {
                        new Claim(ClaimTypes.Name, input.Username),
                    },
                    DefaultAuthenticationTypes.ApplicationCookie,
                    ClaimTypes.Name, ClaimTypes.Role); 

var employe = db.Employes.Single(k => k.User == input.Username);

foreach (var permission in employe.Role.Permissions)
{
    identity.AddClaim(new Claim(ClaimTypes.Role, permission.Nom));
}

为什么User.IsInRole("CanChangeData") 没有收到索赔?

【问题讨论】:

  • 角色不是声明。角色在 AspNetRoles 中定义,用户绑定在 AspNetUserRoles 中定义。索赔是不同的。试试User.HasClaim()

标签: c# asp.net-mvc owin


【解决方案1】:

当您使用声明时,以此为例,您可以这样添加声明:

identity.AddClaim(new Claim("ThisIsTheClaimID", "This is the value"));

那么你可以使用下面的代码来检索它:

var myClaimValue = User.FindFirst("ThisIsTheClaimID").Value

希望这有帮助吗?

【讨论】:

  • User.FindFirst("ThisIsTheClaimID").Value 可能会抛出 NullRefference 异常
  • 没有适当的结构也可以。
【解决方案2】:

您可以像下面的代码一样获取相关的声明值,

var identity = (ClaimsIdentity) User.Identity;
var claims = identity.Claims.ToList();

if (claims.Any(x = > x.ClaimType == ClaimTypes.Role && x.ClaimValue == "CanChangeData")) 
{
    ...
}

【讨论】:

    【解决方案3】:

    我使用以下代码按类型获取声明:

    public string GetClaimByClaimType(string claimType)
    {
        return ((ClaimsPrincipal) Thread.CurrentPrincipal)
            .Claims
            .Where(c => claimType == c.Type)
            .Select(c => c.Value)
            .SingleOrDefault() ?? string.Empty;
    }
    

    在你的特殊情况下,因为你会用:

    // I would recommend using a custom claim type instead of the MS schema name
    var hasCanChangeDataRole =
        GetClaimByClaimType("http://schemas.microsoft.com/ws/2008/06/identity/claims/role");
    
    var canChangeData = 
        "canChangeData".Equals(hasRole, StringComparison.OrdinalIgnoreCase);
    

    根据您的情况,您可以将这些抽象为更简洁的方法。通常我在声明中存储更复杂的数据类型,因此我进行这些检查的支持方法更加定制。

    【讨论】:

      猜你喜欢
      • 2015-04-15
      • 1970-01-01
      • 1970-01-01
      • 2021-04-13
      • 1970-01-01
      • 2018-10-19
      • 2017-08-05
      • 2017-06-08
      • 2012-11-07
      相关资源
      最近更新 更多