azureauthenticationazure-active-directoryasp.net-core-webapiazure-ad-msal

How to debug Bearer error="invalid_token"


We are building an application with a SPA front end and an API backend.

We are using the MSAL authentication library, the frontend and backend are registered as applications in Azure AD.

We get a HTTP 401 error.

To try and debug the problem, we have taken the token from the SPA application, and put it in jwt.io, it looks fine. We have also tried sending the request from Postman, with the bearer token. Still same problem.

Is there a way to find out in what way the token is invalid?


Solution

  • A simple check to get some clue why the token is not accpted, is to set this flag to true in AddJwtBearer:

    .AddJwtBearer(opt =>
    {
        opt.IncludeErrorDetails = true;
        ...
    

    Doing so, will include why it was rejected in the WWW-Authenticate response header:

    HTTP/1.1 401 Unauthorized
    Date: Sun, 02 Aug 2020 11:19:06 GMT
    WWW-Authenticate: Bearer error="invalid_token", error_description="The signature is invalid"
    

    The second step is to check the logs from the AddJwtBearer handler.

    To complement this answer, I wrote a blog post that goes into more detail about this topic: Troubleshooting JwtBearer authentication problems in ASP.NET Core