Reputation: 2151
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.
With the help of a User Name fetch the user details from Database and create a user object.
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
Upvotes: 4
Views: 9820
Reputation: 2151
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.
Upvotes: 4