理想的功能:用户登录并通过网站A身份验证。他们单击一个按钮,后端从数据库中查找网站B中帐户的ID,然后将此信息发送到IdentityServer以创建包含“ user_id”的JWT ”字段。然后,它用于在网站B上调用REST端点并进行身份验证,然后使用“ user_id”创建登录cookie,该cookie将发送回网站A。然后,将用户重定向。

我们正在运行IdentityServer 4,但使用IdentityServer3作为主要代码库与它进行通信是在.NET Framework上。我尝试在extras参数中包括“ user_id”字段,但这似乎无济于事。

var client = new TokenClient(requestPath, CLIENT_ID, CLIENT_SECRET,
  AuthenticationStyle.PostValues);


var test = new Dictionary<string, string>
{
  { "user_id", "123123" }
};

// request token
var tokenResponse = await client
  .RequestClientCredentialsAsync(apiScope, test)
  .ConfigureAwait(false);


我也尝试过使用client.RequestCustomAsync和client.RequestAsync,但是没有运气。

我收到的令牌没有问题,但其中不包含user_id信息-仅包含普通受众群体,范围,有效期限等。

最佳答案

对于自定义问题字段,您需要创建IProfileService的继承类,然后实现方法GetProfileDataAsync。看起来像:

public class IdentityProfileService : IProfileService
{
    public async Task GetProfileDataAsync(ProfileDataRequestContext context)
    {
        var sub = context.Subject.GetSubjectId();
        // Call UserManager or any database to get more fields
        var user = await _userManager.FindByIdAsync(sub);

        // Set returned claims (System.Security.Claims.Claim) by setting context.IssuedClaims
        context.IssuedClaims = claims;
    }

    public async Task IsActiveAsync(IsActiveContext context)
    {
        context.IsActive = true;
    }
}


在注册Identity Service 4时,您需要对其进行声明(一个示例在.NET Core中,与.NET Framework相同)。

var identityBuilder = services.AddIdentityServer().AddProfileService<IdentityProfileService>();

10-02 02:34
查看更多