Search code examples
asp.net-coreasp.net-web-apihttp-status-code-401

Why is my .Net 6 Web API is returning 401


I have a react UI that consumes the Web API. Actually the react UI exists within the same project as the API Controllers. Everything works fine as long as the API Controllers DO NOT have an [Authorize] attribute.

However, with [Authorize], I am seeing the API(s) returning http 401 errors. And this is where my question(s) begin - why 401?

I have done the following things:

  • In Azure AD app, under API Permissions, I added 3 permissions (Azure.Storage user_impersonation, Microsoft.Graph User.Read, and my web API access_as_user).

  • When the UI makes a request to an API, I am adding a header with the Authorization bearer token. Here is the screenshot of that:

    enter image description here

  • I obtain the access token using PublicClientApplication's acquireTokenSilent method

  • I obtain the access token using this scope

Note: in the 401 response, I see this message that suggests the tokens is incorrect. Why is the token bad?

enter image description here

let scopes: string[] = [`${process.env.REACT_APP_CLIENT_ID}/.default`];

Solution

  • It turns out the problem was that I was generating/using the wrong access token.