无法在.NET Core 2.0中检索声明

Nei*_*ski 7 openid-connect identityserver4 asp.net-core-2.0

我正在使用OpenId Connect身份验证服务器,特别是.NET Core 1.1上的Identity Server 4(版本1.5.2).我运行ASP.NET Framework MVC 5和ASP.NET Core 1.1 MVC Web应用程序.以下配置来自.NET Core 1.1 Web应用程序:

public void Configure(
    IApplicationBuilder app,
    IHostingEnvironment env,
    ILoggerFactory loggerFactory)
{
    app.UseDeveloperExceptionPage();
    app.UseStatusCodePages();
    app.UseRewriter(new RewriteOptions().AddRedirectToHttps());
    app.UseStaticFiles();

    #region Configure Authentication
    JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

    app.UseCookieAuthentication(
        new CookieAuthenticationOptions
        {
            AuthenticationScheme = "Cookies",
            AutomaticAuthenticate = true,
            AccessDeniedPath = "/AccessDenied"
        });
    app.UseOpenIdConnectAuthentication(
        new OpenIdConnectOptions
        {
            AuthenticationScheme = "oidc",
            SignInScheme = "Cookies",

            Authority = "https://localhost:44316",
            ClientId = "test-mule",
            ClientSecret = "secret",
            ResponseType = "code id_token",

            SaveTokens = true,
            GetClaimsFromUserInfoEndpoint = true,

            PostLogoutRedirectUri = "https://localhost:44324",
            RequireHttpsMetadata = true,

            Scope = { "openid", "profile", "name", "email", "org", "role" },

            TokenValidationParameters = new TokenValidationParameters
            {
                NameClaimType = "name",
                RoleClaimType = "role"
            }
        });
    #endregion Configure Authentication

    app.UseMvc();
}
Run Code Online (Sandbox Code Playgroud)

登录后,我可以列出与经过身份验证的用户关联的声明:

var claims = User.Claims.OrderBy(c => c.Type).ToList();
Run Code Online (Sandbox Code Playgroud)

在ASP.NET 1.1应用程序中,这提供了以下声明列表:

amr         pwd
aud         test-mule
auth_time   1504529067
c_hash      nouhsuXtd5iKT7B33zxkxg
email       tom@
exp         1504532668
family_name Cobley
given_name  Tom
iat         1504529068
idp         local
iss         https://localhost:44316
name        tom
nbf         1504529068
nonce       6364012...
org         IBX
role        SysAdmin
role        TeleMarketing
role        AccountManager
role        DataManager
role        Member
sid         2091...
sub         1b19...440fa
Run Code Online (Sandbox Code Playgroud)

哪,是我想要/期望的.

我现在尝试使用以下配置在我的第一个ASP.NET Core 2.0应用程序中复制此行为Startup:

public Startup()
{
    JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
}

public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication("Cookies")
        .AddCookie("Cookies", options =>
            {
                options.LoginPath = "/SignIn";
                options.AccessDeniedPath = "/AccessDenied";
            })
        .AddOpenIdConnect("oidc", options =>
            {
                options.SignInScheme = "Cookies";
                options.Authority = "https://localhost:44316";
                options.ClientId = "test-mule";
                options.ClientSecret = "secret";
                options.ResponseType = "code id_token";

                options.SaveTokens = true;
                options.GetClaimsFromUserInfoEndpoint = true;

                options.SignedOutRedirectUri = "https://localhost:44367";
                options.RequireHttpsMetadata = true;

                options.Scope.Clear();
                options.Scope.Add("openid");
                options.Scope.Add("profile");
                options.Scope.Add("name");
                options.Scope.Add("email");
                options.Scope.Add("org");
                options.Scope.Add("role");

                options.TokenValidationParameters = new TokenValidationParameters
                {
                    NameClaimType = "name",
                    RoleClaimType = "role"
                };
            });

    // Add framework services.
    services.AddMvc();
}
Run Code Online (Sandbox Code Playgroud)

作为参考,/Signin控制器动作如下所示:

[Route("/SignIn")]
public IActionResult SignIn(string returnUrl = null)
{
    if (!Url.IsLocalUrl(returnUrl)) returnUrl = "/";

    var props = new AuthenticationProperties
    {
        RedirectUri = returnUrl
    };

    return Challenge(props, "oidc");
}
Run Code Online (Sandbox Code Playgroud)

在此环境中,成功登录后,如果我列出用户的声明,我只会看到Core 1.1中可用内容的一部分:

email       tom@...
family_name Cobley
given_name  Tom
idp         local
name        tom.cobley
sid         2091...
sub         1b19...440fa
Run Code Online (Sandbox Code Playgroud)

我已在客户端和服务器上运行跟踪日志,但无法查看/识别任何不良内容.我还假设它不是一个Identity Server问题,因为它只是一个Open Id Connect服务,应该与任何客户端保持一致?

任何人都可以指出我在哪里出错了吗?

谢谢.

更新

根据MVCutter的建议,我添加了一个`OnUserInformationReceived事件处理程序,因为我注意到并非所有自定义声明都正确映射到用户标识.我不确定为什么这是必要的,或者是否有更好的地方去做,但它似乎给了我现在想要的东西.

private Task OnUserInformationReceivedHandler(
    UserInformationReceivedContext context)
{
    if (!(context.Principal.Identity is ClaimsIdentity claimsId))
    {
        throw new Exception();
    }

    // Get a list of all claims attached to the UserInformationRecieved context
    var ctxClaims = context.User.Children().ToList();

    foreach (var ctxClaim in ctxClaims)
    {
        var claimType = ctxClaim.Path;
        var token = ctxClaim.FirstOrDefault();
        if (token == null)
        {
            continue;
        }

        var claims = new List<Claim>();
        if (token.Children().Any())
        {
            claims.AddRange(
                token.Children()
                    .Select(c => new Claim(claimType, c.Value<string>())));
        }
        else
        {
            claims.Add(new Claim(claimType, token.Value<string>()));
        }

        foreach (var claim in claims)
        {
            if (!claimsId.Claims.Any(
                c => c.Type == claim.Type &&
                     c.Value == claim.Value))
            {
                claimsId.AddClaim(claim);
            }
        }
    }

    return Task.CompletedTask;
}
Run Code Online (Sandbox Code Playgroud)

MVC*_*ter 8

请看下面,我遇到了和你一样的问题.我确定我们缺少一个配置问题,但暂时解析了OnUserInformationReceived事件处理程序中UserInfoEndpoint返回的值.

    public override void ConfigureServices(IServiceCollection services)
    {
        services.AddAuthentication(sharedOptions =>
        {
            sharedOptions.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            sharedOptions.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            sharedOptions.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
        })
            .AddCookie()
            .AddOpenIdConnect(o =>
            {
                o.ClientId = "sss";
                o.ClientSecret = "sss";
                o.RequireHttpsMetadata = false;
                o.Authority = "http://localhost:60000/";
                o.MetadataAddress = "http://localhost:60000/IdSrv/.well-known/openid-configuration";
                o.ResponseType = OpenIdConnectResponseType.IdTokenToken;
                o.CallbackPath = new PathString("/CGI/Home/Index");
                o.SignedOutCallbackPath = new PathString("/CGI/Account/LoggedOut");
                o.Scope.Add("openid");
                o.Scope.Add("roles");
                o.SaveTokens = true;
                o.GetClaimsFromUserInfoEndpoint = true;
                o.Events = new OpenIdConnectEvents()
                {
                    OnUserInformationReceived = (context) =>
                    {
                        ClaimsIdentity claimsId = context.Principal.Identity as ClaimsIdentity;

                        var roles = context.User.Children().FirstOrDefault(j => j.Path == JwtClaimTypes.Role).Values().ToList();
                        claimsId.AddClaims(roles.Select(r => new Claim(JwtClaimTypes.Role, r.Value<String>())));

                        return Task.FromResult(0);
                    }
                };
                o.TokenValidationParameters = new TokenValidationParameters
                {
                    NameClaimType = JwtClaimTypes.Name,
                    RoleClaimType = JwtClaimTypes.Role,
                };
            });
    }
Run Code Online (Sandbox Code Playgroud)

编辑:

我发现有一个名为MapUniqueJsonKey的ClaimsAction属性的扩展方法,这似乎适用于自定义单值键,但对数组类型如炸弹的炸弹......越来越近了

o.ClaimActions.MapUniqueJsonKey("UserType", "UserType");
Run Code Online (Sandbox Code Playgroud)