question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Cannot cast Newtonsoft.Json.Linq.JArray to Newtonsoft.Json.Linq.JToken

See original GitHub issue

I use Identityserver4 and try to connect with a .ner core 2.0 mvc app to Open Id authentication My Configuration is here

            services.AddAuthentication(options =>
            {
                options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
            })
            .AddCookie()
            .AddOpenIdConnect(options =>
            {
                options.ClientId = "clientId";
                options.ClientSecret = "secret";
                options.Authority = Configuration["IdentityServerAddress"];
                options.SignedOutRedirectUri = Configuration["IdentityServerManagerAddress"];
                options.ResponseType = "code id_token";
                options.Scope.Add("openid");
                options.Scope.Add("roles");
                options.Scope.Add("profile");
                options.Scope.Add("offline_access");
                options.Scope.Add("phone_number"); 
                options.SignInScheme = "Cookies";
                options.GetClaimsFromUserInfoEndpoint = true;
                options.SaveTokens = true;
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    NameClaimType = "name",
                    RoleClaimType = "role"
                };
            });

but I got this error :

InvalidCastException: Cannot cast Newtonsoft.Json.Linq.JArray to Newtonsoft.Json.Linq.JToken.
Microsoft.AspNetCore.Authentication.RemoteAuthenticationHandler+<HandleRequestAsync>d__12.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Runtime.CompilerServices.TaskAwaiter.GetResult()
Microsoft.AspNetCore.Authentication.AuthenticationMiddleware+<Invoke>d__6.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware+<Invoke>d__7.MoveNext()

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Comments:24 (12 by maintainers)

github_iconTop GitHub Comments

6reactions
mstrong64commented, Jan 30, 2018

In my case the problem relates to IDS4 returning the role claim as an array when the user has multiple roles (see http://docs.identityserver.io/en/release/endpoints/userinfo.html). This causes an exception when trying to get the role into the Principal via:

oidcOptions.ClaimActions.MapUniqueJsonKey(JwtClaimTypes.Role, JwtClaimTypes.Role);

I’ve got around this as follows:

oidcOptions.Events = new OpenIdConnectEvents()
{
  OnUserInformationReceived = async context =>
  {
    // IDS4 returns multiple claim values as JSON arrays, which break the authentication handler
    if (context.User.TryGetValue(JwtClaimTypes.Role, out JToken role))
    {
      var claims = new List<Claim>();
      if (role.Type != JTokenType.Array) {
        claims.Add(new Claim(JwtClaimTypes.Role, (string)role));
      }
      else  {
        foreach (var r in role)
          claims.Add(new Claim(JwtClaimTypes.Role, (string)r));
      }
      var id = context.Principal.Identity as ClaimsIdentity;
      id.AddClaims(claims);
    }
  ...
}
1reaction
Tratchercommented, Aug 25, 2017
Read more comments on GitHub >

github_iconTop Results From Across the Web

c# - Cannot cast Newtonsoft.Json.Linq.JArray to ...
The error about converting from JArray to JToken likely occurs because DeserializeObject is attempting to directly deserialize to JObject , ...
Read more >
Unable to cast object of type 'Newtonsoft.Json.Linq. ...
Dear All, While running the below code, i am getting Unable to cast object of type 'Newtonsoft.Json.Linq.JProperty' to type 'Newtonsoft.
Read more >
[Solved]-Getting 'Cannot cast Newtonsoft.Json.Linq.JObject to ...
Coding example for the question Getting 'Cannot cast Newtonsoft.Json.Linq.JObject to Newtonsoft.Json.Linq.JToken' when retrieving items from JSON-LINQ,C#.
Read more >
Cannot cast Newtonsoft.Json.Linq.JArray to ...
Getting the below error on the callback to admin. System.Exception: An error was encountered while handling the remote login. ---> System.
Read more >
Argument 1: cannot convert from 'Newtonsoft.Json.Linq. ...
error CS1503: Argument 1: cannot convert from 'Newtonsoft. Json. Linq. JToken' to 'string' : r/csharp.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found