我正在使用 IdtentityServer4,其中有一个场景,支持人员想要代表用户登录以获得支持。
发生这种情况时,我想在我的 ASP.NET Core 应用程序中知道该支持人员正在代表用户行事,并在屏幕上显示一条消息:
“支持先生代表用户名女士”
我目前正在实现IProfileUser
以进行正常登录。我正在寻找一种方法来添加额外的“属性”,以在 token 中包含支持人员的用户名,而无需访问数据库。
我试图传递元素
await _signInManager.SignInAsync(applicationUser, new AuthenticationProperties
{
Items = {new KeyValuePair<string, string>("SupportName", "Mr Support")}
}).ConfigureAwait(false);
但我不知道如何从 IProfileService
实现中传递给 GetProfileDataAsync
的 ProfileDataRequestContext
获取它们。
这是我的 IProfileService
实现:
public async Task GetProfileDataAsync(ProfileDataRequestContext context)
{
ClaimsPrincipal claimsPrincipal = context.Subject;
if (claimsPrincipal == null)
{
throw new ArgumentNullException(nameof(context.Subject));
}
string id = claimsPrincipal.GetSubjectId();
ApplicationUser user = await _userManager.FindByIdAsync(id).ConfigureAwait(false);
if (user == null)
{
throw new ArgumentException("Invalid user identifier");
}
context.IssuedClaims.Add(new Claim(JwtClaimTypes.Email, user.Email));
IList<string> roles = await _userManager.GetRolesAsync(user).ConfigureAwait(false);
foreach (var role in roles)
{
context.IssuedClaims.Add(new Claim(JwtClaimTypes.Role, role));
}
context.IssuedClaims.Add(new Claim(JwtClaimTypes.Name, user.Name));
}
最佳答案
您可以通过声明传递此数据。
修改您的登录代码以包含“SupportName”声明:
// Sign in the user and include the SupportName claim
await HttpContext.SignInAsync(userId, username, new Claim("SupportName", "Mr Support"));
并在 GetProfileDataAsync
中访问此声明:
public async Task GetProfileDataAsync(ProfileDataRequestContext context) {
// Find the "SupportName" claim added during sign-in
var supportNameClaim = context.Subject.FindFirst("SupportName");
if (supportNameClaim != null) {
Console.WriteLine($"Signed in on behalf of {supportNameClaim.Value}");
}
// Issue all the claims (if required)
context.IssuedClaims.AddRange(context.Subject.Claims);
}
关于asp.net-core - 将数据传递给 IdentityServer4 中的 IProfileService,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45549114/