将数据传递到IdentityServer4中的IProfileService

时间:2017-08-07 14:17:18

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

我正在使用IdtentityServer4,我有一个支持人员希望代表用户登录以获得支持的方案。

当发生这种情况时,我想在整个ASP.NET Core应用程序中知道这个支持人员代表用户行事,并在屏幕上显示以下信息:
" Mr Mr代表Ms用户名"

我目前正在实施IProfileUser正常登录。我正在寻找一种方法来添加额外的"属性"在不访问数据库的情况下在令牌中包含支持人员的用户名。

我试图传递物品

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

但我不知道如何在ProfileDataRequestContext实施中GetProfileDataAsync传递给IProfileService

这是我的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));
}

1 个答案:

答案 0 :(得分:0)

您可以通过索赔传递此数据。

修改登录代码以包含“ 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);
    }