1

I am calling backend-api from frontend, for authentication purpose I am using azure-ad onfronted and backend, when I fetch API for first time, request gets authenticated but for next api call, fronted is calling method

  const checkAccessTokenandGenerateIfExpired = () => {
    const account = msalInstance.getAllAccounts()[0];
    const accessTokenRequest = {
      scopes: ["User.Read"],
      account: account
    }
    msalInstance.acquireTokenSilent(accessTokenRequest).then(function (accessTokenResponse) {
      let accessToken = accessTokenResponse.accessToken;
      localStorage.removeItem("token");
      localStorage.setItem("token", accessToken);
      return toString(accessToken)
    }).catch(function (error) {
      if (error instanceof InteractionRequiredAuthError) {
        msalInstance.acquireTokenPopup(accessTokenRequest).then(function (accessTokenResponse) {
          console.log(accessTokenResponse)
          let accessToken = accessTokenResponse.accessToken;
          localStorage.removeItem("token");
          localStorage.setItem("token", accessToken);
        }).catch(function (error) {
          console.log(error);
        });
      }
      console.log(error);
    });

  };

Backend returns : - authentication failed

Don't know what's the error in above code, because above block of code is generating new token during second API call

Sanket Patil
  • 807
  • 1
  • 11
  • 19
  • 1
    It's because you are using Microsoft Graph API scope in your accessTokenRequest (User.Read). You need to use a scope for your API, not MS Graph. You can define them in the "Expose an API" page of your API app registration. – juunas Feb 16 '22 at 12:53

1 Answers1

3

It's because you are using Microsoft Graph API scope in your accessTokenRequest (User.Read). You need to use a scope for your API, not MS Graph. You can define them in the "Expose an API" page of your API app registration.

juunas
  • 54,244
  • 13
  • 113
  • 149
  • Even better, specify the scope to be 'openid'. You can see my detailed answer here: https://stackoverflow.com/a/76873146/10030693 – Gilbert Aug 10 '23 at 06:38