从 usermanager 获取 ClaimsPrincipal
Get ClaimsPrincipal from usermanager
在 ASP.NET 核心控制器中,我可以访问 User
以获取所有当前用户声明为 ClaimsPrincipal
。现在我使用 userManager.CreateAsync
添加了一个新用户,添加了一些声明并需要他的所有声明作为其他功能的 ClaimsPrincipal。
我尝试了以下方法:
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));
之后我像这样创建了一个 ClaimsPrincipal:
var user1cp = new ClaimsPrincipal(new ClaimsIdentity(await userManager.GetClaimsAsync(user1)));
问题是,这个 ClaimsPrincipal 不包含 NameIdentifier(可能还有其他东西?)。
如何从刚添加到数据库的用户那里获得完整的 ClaimsPrincipal?
我认为您正在寻找 SignInManager
的 CreateUserPrincipalAsync
方法:
/// <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);
在 ASP.NET 核心控制器中,我可以访问 User
以获取所有当前用户声明为 ClaimsPrincipal
。现在我使用 userManager.CreateAsync
添加了一个新用户,添加了一些声明并需要他的所有声明作为其他功能的 ClaimsPrincipal。
我尝试了以下方法:
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));
之后我像这样创建了一个 ClaimsPrincipal:
var user1cp = new ClaimsPrincipal(new ClaimsIdentity(await userManager.GetClaimsAsync(user1)));
问题是,这个 ClaimsPrincipal 不包含 NameIdentifier(可能还有其他东西?)。
如何从刚添加到数据库的用户那里获得完整的 ClaimsPrincipal?
我认为您正在寻找 SignInManager
的 CreateUserPrincipalAsync
方法:
/// <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);