IdentityServer4 Net Core 2不调用自定义iProfileService [英] IdentityServer4 Net Core 2 not calling custom iProfileService

查看:187
本文介绍了IdentityServer4 Net Core 2不调用自定义iProfileService的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've upgraded my Identity Server project to Net Core 2 and now I am not able to get the iProfileService object to be called to add in custom user claims. It did work in 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中确实包含它.

The first thing I'm trying is just to get the identity server to allow me to login and show the user claims similar to the id4 samples. When I login, the standard claims are listed but none of the custom claims. I've put break points in the M25ProfileService class but they never get hit. It seems that ID4 is never using the customer ProfileService class but I do have it in my startup.cs.

我也从测试JS Client中尝试过,并获得了相同的结果.这是我的JS客户端的摘录:

I've also tried from my test JS Client and get the same results. Here's a snippet from my JS Client:

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()函数),我都会看到声明,但似乎没有任何作用.请帮忙!预先感谢!

At this point, I'm not sure what to try. I thought if I added the claims to the id token (GetIdentityResources() function from what I understand) and even the access token (GetApiResources() function from what I understand), I'd see the claims but nothing seems to work. Please help! Thanks in advance!

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

Also, I used to be able to get the custom claims from my client as well as from the Identity Server's own index page that renders after log

推荐答案

我知道了.感谢 GitHub上的一些代码,我能够弄清我所缺少的内容.我只需要将这2行添加到config.cs的每个客户端的配置中,一切就完美了!

I figured it out. Thanks to some code on GitHub, I was able to figure out what I was missing. I just needed to add these 2 lines to each client's config in config.cs and all worked perfect!

AlwaysSendClientClaims = true,
AlwaysIncludeUserClaimsInIdToken = true

这适用于远程客户端.但是,当我在ID Server本身(而不是从客户端)登录时,仍然无法使其正常工作.目前这不是什么大问题,但将来可能会有所发展.如果/当我弄清楚那个部分时,我会尽力记住要更新我的答案.同时,我希望这对其他人有帮助.

This works for remote clients. However, I still can't get it to work when I'm on the ID Server itself logging in (not from a client). That's not a big deal for now but could be something in the future. If/When I figure that piece out, I'll try to remember to update my answer. Meanwhile, I hope this helps others.

这篇关于IdentityServer4 Net Core 2不调用自定义iProfileService的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆