【问题标题】:Get all users with a given claim获取具有给定声明的所有用户
【发布时间】:2016-11-15 01:11:39
【问题描述】:

我正在做一个 aspnet core 1.0 项目,我最近了解了什么是声明以及如何使用它们来实现基于策略的授权。

我想要达到的目标:

我想获取所有获得给定政策授权的用户(即拥有给定声明的用户,比如说Claim {Type = "CanReceiveXReport", Value = True}

我希望这样做的代码类似于:

public static IQueryable<User> WithClaim(this IQueryable<User> users, string claimName) =>
    users
        .Include(u=> u.Claims)
        .Where(u=> u.Claims.Any(c=> c.ClaimType == claimName));

问题:

当我运行上述代码时,对于所有用户,user.Claims 始终为空。我还尝试通过在Include() 之后添加ToList() 来实现查询,但没有成功。


当我意识到这不起作用时,我希望有某种ClaimsManager&lt;T&gt; 来执行此类操作。

我发现的所有 api 和 answers 都专注于为单个用户获取声明。

我知道我可以做类似this answer 的事情,但我宁愿不这样做,我希望在数据库中运行该查询。

我想可以创建一个存储过程,但我宁愿在我的应用程序中保留我的域逻辑。

版本:

(我认为是相关的)

{
    "Microsoft.AspNetCore.Identity": "1.0.0",
    "Microsoft.AspNetCore.Identity.EntityFrameworkCore": "1.0.0",
    "Microsoft.EntityFrameworkCore.Relational": "1.0.0",
    "Microsoft.EntityFrameworkCore.SqlServer": "1.0.1",
    "Microsoft.NETCore.App": "1.0.0"
}

【问题讨论】:

    标签: asp.net-core asp.net-identity entity-framework-core claims-based-identity


    【解决方案1】:

    相信你在 UserManager 中寻找this 方法:

    /// <summary>
    /// Returns a list of users from the user store who have the specified <paramref name="claim"/>.
    /// </summary>
    /// <param name="claim">The claim to look for.</param>
    /// <returns>
    /// A <see cref="Task{TResult}"/> that represents the result of the asynchronous query, a list of <typeparamref name="TUser"/>s who
    /// have the specified claim.
    /// </returns>
    public virtual Task<IList<TUser>> GetUsersForClaimAsync(Claim claim)
    {
        ThrowIfDisposed();
        var store = GetClaimStore();
        if (claim == null)
        {
            throw new ArgumentNullException(nameof(claim));
        }
        return store.GetUsersForClaimAsync(claim, CancellationToken);
    }
    

    【讨论】:

    • 是的,我也找到了这种方法,但是我需要使用声明值来限制我的搜索,这不适用于我的特定情况。我查看了该方法的实现,并且正在编写自己的忽略声明值的版本。​​
    猜你喜欢
    • 1970-01-01
    • 2016-03-04
    • 1970-01-01
    • 2012-11-03
    • 2020-01-06
    • 2013-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多