在以前版本的 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/