37

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.

Patrick
  • 5,526
  • 14
  • 64
  • 101
  • 1
    How did you acquire the access token? Sounds like the token *might* be a Microsoft Graph API token. – juunas Oct 26 '19 at 08:33
  • @juunas I have an application registered in Azure AD and have a ClientID, TenantID, and app-specific secret that are being passed to the proper endpoints as provided in the Azure management console. It's a valid JWT. It looks like this may end up being a conflict with an existing authorization scheme in the application. Working on that angle. – Patrick Oct 26 '19 at 12:50
  • 5
    Any luck on this? I am also facing the same issue. – Rohith Gopi Jun 21 '20 at 18:23
  • 1
    @PatrickI had same issue ? Did you find a solution ? – Antoine V Jul 12 '20 at 20:32

10 Answers10

19

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
                });
Muhammad Maaz
  • 423
  • 5
  • 12
  • 1
    Adding `Authority` saved my day! I use `services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(x => { x.Authority = ""; })` and it does not work without `Authority`. – ivanblin Jul 28 '20 at 10:04
  • 1
    Isn't that using IdentityServer though on top of the JWT Bearer settings? – djangojazz Sep 10 '21 at 18:11
7

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.

4e 69 63 6b
  • 206
  • 2
  • 8
3

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
            };
        });
AvahW
  • 2,083
  • 3
  • 24
  • 30
2

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

Omkar Manjare
  • 53
  • 1
  • 5
1

The key when we generate the token:

var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("this is my custom Secret key for authentication"));

Should be the same on DI:

IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("this is my custom Secret key for authentication"))
Jeremy Caney
  • 7,102
  • 69
  • 48
  • 77
0

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.

Konrad Viltersten
  • 36,151
  • 76
  • 250
  • 438
Marc
  • 953
  • 7
  • 17
  • Access token is verified fine on jwt.io ... pasting my secret gets me a "Signature Verified". Decodes properly there. Perhaps I should switch to trying this with `AddJwtBearer` ... I am using Microsoft's library with `AddAzureADBearer` ... I assume options are the same. Do you have anything specified other than the default `[Authorize]` attribute on the secure API? – Patrick Oct 25 '19 at 21:10
  • 1
    No, just Authorize. I assume you mean 'pasting the public key', not 'pasting my secret', right? A token may have valid signature but not be for the API - is the aud claim same as what your API expects? – Marc Oct 25 '19 at 21:18
0
  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}}
Darío León
  • 680
  • 7
  • 7
0

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

Ashish Deora
  • 179
  • 1
  • 9
0

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.

chaitanyasingu
  • 121
  • 1
  • 13
-2

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.

ompao
  • 28
  • 1
  • 6