IdentityServer4 Net Core 2 不调用自定义 iProfileService

IdentityServer4 Net Core 2 not calling custom iProfileService

我已经将我的 Identity Server 项目升级到 Net Core 2,但现在我无法调用 iProfileService 对象来添加自定义用户声明。它在 Net Core 1 中确实有效。

Startup.cs 配置服务函数

            // Add application services.
        services.AddTransient<IEmailSender, AuthMessageSender>();
        services.AddTransient<ISmsSender, AuthMessageSender>();
        services.AddTransient<IProfileService, M25ProfileService>();

        //Load certificate
        var cert = new X509Certificate2(Path.Combine(_environment.ContentRootPath, "m25id-cert.pfx"), "mypassword");

        services.AddIdentityServer()
            .AddSigningCredential(cert)
            .AddConfigurationStore(options =>
            {
                options.ConfigureDbContext = builder =>
                    builder.UseSqlServer(connectionString,
                        sql => sql.MigrationsAssembly(migrationsAssembly));
            })
            .AddOperationalStore(options =>
            {
                options.ConfigureDbContext = builder =>
                    builder.UseSqlServer(connectionString,
                        sql => sql.MigrationsAssembly(migrationsAssembly));
                //options.EnableTokenCleanup = true;
                //options.TokenCleanupInterval = 30;
            })
            .AddProfileService<M25ProfileService>()
            .AddAspNetIdentity<ApplicationUser>();

M25ProfileService.cs

    public class M25ProfileService : IProfileService
{
    public M25ProfileService(UserManager<ApplicationUser> userManager)
    {
        _userManager = userManager;
    }

    public Task GetProfileDataAsync(ProfileDataRequestContext context)
    {
        var user = _userManager.GetUserAsync(context.Subject).Result;

        var claims = new List<Claim>
        {
            new Claim(JwtClaimTypes.GivenName, user.FirstName),
            new Claim(JwtClaimTypes.FamilyName, user.LastName),
            new Claim(IdentityServerConstants.StandardScopes.Email, user.Email),
            new Claim("uid", user.Id),
            new Claim(JwtClaimTypes.ZoneInfo, user.TimeZone)
        };
        if (user.UserType != null) claims.Add(new Claim("mut", ((int)user.UserType).ToString()));
        context.IssuedClaims.AddRange(claims);
        return Task.FromResult(0);

    }

    public Task IsActiveAsync(IsActiveContext context)
    {
        var user = _userManager.GetUserAsync(context.Subject).Result;
        context.IsActive = user != null;
        return Task.FromResult(0);
    }
}

}

Config.cs

    public class Config
{
    // try adding claims to id token
    public static IEnumerable<IdentityResource> GetIdentityResources()
    {
        var m25Profile = new IdentityResource(
            "m25.profile", 
            "m25 Profile", 
            new[]
            {
                ClaimTypes.Name,
                ClaimTypes.Email,
                IdentityServerConstants.StandardScopes.OpenId,
                JwtClaimTypes.GivenName,
                JwtClaimTypes.FamilyName,
                IdentityServerConstants.StandardScopes.Email,
                "uid",
                JwtClaimTypes.ZoneInfo
            }
        );

        return new List<IdentityResource>
        {
            new IdentityResources.OpenId(),
            new IdentityResources.Profile(),
            new IdentityResources.Email(),
            m25Profile
        };
    }

    public static IEnumerable<ApiResource> GetApiResources()
    {
        //Try adding claims to access token
        return new List<ApiResource>
        {
            new ApiResource(
                "m25api",
                "message25 API",
                new[]
                {
                    ClaimTypes.Name,
                    ClaimTypes.Email,
                    IdentityServerConstants.StandardScopes.OpenId,
                    JwtClaimTypes.GivenName,
                    JwtClaimTypes.FamilyName,
                    IdentityServerConstants.StandardScopes.Email,
                    "uid",
                    JwtClaimTypes.ZoneInfo
                }
            )
        };
    }

    public static IEnumerable<Client> GetClients()
    {
        // client credentials client
        return new List<Client>
        {
            new Client
            {
                ClientId = "client",
                ClientName = "Client",
                AllowedGrantTypes = GrantTypes.HybridAndClientCredentials,

                ClientSecrets =
                {
                    new Secret("secret".Sha256())
                },
                AllowedScopes = new List<string>
                {
                    IdentityServerConstants.StandardScopes.OpenId,
                    IdentityServerConstants.StandardScopes.Profile,
                    IdentityServerConstants.StandardScopes.Email,
                    "m25api"
                }
            },

            // Local Development Client
            new Client
            {
                ClientId = "m25AppDev",
                ClientName = "me25",
                AllowedGrantTypes = GrantTypes.Implicit,
                AllowAccessTokensViaBrowser = true,
                RequireConsent = false,

                RedirectUris = { "http://localhost:4200/authorize.html" },
                PostLogoutRedirectUris = { "http://localhost:4200/index.html" },
                AllowedCorsOrigins = { "http://localhost:4200" },

                AllowedScopes =
                {
                    IdentityServerConstants.StandardScopes.OpenId,
                    IdentityServerConstants.StandardScopes.Profile,
                    IdentityServerConstants.StandardScopes.Email,
                    JwtClaimTypes.GivenName,
                    "mut",
                    "m25api"
                },
                AllowOfflineAccess = true,

                IdentityTokenLifetime = 300,
                AccessTokenLifetime = 86400
            }
        };
    }
}

我尝试的第一件事就是让身份服务器允许我登录并显示类似于 id4 示例的用户声明。当我登录时,列出了标准声明,但列出了 none 自定义声明。我在 M25ProfileService class 中设置了断点,但它们从未被击中。似乎 ID4 从未使用过客户 ProfileService class,但我的 startup.cs 中确实有它。

我也从我的测试 JS 客户端尝试过并得到相同的结果。这是我的 JS 客户端的一个片段:

var config = {
    authority: "http://localhost:5000",
    client_id: "m25AppDev",
    redirect_uri: "http://localhost:4200/authorize.html",
    response_type: "id_token token",
    scope:"openid profile m25api",
    post_logout_redirect_uri : "http://localhost:4200/index.html"
};
var mgr = new Oidc.UserManager(config);

mgr.getUser().then(function (user) {
    if (user) {
        log("User logged in", user.profile);
        document.getElementById("accessToken").innerHTML = "Bearer " + user.access_token + "\r\n";
    }
    else {
        log("User not logged in");
    }
});

function login() {
    mgr.signinRedirect();
}

此时,我不确定要尝试什么。我想如果我将声明添加到 id 令牌(根据我的理解为 GetIdentityResources() 函数)甚至访问令牌(根据我的理解为 GetApiResources() 函数),我会看到声明但似乎没有任何效果。请帮忙!提前致谢!

此外,我曾经能够从我的客户端以及在日志后呈现的身份服务器自己的索引页面中获取自定义声明

更改这些代码行的顺序:

.AddProfileService<M25ProfileService>()
.AddAspNetIdentity<ApplicationUser>();

一个如果覆盖另一个。

我明白了。多亏了 GitHub 上的 some code,我才能够弄清楚我遗漏了什么。我只需要将这两行添加到 config.cs 中每个客户端的配置中,一切都完美无缺!

AlwaysSendClientClaims = true,
AlwaysIncludeUserClaimsInIdToken = true

这适用于远程客户端。但是,当我在 ID 服务器本身登录时(不是从客户端),我仍然无法让它工作。现在这不是什么大问题,但将来可能会成为问题。 If/When 我想通了,我会尽量记得更新我的答案。同时,我希望这对其他人有帮助。

除了上面的答案(除了问题中显示的 Startup.cs 已经包含相关代码行这一事实之外)我想添加另一个非常简单的原因来解释为什么可能不会调用配置文件服务:

别忘了用依赖注入容器注册服务!

因为只有 .AddProfileService<ProfileService>() 是不够的。

您还需要:

services.AddScoped<IProfileService, ProfileService>();

或者:

services.AddTransient<IProfileService, ProfileService>();