【问题标题】:How to check if an ApplicationUser has a Claim如何检查 ApplicationUser 是否有声明
【发布时间】:2018-03-22 10:49:38
【问题描述】:

是否可以检查 ApplicationUser 是否有声明?

我知道可以检查 ApplicationUser 是否在某个角色中

userManager.IsInRoleAsync(applicationUser,"admin");

而且我知道可以检查用户是否有这样的声明:

userManager.GetClaimsAsync(applicationUser)).Any(c=>c.Type == "userType" && c.Vaue == "admin");

但我想使用类似 ClaimsPrincipal 对象的东西:

User.HasClaim("userType", "admin");

但我没有 ClaimsPrincipal,我只有 ApplicationUser。因此,如果可能的话,我也想知道获取 ApplicationUser 的 ClaimsPrincipal 的方法。

【问题讨论】:

  • 你可以为UserManager写一个扩展方法吗?

标签: c# identity claims-based-identity


【解决方案1】:

正如@Jerodev 回答的那样,您可以使用UserManager 来获取用户声明。或者,您可以使用派生自 IdentityDbContext<ApplicationUser>DbContext

bool hasClaim = _db.UserClaims
   .Any(c => c.UserId == userId && c.ClaimValue == claimValue && c.ClaimType == claimType);

这两种技术仅适用于存储在 DB 中的声明,不适用于您将动态添加的声明,例如 UserClaimsPrincipalFactory。因此,这两种技术都与User.HasClaim("userType", "admin") 不同,其中UserClaimsPrincipal

【讨论】:

    【解决方案2】:

    您可以将以下扩展方法添加到您的 UserManager 类中:

    public static bool HasClaim(this UserManager userManager, string type, string value)
    {
        return userManager.GetClaims(applicationUser).Any(c=>c.Type == type && c.Vaue == value);
    }
    

    现在您可以在 userManager 对象上使用此方法:

    var isAdmin = userManager.HasClaim("userType", "admin");
    

    【讨论】:

    • applicationUser在哪里,什么是代码sn-p?
    • 我认为扩展方法的签名是:static bool HasClaim<TUser>(this UserManager<TUser> umgr, TUser user, string type, string value) where TUser : IdentityUser
    猜你喜欢
    • 2015-08-25
    • 2019-07-16
    • 2018-05-01
    • 1970-01-01
    • 2021-10-04
    • 2012-02-25
    • 1970-01-01
    • 1970-01-01
    • 2010-10-25
    相关资源
    最近更新 更多