Reputation: 28989
In a ASP.NET Core Controller I can Access User
to get all current user claims as ClaimsPrincipal
. Now I added a new user using userManager.CreateAsync
, added some claims and need all his claims as a ClaimsPrincipal for some other function.
I tried the following:
var user1 = new IdentityUserEntity
{
// set username and stuff
};
var result = await userManager.CreateAsync(user1, passwort);
await userManager.AddClaimAsync(user1, new System.Security.Claims.Claim(MyClaimTypes.Stuff, MyClaimValues.Whatever));
afterwards I created a ClaimsPrincipal like this:
var user1cp = new ClaimsPrincipal(new ClaimsIdentity(await userManager.GetClaimsAsync(user1)));
Problem is, this ClaimsPrincipal does not contain the NameIdentifier (and maybe other stuff?).
How do I get a complete ClaimsPrincipal from a user I freshy added to the database?
Upvotes: 4
Views: 3207
Reputation: 20383
I think you are looking for CreateUserPrincipalAsync
method of SignInManager
:
/// <summary>
/// Creates a <see cref="ClaimsPrincipal"/> for the specified <paramref name="user"/>, as an asynchronous operation.
/// </summary>
/// <param name="user">The user to create a <see cref="ClaimsPrincipal"/> for.</param>
/// <returns>The task object representing the asynchronous operation, containing the ClaimsPrincipal for the specified user.</returns>
public virtual async Task<ClaimsPrincipal> CreateUserPrincipalAsync(TUser user) => await ClaimsFactory.CreateAsync(user);
Upvotes: 4