如何设置MVC 5自定义ClaimsPrincipal? [英] How to set a custom ClaimsPrincipal in MVC 5?
问题描述
我创建了一个自定义的主类
I created a custom principal class
public class FacebookPrincipal : ClaimsPrincipal
{
public JObject Data { get; set; }
}
和我想使用它。当用户登录时,我试图设置
And I want to use it. When the user logs in, I tried to 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
和铸造 FacebookPrincipal
返回null。
我如何设置自定义的主?
How do I set a custom principal?
推荐答案
ASP.NET身份使用默认ClaimsIdentityFactory到用户和线程分配ClaimsIdentity之前创建。您应该创建自己的ClaimsIdentityFactory,您可以添加或管理的更多信息。
ASP.NET Identity uses default ClaimsIdentityFactory to create before assigning ClaimsIdentity to User and Thread. You shall create your own ClaimsIdentityFactory where you can add or manage additional information.
UserManager<IdentityUser> userManager = new UserManager<IdentityUser>(new UserStore<IdentityUser>());
userManager.ClaimsIdentityFactory=new MyClaimsIdentityFactory<IdentityUser>();
和下面的例子中创建您的ClaimsIdentity或其子类实现。
And following example to create your implementation for ClaimsIdentity or its subclass.
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 Creattion of ClaimsIdentity and return it.
}
}
- 确保你绝对需要继承ClaimsIdentity。您可以添加其他信息作为索赔。
- 您应使用
base.CreateAync
并合并声明
来创建你的ClaimsIdentity
。 - Make sure you absolutely need to subclass ClaimsIdentity. You can add additional info as Claims.
- You shall use
base.CreateAync
and merge theClaims
to your createdClaimsIdentity
.
这篇关于如何设置MVC 5自定义ClaimsPrincipal?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!