asp.net-core - 将数据传递给 IdentityServer4 中的 IProfileService

标签 asp.net-core identityserver4 asp.net-core-identity

我正在使用 IdtentityServer4,其中有一个场景,支持人员想要代表用户登录以获得支持。

发生这种情况时,我想在我的 ASP.NET Core 应用程序中知道该支持人员正在代表用户行事,并在屏幕上显示一条消息:
“支持先生代表用户名女士”

我目前正在实现IProfileUser以进行正常登录。我正在寻找一种方法来添加额外的“属性”,以在 token 中包含支持人员的用户名,而无需访问数据库。

我试图传递元素

await _signInManager.SignInAsync(applicationUser, new AuthenticationProperties
{
    Items = {new KeyValuePair<string, string>("SupportName", "Mr Support")}
}).ConfigureAwait(false);

但我不知道如何从 IProfileService 实现中传递给 GetProfileDataAsyncProfileDataRequestContext 获取它们。

这是我的 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/

相关文章:

c# - 身份服务器4 : how to set Authority based on environment?

c# - 与.net core和身份框架的集成测试

c# - Blazor 和 Web API 解决方案中的 .NET Core 身份

c# - 为什么 Graph API 无法正确提供 AAD 用户上次事件

asp.net-core - ASP.NET Core 3.1 HttpClient 仅记录警告和错误

c# - 使用 IdentityServer4 加载项目时 DefaultUserSession 中的 NullReferenceException

c# - ASP.NET Core 识别 Auth + Angular : Login Not Working

c# - ContractResolver,带下划线的小写字母(蛇形属性名称)?

.net core - 工作单元通用存储库模式

.net - IdentityServer 4 还是 OpenIddict?