有效地检查角色声明

Nai*_*gel 9 c# asp.net authentication asp.net-mvc claims

我正在开发一个Asp.NET MVC5 Web应用程序(.NET 4.6),我需要向具有特定声明的一组用户显示一些额外的HTML行.我见过一些冗长的解决方案,但我更喜欢保持简短,所以我想出了这个

@{
    if (System.Security.Claims.ClaimsPrincipal.Current.Claims.ToList().FirstOrDefault(c => c.Type == "role" && c.Value == "AwesomeUserRole") != null) {
        <!-- my HTML goes here -->
    }
 }
Run Code Online (Sandbox Code Playgroud)

这是检查经过身份验证的用户声明的好方法,还是有最佳做法可以遵循?任何更清洁/更有效的解决方案也是受欢迎的.

Jim*_*uts 23

因为IdentityASP.NET中的所有对象现在都是a ClaimsIdentity,所以您始终可以将当前IPrincipal转换为ClaimsIdentity:

((System.Security.Claims.ClaimsIdentity)User.Identity).HasClaim("role", "AwesomeUserRole")
Run Code Online (Sandbox Code Playgroud)

但它实际上最容易使用 User.IsInRole("AwesomeUserRole")

只要您没有更改默认配置,具有类型的声明就会role自动输入到线程主体的roles集合中.

如果您需要检查除角色之外的其他声明类型,我通常会创建一组扩展方法来IPrincipal包装声明检查:

public static bool CanDoX(this IPrincipal principal)
{
    return ((ClaimsIdentity)principal.Identity).HasClaim(claimType, claimValue);
}
Run Code Online (Sandbox Code Playgroud)

扩展方法的好处是,您可以检查任何类型的声明并返回它们可能包含的任何值,而不仅仅是声明是否存在.


Pau*_*her 12

请记住,Principal可以有多个与之关联的标识,例如,您已通过Windows身份验证进行身份验证,但随后添加了自定义标识以及数据库中的声明.

因此,任何声明检查都可能需要查看所有身份,这里有一些有用的扩展方法

public static bool ClaimExists(this IPrincipal principal, string claimType)
{
    var ci = principal as ClaimsPrincipal;
    if (ci == null)
    {
        return false;
    }

    var claim = ci.Claims.FirstOrDefault(x => x.Type == claimType);

    return claim != null;
}

public static bool HasClaim(this IPrincipal principal, string claimType,
                            string claimValue, string issuer = null)
{
    var ci = principal as ClaimsPrincipal;
    if (ci == null)
    {
        return false;
    }

    var claim = ci.Claims.FirstOrDefault(x => x.Type == claimType
                                         && x.Value == claimValue
                                         && (issuer == null || x.Issuer == issuer));

    return claim != null;
}
Run Code Online (Sandbox Code Playgroud)