从身份服务器4重定向URL的行为不符合预期,并且“无法将Newtonsoft.Json.Linq.JArray转换为Newtonsoft.Json.Linq.JToken".错误 [英] Redirecting url from Identity server 4 is not behaving as expected and "Cannot cast Newtonsoft.Json.Linq.JArray to Newtonsoft.Json.Linq.JToken" error

查看:742
本文介绍了从身份服务器4重定向URL的行为不符合预期,并且“无法将Newtonsoft.Json.Linq.JArray转换为Newtonsoft.Json.Linq.JToken".错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

注意:解决了重定向问题之后,我遇到了另一个问题,即出现错误无法将Newtonsoft.Json.Linq.JArray转换为Newtonsoft.Json.Linq.JToken".因此,在我的回答中,我为两者都提供了正确的解决方案.

Note : After resolving the redirection issue i had an another issue that is getting an error "Cannot cast Newtonsoft.Json.Linq.JArray to Newtonsoft.Json.Linq.JToken". So in my answer I have provided the correct solution for both.

我有身份服务器项目和客户端项目,所有工作都可以通过身份验证,没有任何问题,甚至可以重定向到正确的客户端url,但url例如:"

I have identity server project and the client project, everything works up to authentication without any issues and even it redirects to the correct client url but the url ex : "https://localhost:44309/signin-oidc" gives the blank page.

注意:为身份服务器和客户端应用程序启用了SSl.

Note : SSl enabled for Identity Server and Client application.

它正在按预期方式对用户进行身份验证,如下面的屏幕快照所示. 我的身份服务器包含以下客户端配置值.

It is authenticating the user as expected as you can see below in the screen shot. My Identity server contains the following config values for client.

                // OpenID Connect hybrid flow and client credentials client (MVC)
            new Client
            {
                ClientId = "mvc",
                ClientName = "MVC Client",
                AllowedGrantTypes = GrantTypes.HybridAndClientCredentials,
                ClientSecrets =
                {
                    new Secret("secret".Sha256())
                },

                RedirectUris = { /*"http://localhost:5002/signin-oidc",*/"https://localhost:44309/signin-oidc" },
                PostLogoutRedirectUris = { /*"http://localhost:5002/signout-callback-oidc",*/"https://localhost:44309/signout-callback-oidc" },

                AllowedScopes = 
                {
                    IdentityServerConstants.StandardScopes.OpenId,
                    IdentityServerConstants.StandardScopes.Profile,
                    //"api1"
                },
                AllowOfflineAccess = true
            }

startup.cs如下.

The startup.cs is as follows.

        public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();

        // configure identity server with in-memory stores, keys, clients and scopes
        services.AddIdentityServer()
            .AddDeveloperSigningCredential()
            .AddInMemoryIdentityResources(Config.GetIdentityResources())
            .AddInMemoryApiResources(Config.GetApiResources())
            .AddInMemoryClients(Config.GetClients())
            .AddTestUsers(Config.GetUsers());

        services.AddAuthentication()
            //.AddGoogle("Google", options =>
            //{
            //    options.SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme;

            //    options.ClientId = "434483408261-55tc8n0cs4ff1fe21ea8df2o443v2iuc.apps.googleusercontent.com";
            //    options.ClientSecret = "3gcoTrEDPPJ0ukn_aYYT6PWo";
            //})
            .AddOpenIdConnect("oidc", "dataVail Login", options =>
            {
                options.SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme;

                options.SignOutScheme = IdentityServerConstants.SignoutScheme;

                options.Authority = "https://login.microsoftonline.com/d0e2ebcc-0961-45b2-afae-b9ed6728ead7";//"https://demo.identityserver.io/";
                options.ClientId = "f08cc131-72da-4831-b19d-e008024645e4";
                options.UseTokenLifetime = true;
                options.CallbackPath = "/signin-oidc";
                options.RequireHttpsMetadata = false;

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

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseForwardedHeaders(new ForwardedHeadersOptions
        {
            ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
        });

        app.Use(async (context, next) =>
        {
            context.Request.Scheme = "https";
            await next.Invoke();
        });
        app.UseIdentityServer();

        app.UseStaticFiles();
        app.UseMvcWithDefaultRoute();
    }

这是我的客户端应用程序的startup.cs

Here is the startup.cs for my client app

        public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();

        JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

        services.AddAuthentication(options =>
        {
            options.DefaultScheme = "Cookies";
            options.DefaultChallengeScheme = "oidc";
        })
            .AddCookie("Cookies")
            .AddOpenIdConnect("oidc", options =>
            {
                options.SignInScheme = "Cookies";

                options.Authority = "https://localhost:44392/";
                options.RequireHttpsMetadata = false;

                options.ClientId = "mvc";
                options.ClientSecret = "secret";
                options.ResponseType = "code id_token";

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

                //options.Scope.Add("api1");
                options.Scope.Add("offline_access");

            });
    }

任何人都可以尝试帮助我解决这个问题.

Can anyone please try helping me to sort this out.

推荐答案

我可以借助Identity Server 4人员解决此问题. 如果有人遇到这个问题,这里就是解决方案.

I could resolved this with the help of Identity Server 4 folks. If any one come across this problem here is the solution.

我没有在配置客户端MVC管道"中添加"UseAuthentication".因此,添加完后,我按照预期进行了重定向,然后又遇到了另一个问题,如下所示.

I missed adding "UseAuthentication" in Configure the client MVC pipeline. So after adding that i was redirected as expected and then I had another issue as shown below.

System.InvalidCastException: Cannot cast Newtonsoft.Json.Linq.JArray to Newtonsoft.Json.Linq.JToken. at Microsoft.AspNetCore.Authentication.RemoteAuthenticationHandler1.d__12.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter1.GetResult() at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.<Invoke>d__6.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.<Invoke>d__7.MoveNext()

在使用AzureAD作为外部身份验证提供程序将我的应用程序连接到IdentityServer4时,遇到了此异常.我的应用程序使用混合流连接到IdentityServer4.我已正确重定向到Azure,登录,并且正确发出了代码和id_tokens.调用userInfo端点时,在我的应用程序中引发了此异常.

I'm getting this exception while connecting my application to IdentityServer4 with AzureAD as external authentication provider. My application is using Hybrid flow to connect to IdentityServer4. I get properly redirected to Azure, login, and code and id_tokens are properly issued. This exception is raised in my application when userInfo endpoint is invoked.

为了解决这个问题,我不得不删除名称两次的索赔.

In order resolve this I had to remove the claim which has the name twice.

我确认AAD发送了两个名称声明.删除其中之一即可解决问题.

I confirmed that AAD sends two name claims. Removing one of them resolved the problem.

var namesClaim = externalUser.FindFirst(ClaimTypes.Name) ??
                             throw new Exception("Unknown names");

if (namesClaim!=null)
{
    claims.Remove(namesClaim);
}

希望这可能对某人有所帮助.

Hope this may help someone.

这篇关于从身份服务器4重定向URL的行为不符合预期,并且“无法将Newtonsoft.Json.Linq.JArray转换为Newtonsoft.Json.Linq.JToken".错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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