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.

JWT Signature validation fails in .NET Core app targetting .NET Framework 4.7.1

See original GitHub issue

From @fabiodaniele on February 13, 2018 15:55

Hi, I was having an issue trying to authenticate users to a .NET Core WebAPI using a JWT bearer token generated by a WSO2 Identity Server.

The project targets .NET Framework 4.7.1 and references Microsoft.AspNetCore.Authentication.JwtBearerToken.

At first, I thought it was an issue related to my WSO2 IS configuration.

Then, I found this article: https://www.jerriepelser.com/blog/manually-validating-rs256-jwt-dotnet/ and tried to execute the same code found there in a new .NET Core Console app: it worked!

So, I thought: “it maybe an issue of my WebAPI project”.

I then made a few tries with two different brand new .NET Core WebAPI projects, one targetting .NET Core 2.0 and the other one targetting .NET Framework 4.7.1, using the same startup code in both.

Here is the code:

      // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            IConfigurationManager<OpenIdConnectConfiguration> configurationManager = new ConfigurationManager<OpenIdConnectConfiguration>($"{Configuration["OpenId:Authority"]}/.well-known/openid-configuration", new OpenIdConnectConfigurationRetriever());
            OpenIdConnectConfiguration openIdConfig = configurationManager.GetConfigurationAsync(CancellationToken.None).Result;

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(options =>
                {
                    options.IncludeErrorDetails = true;
                    options.TokenValidationParameters.ValidateIssuer = true;
                    options.TokenValidationParameters.ValidateAudience = true;
                    options.TokenValidationParameters.ValidateIssuerSigningKey = true;
                    options.TokenValidationParameters.ValidIssuer = Configuration["OpenId:Issuer"];
                    options.TokenValidationParameters.ValidAudiences = new[] { Configuration["OpenId:Audience"] };
                    options.TokenValidationParameters.IssuerSigningKeys = openIdConfig.SigningKeys;
                });

            services.AddMvc();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseAuthentication();

            app.UseMvc();
        }

I decorated the default ValuesController with the Authorize attribute and tried to invoke it via Postman, with a new JWT token obtained from the WSO2 IS.

The results are different:

  • the app targetting .NET Core 2.0 simply works, giving me the expected JSON result from the Action invoked
  • the one targetting .NET Framework 4.7.1 replies with Bearer error=“invalid_token”, error_description=“The signature is invalid”

So the question is: is this the expected behavior or is it a bug?

Thanks in advance.

Copied from original issue: aspnet/Security#1649

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Reactions:1
  • Comments:48 (20 by maintainers)

github_iconTop GitHub Comments

7reactions
EkwofiePraxcommented, Feb 11, 2020

@brentschmaltz I’m being faced with similar issue that’s been reported in here. I have tried all the suggestions but I’m getting no where.

Am I missing something?

I have added a snapshot of my code

IDX10511: Signature validation failed. Keys tried: 'Microsoft.IdentityModel.Tokens.X509SecurityKey

I’m using MSAL interceptor in Angular 8 code to send access token to the server “C# .NET core 3.1”.

//***************************************************************************************************** public static JwtSecurityToken Validate(string token) {

        string stsDiscoveryEndpoint = "https://login.microsoftonline.com/eddf9e42-9a7f-4639-8042-***********/.well-known/openid-configuration?appid=7391aebb-1a35-4ad7-8166-xxxxxxxxxx"; // https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration";
        
        ConfigurationManager<OpenIdConnectConfiguration> configManager = new ConfigurationManager<OpenIdConnectConfiguration>(stsDiscoveryEndpoint, new OpenIdConnectConfigurationRetriever());
        OpenIdConnectConfiguration config = configManager.GetConfigurationAsync().Result;


        TokenValidationParameters validationParameters = new TokenValidationParameters
        {
            ValidateAudience = false,
            ValidIssuer = config.Issuer,
            IssuerSigningKeys = config.SigningKeys,
            ValidateIssuerSigningKey = false,
            ValidateIssuer = true,
            ValidateActor = false,
            ValidateLifetime = true
        };

        IdentityModelEventSource.ShowPII = true;
        JwtSecurityTokenHandler tokendHandler = new JwtSecurityTokenHandler();

        SecurityToken jwt;
        var result = tokendHandler.ValidateToken(token, validationParameters, out jwt);
        return jwt as JwtSecurityToken;
    }

/* IDX10511: Signature validation failed. Keys tried: 'Microsoft.IdentityModel.Tokens.X509SecurityKey, KeyId: ‘HlC0R12skxNZ1WQwmjOF_6t_tDE’, InternalId: ‘91ea3222-c9ea-4aa4-a515-83f2b195f989’. , KeyId: HlC0R12skxNZ1WQwmjOF_6t_tDE '. kid: ‘HlC0R12skxNZ1WQwmjOF_6t_tDE’. Exceptions caught: ‘’. token: ‘{“alg”:“RS256”,“typ”:“JWT”,“nonce”:“19yszC4xPiqhnbI587HT_08QFjftE7J3qE8F9xw_sqY”,“x5t”:“HlC0R12skxNZ1WQwmjOF_6t_tDE”,“kid”:“HlC0R12skxNZ1WQwmjOF_6t_tDE”}.{“aud”:“00000003-0000-0000-c000-000000000000”,“iss”:“https://sts.windows.net/eddf9e42-9a7f-4639-8042-110281cf41a2/",“iat”:1581413726,“nbf”:1581413726,“exp”:1581417626,“acct”:0,“acr”:“1”,“aio”:“42NgYLgWut8sY6dad5urN6/nxuP8P7Z6ZXr1Wwl355xibZu8nxMA”,“amr”:[“pwd”],“app_displayname”:“SoraxWeb”,“appid”:“7391aebb-1a35-4ad7-8166-xxxxxxxx”,“appidacr”:“0”,“family_name”:“kwofie”,“given_name”:“Ernest”,“ipaddr”:“212.161.81.38”,“name”:"Exxxx kxxxx”,“oid”:“9f9efce3-37e5-4018-8035-7ffc6323e827”,“onprem_sid”:“S-1-5-21-3789744388-407605227-1228871550-7770”,“platf”:“3”,“puid”:“100320003319DDA9”,“scp”:“Mail.Send openid profile User.Read User.ReadWrite email”,“sub”:“LhkC5zL_zJm-MZBjJDYCz5Asjm7Nwg9tHUehKVSH40A”,“tid”:“eddf9e42-9a7f-4639-8042-*************”,“unique_name”:“Exxxx.kxxxx@xxxx.com”,“upn”:“Exxxx.kxxxx@xxxxx.com”,“uti”:“3RsEnJpEokmZb-Y3MwJzAA”,“ver”:“1.0”,“xms_st”:{“sub”:“zSJz0JM6iB6SRwxi1ZZm_1F__aYqHhEDtjb5qkege_o”},“xms_tcdt”:1443089411}’. */

Startup.cs public void ConfigureServices(IServiceCollection services) { services.AddCors(options => options.AddPolicy(MyAllowSpecificOrigins, builder => { builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader(); })); services.AddControllers(); }

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

        app.UseRouting();
        app.UseCors(MyAllowSpecificOrigins);
        app.UseHttpsRedirection();
        app.UseAuthorization();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
3reactions
mathew-weavercommented, Jan 9, 2019

I am running into the same error [IDX10511: Signature validation failed.] when trying to validate a JWT AccessToken obtained from https://login.microsoftonline.com/common. If I obtain the AccessToken via ADAL.NET (Microsoft.IdenityModel.Clients.ActiveDirectory v3.9.30421) then it validates successfully. However, if I obtain the AccessToken via MSAL.NET (Microsoft.Identity.Client v2.6.2) then it fails with the IDX10511 exception.

In both cases, I am using System.IdentityModel.Tokens.Jwt v5.3.0 to validate. Also, in both cases, I am validating using signing keys obtained from https://login.microsoftonline.com/common/.well-known/openid-configuration (aka https://login.microsoftonline.com/common/discovery/keys) using Microsoft.IdentityModel.Protocols.OpenIdConnect.OpenIdConnectConfigurationRetriever.

Any ideas why the ADAL.NET-obtained token validates successfully but the MSAL.NET-obtained token fails signature validation?

[update] This post helped me resolve my issue. As explained in that post by @brentschmaltz, the AccessToken obtained via MSAL.NET has an audience of https://graph.windows.net. Graph access tokens contain a nonce and require special processing during validation. As @brentschmaltz noted, we should not really be trying to validate Graph access tokens anyway. In my use case, I do not need to access Graph; so instead of using the AccessToken (which will not validate), I switch to using the IdToken. The IdToken has an audience of my registered application’s clientId (not https://graph.windows.net) and it does validate as expected.

Read more comments on GitHub >

github_iconTop Results From Across the Web

JWT validation works in .NET Core, fails in .NET Framework
NET Framework 4.7.2; there, it throws an exception: Microsoft.IdentityModel.Tokens.SecurityTokenInvalidSignatureException: 'IDX10503: Signature ...
Read more >
how do I solve the invalid signature error in jwt ...
I am getting invalid signature error.I tried everything but the error is not solving.What can I do? ASP.NET Core.
Read more >
Access Token validating fails with JWTSecurityTokenHandler
I try to validate an access token, which I get from Azure. ... Token validating fails with JWTSecurityTokenHandler - Signature invalid.
Read more >
Port from .NET Framework to .NET 7 - .NET Core
This article provides an overview of what you should consider when porting your code from .NET Framework to .NET (formerly named .NET Core)....
Read more >
Secure Your ASP.NET Web Forms Application with OpenID ...
This tutorial walks you through securing your ASP.NET Web Forms application with OpenID Connect and Okta.
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