How to obtain a valid access token so ReactJS UI can access a Web API (same asp.net core project)?

Viewed 32

I have an asp.net core ReactJS + web api (one project). Im trying to obtain an access/authorization token so my UI can access the web api (with the [Authorize] attribute enabled). -- Note that the UI can access my web API if [Authorize] is NOT enabled.

So here is the steps my UI is taking to try to obtain a valid access token:

Option A - Using acquireTokenSilent()

  1. User invokes msal's loginPopup().
  2. After user logs in the msal's accounts has a valid user account.
  3. Using the valid user account, the UI then makes a request to obtain a token via acquireTokenSilent().
  4. This returns a token immediately, BUT unfortunately the access token appears to be invalid.
  5. I verify that the token is invalid by using a simple token validator online: online token validating tool

Option B - Requesting access token via https URL

An alternate approach i tried is setting window.location.assign(url) from the UI itself where the url is:

https://login.microsoftonline.com/<my tenant>/oauth2/v2.0/authorize?
client_id=<my client id>
&response_type=token
&redirect_uri=https%3A%2F%2Flocalhost%3A7070
&scope=https%3A%2F%2Fgraph.microsoft.com%2Fuser.read
&response_mode=fragment
&state=12345
&nonce=678910
&prompt=none
&login_hint=<my email>

The interesting thing with this approach:

  • If i navigate to the url from the browser, i get a proper access token!
  • But if i call this from the UI (using window.location.assign(url)), then the access token is NOT valid (it is about half the size of a valid token).

Option C - Requesting access token via browser (this is not a viable option)

When i navigate to the "https://login.microsoftonline.com...." URL from a browser, i can get an access token as a response. This appears to be a valid token. Although this works fine, i am just curious why it only works when requesting directly from a browser.

My ultimate question is: what am i doing wrong in obtaining an access token which i can use as a Bearer token?

A side question is related to Option B: why does the browser way get me a valid token while the programmatic way does not?

0 Answers
Related