CodeGo.net>如何在MVC 5中设置自定义ClaimsPrincipal?
作者:互联网
我创建了一个自定义的校长班
public class FacebookPrincipal : ClaimsPrincipal
{
public JObject Data { get; set; }
}
我想使用它.用户登录时,我尝试设置
var fbP = new FacebookPrincipal { Data = user.Data };
Thread.CurrentPrincipal = fbP;
AuthenticationManager.User = fbP;
HttpContext.User = fbP;
设置后它立即可用,但是当我返回首页/索引时,该值会丢失
var user = HttpContext.GetOwinContext().Authentication.User;
var bbbb = this.User;
var cccc = ClaimsPrincipal.Current;
以上所有方法均返回类型为ClaimsPrincipal的Principal,并将其转换为FacebookPrincipal则返回null.
如何设置自定义主体?
解决方法:
在将ClaimsIdentity分配给User和Thread之前,ASP.NET Identity使用默认的ClaimsIdentityFactory进行创建.您应该创建自己的ClaimsIdentityFactory,可以在其中添加或管理其他信息.
UserManager<IdentityUser> userManager = new UserManager<IdentityUser>(new UserStore<IdentityUser>());
userManager.ClaimsIdentityFactory = new MyClaimsIdentityFactory<IdentityUser>();
以下代码可为ClaimsIdentity或其子类创建实现.
public class MyClaimsIdentityFactory<IUser> : ClaimsIdentityFactory<IUser> where IUser : IdentityUser
{
public MyClaimsIdentityFactory(): base()
{
}
public override System.Threading.Tasks.Task<System.Security.Claims.ClaimsIdentity> CreateAsync(UserManager<IUser> manager, IUser user, string authenticationType)
{
// Override Creation of ClaimsIdentity and return it.
}
}
>确保您绝对需要对ClaimsIdentity进行子类化.您可以添加其他信息作为声明.
>您应使用base.CreateAsync并将Claims合并到您创建的ClaimsIdentity中.
标签:owin,authentication,asp-net-mvc-5,c,asp-net-mvc 来源: https://codeday.me/bug/20191030/1966376.html