【问题标题】:Asp.Net 5 / Identity 3: Caching of Claims in the IdentityDbContext implementationAsp.Net 5 / Identity 3:在 IdentityDbContext 实现中缓存声明
【发布时间】:2016-01-05 00:17:05
【问题描述】:

在寻找一种能够通过管理控制器为发出请求的用户以外的用户分配和撤销角色的方法时,我实现了一个自定义 IAuthorizeFilter 来检查存储为声明的 Guid 标记是否匹配UserClaims 的 Entity Framework 7 Code First Identity 表中的一个值。

要点,就是这段代码:

public class RefreshUserClaimsFilterAttribute : IAuthorizationFilter
{
    public void OnAuthorization(AuthorizationContext context)
    {
        var User = context.HttpContext.User;
        var dbContext = context.HttpContext.ApplicationServices.GetRequiredService<ApplicationDbContext>();
        var stampFromClaims = User.Claims.FirstOrDefault(Claim => Claim.Type == "ClaimsStamp")?.Value;
        var stampFromDb = dbContext.UserClaims.Where(UserClaim => UserClaim.UserId == User.GetUserId()).ToList().FirstOrDefault(UserClaim => UserClaim.ClaimType == "ClaimsStamp")?.ClaimValue; 
        // Update claims via RefreshSignIn if necessary
    }
}

我在分配var stampFromDb 的那一行遇到了问题,通过以下方式可能更易读:

var stampFromDb = dbContext.UserClaims.FirstOrDefault(UserClaim => UserClaim.UserId == User.GetUserId() && UserClaim.ClaimType == "ClaimsStamp")?.ClaimValue;

然而,这给了我缓存(与来自 User.Identity 的实际声明相同的值)结果,我找不到任何关于此的文档。我最好的猜测是错误就在我身边,但我以前从未遇到过这样的问题。这是我第一次使用 Asp.Net 5 和 EF7。我正在使用默认连接 (LocalDB) 到 SQL Server 12.0.2000。

这是一项功能吗?如果是,是否可以将其关闭或我在某处犯了错误?

【问题讨论】:

  • 当我调用User.Claims(它确实如此)时,我期待一个缓存的结果(据我所知来自Http cookie)。然后我用UserManager.ReplaceClaimAsync() 更新数据库。现在,UserClaims 的数据库条目与缓存在 cookie 中的 ClaimValue 不同。但是,当我按照ApplicationDbContext.UserClaims DbSet 上的问题中所述访问声明时,如果我使用提到的查询,我确实会得到旧值。

标签: c# asp.net asp.net-core entity-framework-core asp.net-identity-3


【解决方案1】:

这个问题是由于通过依赖注入创建服务有两种不同的方法: 我的问题中使用的示例代码

var dbContext = context.HttpContext.ApplicationServices.GetRequiredService<ApplicationDbContext>();

应该在哪里使用

var dbContext = context.HttpContext.RequestServices.GetRequiredService<ApplicationDbContext>();

这里的区别在于ApplicationServicesRequestServices。看起来ApplicationServices 注入器在某处确实有一个数据库上下文实例,该实例已较早填充 DbSet,因此返回缓存数据而不是执行数据库查询。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-18
    • 1970-01-01
    • 2020-02-09
    • 2015-06-20
    • 2016-02-28
    • 1970-01-01
    • 2016-02-18
    • 2014-08-26
    相关资源
    最近更新 更多