asp.net - 在 ASP.Net Core Identity 中获取当前主体作为我的自定义应用程序用户

标签 asp.net asp.net-mvc asp.net-identity claims-based-identity

在以前版本的 ASP.NET 中,如果我想要一个自定义类作为当前登录用户,我所做的是:让 FormsAuthentication 模块完成其工作,然后在 PostAuthenticateRequest 事件中我将当前主体 (HttpContext.Current.User) 以及我从数据库中获取的自定义主体对象(带有一些性能缓存)。

如何在 ASP.NET Identity 中实现相同的目标?我有自己的 ApplicationUser(不是 EntityFramework ASP.NET Identity 附带的默认值)和我自己的 UserStore。

在每个经过身份验证的请求中,我都有 HttpContext.User 作为 ClaimsPrincipal 对象。有没有办法用我的 CustomClaimsPrincipal 替换它?

是否有另一种更好的方法来根据当前的 ClaimsPrincipal 检索当前的 ApplicationUser 实例?

最佳答案

如果您有自己的IUserStore您可以实现IUserClaimStore自定义传递给声明主体的声明身份。

如果您需要替换默认声明主体,您应该实现 IUserClaimsPrincipalFactory并将您的实现传递给 SignInManager并将配置的管理器注册到您自己的上下文中。

它应该看起来像这样。 (假设您使用ASP.NET Core Identity,对于 Identity v2,接口(interface)和构造函数可能有所不同!)

class CustomClaimsFactory<TUser> : Microsoft.AspNetCore.Identity.IUserClaimsPrincipalFactory<TUser>
    where TUser : class
{
    public Task<ClaimsPrincipal> CreateAsync(TUser user)
    {
        // create and return your custom principal
    }
}

class OwinStartup
{
    public void Configuration(IAppBuilder app)
    {
        app.CreatePerOwinContext(CreateSignInManager);
    }

    Microsoft.AspNetCore.Identity.SignInManager CreateSignInManager()
    {
        UserManager manager; // the manager that uses your custom IUserStore
        IHttpContextAccessor accessor; // I don't know where to get it from...

        var factory = new CustomClaimsFactory();
        return new SignInManager(manager, accessor, factory, null, null, null);
    }
}

对于 ASP.Net Core 类似 OWIN 的启动配置是通过 dependency injection 完成的.

关于asp.net - 在 ASP.Net Core Identity 中获取当前主体作为我的自定义应用程序用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44152696/

相关文章:

javascript - 我们总是有 session[] 变量,那么 HTML5 的 code.SessionStorage 带来了什么新东西呢?

asp.net-mvc - ASP.NET MVC 单元测试 - 虚假存储库变得笨拙

asp.net-mvc - 未找到 WebAPI

jquery - HTML 帮助器 - 将工具提示添加到 TextBoxFor

oauth - 我如何解决 AspNet.Security.OpenIdConnect.Server 的 '"对类型 'BaseControlContext"声明的引用...

c# - ASP.NET 身份(使用 IdentityServer4)获取外部资源 oauth 访问 token

asp.net - 使用 WCF 服务调用作为 ASP.NET Identity 的用户存储

c# - Azure WebJobs 支持的 .Net Framework 版本吗?

asp.net - 如何为中继器中的第一项使用不同的样式?

c# - For循环计算阶乘