【问题标题】:Authenticate User into the System using Claims Identity使用声明身份验证用户进入系统
【发布时间】:2016-04-07 22:03:24
【问题描述】:

我需要通过声明身份将用户(在用户名的帮助下)登录到系统,以下是我试图实现的目标。

  1. 借助用户名从数据库中获取用户详细信息并创建用户对象。

  2. 并将对象传递给 CreateIdentityAsync

UserManager.CreateIdentityAsync(user,DefaultAuthenticationTypes.ApplicationCookie);

目前该应用程序已启用多租户。上述方法仅适用于租户 ID 为空的记录。但是对于其他租户 id 不为 null 的有效记录,它会抛出错误

找不到用户ID

来自 userManager.CreateIdentityAsync

所以我尝试创建一个自定义声明身份并如下登录系统

        AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);

        List<Claim> claims = new List<Claim>{
    new Claim(ClaimTypes.GivenName, newUser.Name), //user.Name from my database
    new Claim(ClaimTypes.NameIdentifier, newUser.Id.ToString()), //user.Id from my database
    new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "MyApplicationName"),      
    new Claim(ClaimTypes.Email, newUser.EmailAddress),
    new Claim(ClaimTypes.Surname, newUser.Surname)
};
        ClaimsIdentity identity = new System.Security.Claims.ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie, ClaimTypes.Name, ClaimTypes.Role);

        AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = false }, identity);

由于某种原因,这也失败了。

谁能帮我解决这个问题。如何通过声明身份将用户登录到系统

【问题讨论】:

    标签: c# asp.net-mvc asp.net-mvc-5 owin claims-based-identity


    【解决方案1】:

    通过查看 Asp.net Identity Framework 如何实现 Claims Identity 。我能够成功创建自定义声明身份,如下所示。

        string IdentityProviderClaimType =
        "http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider";
        string DefaultIdentityProviderClaimValue = "ASP.NET Identity";
    
        var id = new ClaimsIdentity(DefaultAuthenticationTypes.ApplicationCookie, ClaimsIdentity.DefaultNameClaimType, ClaimsIdentity.DefaultRoleClaimType);
        id.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id.ToString(), ClaimValueTypes.String));
        id.AddClaim(new Claim(ClaimsIdentity.DefaultNameClaimType, user.UserName, ClaimValueTypes.String));
        id.AddClaim(new Claim(IdentityProviderClaimType, DefaultIdentityProviderClaimValue, ClaimValueTypes.String));
       //Provide the below if you have any role name 
            id.AddClaim(new Claim(ClaimsIdentity.DefaultRoleClaimType,role.Name , ClaimValueTypes.String));
    

    希望这对某人有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-05
      • 1970-01-01
      • 2011-05-30
      • 2016-11-27
      • 2020-05-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多