【问题标题】:How to set a custom ClaimsPrincipal in MVC 5?如何在 MVC 5 中设置自定义 ClaimsPrincipal?
【发布时间】:2013-11-14 20:10:24
【问题描述】:

我创建了一个自定义主体类

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;

设置后它就可以工作,但是当我去 ho home/index 时,值丢失了

var user = HttpContext.GetOwinContext().Authentication.User;
var bbbb = this.User;
var cccc = ClaimsPrincipal.Current;

上述所有方法都返回ClaimsPrincipal 类型的主体,而转换为FacebookPrincipal 则返回null。

如何设置自定义主体?

【问题讨论】:

  • Claims属性的枚举返回什么?
  • [0] = {http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier: #########} - [1] = {http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name: ####} - [2] = {http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider: ASP.NET Identity}
  • 这是我在类似问题上发布的解决方案:http://stackoverflow.com/a/25731422/264672

标签: c# asp.net-mvc authentication asp.net-mvc-5 owin


【解决方案1】:

ASP.NET Identity 在将ClaimsIdentity 分配给用户和线程之前使用默认的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

【讨论】:

  • 不需要自定义 ClaimsIdentityFactory,可以通过为用户存储实现 IUserClaimStore 接口来添加额外的声明。
【解决方案2】:

•确保您绝对需要对 ClaimsIdentity 进行子类化。您可以将其他信息添加为声明。

您应该谨慎添加额外的补充信息声明,因为副作用可能会改变授权政策的决策方式。

【讨论】:

    【解决方案3】:

    根据@marisks 的建议,您可以使用IUserClaimsStore 来存储第三方为您的用户发出的声明。仅当自定义声明访问是问题时。

    此外,要在两个请求之间保持身份,请使用以下代码。

    // One can create one's 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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-11
      相关资源
      最近更新 更多