IdentityServer4 Net Core 2 不调用自定义 iProfileService

问题描述 投票:0回答:3

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

Startup.csConfigureServices函数

// 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);
    }
}

}

配置.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 示例的用户声明。当我登录时,会列出标准声明,但不会列出自定义声明。我在 M25ProfileService 类中放置了断点,但它们从未被击中。看来 ID4 从未使用过客户 ProfileService 类,但我的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() 函数),我会看到这些声明,但似乎没有任何效果。请帮忙!预先感谢!

此外,我曾经能够从我的客户端以及在日志之后呈现的 Identity Server 自己的索引页面获取自定义声明

profile asp.net-core-2.0 identityserver4
3个回答
10
投票

更改这些代码行的顺序:

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

一个如果覆盖另一个。


8
投票

我想通了。感谢 GitHub 上的一些代码,我能够找出我缺少的内容。我只需要将这两行添加到 config.cs 中每个客户端的配置中,一切都很完美!

AlwaysSendClientClaims = true,
AlwaysIncludeUserClaimsInIdToken = true

这适用于远程客户端。但是,当我在 ID 服务器本身登录(而不是从客户端)时,我仍然无法让它工作。目前这不是什么大事,但将来可能会发生。如果/当我弄清楚这一点时,我会尽力记住更新我的答案。同时,我希望这对其他人有帮助。


4
投票

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

不要忘记向依赖注入容器注册服务!

仅仅拥有

.AddProfileService<ProfileService>()
是不够的。

您还需要:

services.AddScoped<IProfileService, ProfileService>();

或者:

services.AddTransient<IProfileService, ProfileService>();
© www.soinside.com 2019 - 2024. All rights reserved.