Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.8k views
in Technique[技术] by (71.8m points)

c# - Bearer error - invalid_token - The signature key was not found

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
                });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...