如何在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;
它在我设置之后就可以正常工作,但是当我home/index
该值就会丢失
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 userManager = new UserManager (new UserStore ()); userManager.ClaimsIdentityFactory = new MyClaimsIdentityFactory ();
以下代码为ClaimsIdentity或其子类创建实现。
public class MyClaimsIdentityFactory : ClaimsIdentityFactory where IUser : IdentityUser { public MyClaimsIdentityFactory(): base() { } public override System.Threading.Tasks.Task CreateAsync(UserManager manager, IUser user, string authenticationType) { // Override Creation of ClaimsIdentity and return it. } }
- 确保您绝对需要inheritanceClaimsIdentity。 您可以添加其他信息作为声明。
- 您应使用
base.CreateAsync
并将Claims
合并到您创建的ClaimsIdentity
。
•确保您绝对需要子类化ClaimsIdentity。 您可以添加其他信息作为声明。
您应该注意添加额外的补充信息声明,因为副作用可能会改变授权策略的决策方式。
今天再次阅读这个问题我意识到问题是身份持久性而不是如何创建自定义ClaimsIdentity !!!
- 使用ClaimsIdentity子类而不是ClaimsPrincipal可能有助于大多数自定义。
- 其次,正如@marisks所建议的那样,您可以使用IUserClaimsStore存储为您的用户发布的第三方声明。 只有自定义声明访问是问题。
此外,要保持两个请求之间的标识,请使用以下代码。
//you can create your own Identity here. var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie); //Or add custom claims. Claims Stored in IUserClaimStore are already populated by above creation. identity.AddClaim(new Claim("ProfileDATA", "VALUE")); AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);