profile - IdentityServer4 Net Core 2未调用自定义iProfileService

标签 profile asp.net-core-2.0 identityserver4

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

Startup.cs ConfigureServices函数

            // 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示例的用户声明。登录时,列出了标准声明,但未列出任何自定义声明。我已经在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 token (根据我的理解得到GetIdentityResources()函数)甚至访问 token (从我的理解得到的GetApiResources()函数),我都会看到声明,但似乎没有任何作用。请帮忙!提前致谢!

另外,我以前能够从客户端以及从Identity Server自己的索引页获取自定义声明,该索引页在登录后呈现

最佳答案

更改以下代码行的顺序:

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

一个如果覆盖另一个。

关于profile - IdentityServer4 Net Core 2未调用自定义iProfileService,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48292112/

相关文章:

来自 &lt;input&gt; 的 PHP POST 值是使用 While 循环创建的

c# - 如何为使用 AutoMapper 和依赖注入(inject)的 .net core 2.0 服务编写 xUnit 测试?

asp.net-core-2.0 - 如何扩展 ASP.NET Core 2.0 的角色以处理不同位置的不同权限?

identityserver4 - Identityserver4 连接/ token 端点给出 400 错误请求

owin - IdentityServer4 和 Web API .NET 4.6.2

authentication - IdentityServer4 分别对每个客户端进行身份验证

docker - Visual Studio 配置文件更改导致无效的 ssl 证书?

PowerShell $PROFILE、变量和 NoteProperty/Add-Member

c# - SignalR - 从上下文调用静态类型的集线器

firefox - 在 Selenium 2 中使用现有的 Firefox 配置文件 - 不起作用?一个错误?