繁体   English   中英

使用声明身份验证用户到系统的身份

[英]Authenticate User into the System using Claims Identity

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

  1. 在用户名的帮助下,从数据库中获取用户详细信息并创建用户对象。

  2. 并将对象传递给CreateIdentityAsync

UserManager.CreateIdentityAsync(用户,DefaultAuthenticationTypes.ApplicationCookie);

当前,该应用程序已启用多租户。 上面的方法仅适用于租户ID为空的记录。 但是,对于其他具有租户ID不为null的有效记录,则会引发错误

找不到userId

来自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。 我能够成功创建一个自定义的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));

希望这对某人有帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM