首页 文章

在ASP.Net核心标识中获取当前主体作为我的自定义应用程序用户

提问于
浏览
3

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

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

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

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

1 回答

  • 2

    如果您有自己的 IUserStore ,则可以实现 IUserClaimStore 来自定义传递给声明主体的声明标识 .

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

    它应该看起来像这样 . (假设您使用的是ASP.NET核心标识,对于Identity v2,接口和构造函数可能会有所不同!)

    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);
        }
    }
    

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

相关问题