简体   繁体   中英

Authenticate User into the System using Claims Identity

I Need to login a user (with help of user name) to the system through claims identity and below is what am trying to achieve.

  1. With the help of a User Name fetch the user details from Database and create a user object.

  2. And passing the object to the CreateIdentityAsync

UserManager.CreateIdentityAsync(user,DefaultAuthenticationTypes.ApplicationCookie);

Currently the application is multi-tenant enabled. The above method works only for the records where tenant Id is null. But for other valid records with tenent id not null , it's throwing error

userId not found

from userManager.CreateIdentityAsync

So I tried creating a custom claim identity and login into the system as below

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

Which is also failing due to some reason.

Can anybody help me solve this issue. How can I login a user to the system through claims identity

By Looking at how Asp.net Identity Framework implemented the Claims Identity . I was able to successfully create an custom Claims Identity as below.

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

Hope this helps someone.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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