Bearer error - invalid_token - The signature key was not found

Viewed 46773

I have an Angular 7 application interfacing with a .Net Core 2.2 API back-end. This is interfacing with Azure Active Directory.

On the Angular 7 side, it is authenticating properly with AAD and I am getting a valid JWT back as verified on jwt.io.

On the .Net Core API side I created a simple test API that has [Authorize] on it.

When I call this method from Angular, after adding the Bearer token, I am getting (as seen in Chrome Debug Tools, Network tab, "Headers"):

WWW-Authenticate: Bearer error="invalid_token", error_description="The signature key was not found"

With a HTTP/1.1 401 Unauthorized.

The simplistic test API is:

    [Route("Secure")]
    [Authorize]
    public IActionResult Secure() => Ok("Secure works");

The Angular calling code is also as simple as I can get it:

    let params : any = {
        responseType: 'text',
        headers: new HttpHeaders({
            "Authorization": "Bearer " + token,
            "Content-Type": "application/json"
        })
    }

    this.http
        .get("https://localhost:5001/api/azureauth/secure", params)
        .subscribe(
            data => { },
            error => { console.error(error); }
        );

If I remove the [Authorize] attribute and just call this as a standard GET request from Angular it works fine.

My Startup.cs contains:

        services
            .AddAuthentication(AzureADDefaults.AuthenticationScheme)
            .AddAzureADBearer(options => this.Configuration.Bind("AzureAd", options));

The options are all properly set (such as ClientId, TenantId, etc) in the appsettings.json and options here is populating as expected.

9 Answers

I was facing the same issue. i was missing the authority..make sure authority and api name is correct now this code in configure services in startup file works for me:

services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
                .AddIdentityServerAuthentication( x =>
                {
                    x.Authority = "http://localhost:5000"; //idp address
                    x.RequireHttpsMetadata = false;
                    x.ApiName = "api2"; //api name
                });

I had a unique scenario, hopefully this will help someone.

I was building an API which has Windows Negotiate authentication enabled (.NET Core 5.0, running from IIS) and unit testing the API using the CustomWebApplicationFactory (see documentation for CustomWebApplicationFactory) through XUnit which does not support Negotiate authentication.

For the purposes of unit testing, I told CustomWebApplicationFactory to use a "UnitTest" environment (ASPNETCORE_ENVIRONMENT variable) and specifically coded logic into my application Startup.cs file to only add JWT authentication for the "UnitTest" environment.

I came across this error because my Startup.cs configuration did not have the signing key I used to create the token (IssuerSigningKey below).

if (_env.IsEnvironment("UnitTest"))
{
  // for unit testing, use a mocked up JWT auth, so claims can be overridden
  // for testing specific authentication scenarios
  services.AddAuthentication()
    .AddJwtBearer("UnitTestAuth", opt =>
    {
      opt.Audience = "api://local-unit-test";
      opt.RequireHttpsMetadata = false;
      opt.TokenValidationParameters = new TokenValidationParameters()
      {
        ClockSkew = TokenValidationParameters.DefaultClockSkew,
        ValidateAudience = true,
        ValidateIssuer = true,
        ValidateIssuerSigningKey = true,
        ValidAudience = "api://local-unit-test",
        ValidIssuer = "unit-test",
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("abcdefghijklmnopqrstuvwxyz123456"))
      };
    });
} else {
  // Negotiate configuration here...
}

Regardless of the ValidateIssuerSigningKey being true or false, I still received the "invalid_token" 401 response, same as the OP. I even tried specifying a custom IssuerSigningKeyValidator delegate to always override the result, but did not have luck with that either.

WWW-Authenticate: Bearer error="invalid_token", error_description="The signature key was not found"

When I added IssuerSigningKey to the TokenValidationParameters object (of course matching the key I used when generating the token in my unit test), everything worked as expected.

There could be two reason:

  1. You might have missed registering service :
services.AddAuthorization(auth =>
            {
                auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder()
                    .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme‌​)
                    .RequireAuthenticatedUser().Build());
            });

Or 2. You might have missed assigning value to key "IssuerSigningKey" as shown below

validate.TokenValidationParameters = new TokenValidationParameters()
                                        {
                                            ValidateAudience = true,
                                            ValidAudience = "Audience",
                                            ValidateIssuer = true,
                                            ValidIssuer = "http://localhost:5000",
                                            RequireExpirationTime = false,
                                            ValidateIssuerSigningKey = true,
                                            IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("abcdefghi12345"))

                                        });

This resolved my problem

My problem was that I needed to set the ValidIssuer option in the AddJwtBearer TokenValidationParameters, in addition to the authority

For example:

services.AddAuthentication("Bearer")
        .AddJwtBearer(options =>
        {
            options.Audience = "My Audience";
            options.Authority = "My issuer";
            options.TokenValidationParameters = new TokenValidationParameters {
                ValidateIssuerSigningKey = true,
                ValidateLifetime = true,
                ValidateIssuer = true,
                ValidIssuer = "Also My Issuer",    //Missing line here
                ValidateAudience = true
            };
        });

My Core API uses different services configuration (and it works :)):

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
  .AddJwtBearer(options =>
  {
    Configuration.Bind("JwtBearer", options);
  }

Are you sure you are passing an access token and not an id_token? Is the aud claim present in the token exactly the same as the clientid your API is configured with? You may want to add some events to your options to see what you are receiving and where the validation fails.

  1. Verify the values that you send for request the jwt token (eg: grant_type, client_secret, scope, client_id, etc)
  2. Ensuere that you are using the appropiate token. That's all!

Here is my mistake: I was using Postman, and request a token and set it to a varibale "Var_Token1":

pm.environment.set("Var_Token1", pm.response.json().access_token);

But when I need to use the token for my final request, I selected and use the wrong token (Var_Token2):

Authorization: Bearer {{Var_Token2}}

For me, this error was coming because the URL in appsettings.json was incorrect. I fixed it and it's working fine now.

This can also happen if you are using a different SignedOutCallbackPath/SignUpSignInPolicyId policy id than which is being passed in the token as tfp/acr.

I had this issue, and it was caused by jwtOptions.Authority not being set in config.

If you are using:

services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
            .AddIdentityServerAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme,

And jwtOptions.Authority is set to null or "" you can get this error message.

Related