使用 Claims Identity 验证用户进入系统

Authenticate User into the System using Claims Identity

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

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

  2. 并将对象传递给 CreateIdentityAsync

UserManager.CreateIdentityAsync(user,DefaultAuthenticationTypes.ApplicationCookie);

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

userId not found

来自 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);

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

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

通过查看 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));

希望这对某人有所帮助。