Mohmad sabban
Mohmad sabban

Reputation: 69

Azure B2C throw Access token validation failure. Invalid audience

I'm trying to use Microsoft Azure B2C AD in my react app and using graph SDK to try to get user information in react app.

I'm successfully able to log in using user flow and also get ID-Token after login.

Now when I try to get a user profile using Graph SDK or get a token using the acquireTokenSilent method I'm getting a different error:-

import React from 'react';
import {
  AuthenticatedTemplate,
  UnauthenticatedTemplate,
  useMsal,
} from '@azure/msal-react';
import { loginRequest } from '../authConfig';

import { AuthCodeMSALBrowserAuthenticationProvider } from '@microsoft/microsoft-graph-client/authProviders/authCodeMsalBrowser';
import { InteractionType } from '@azure/msal-browser';
import { Client } from '@microsoft/microsoft-graph-client';

const Home = () => {
  const { instance } = useMsal();
  const { accounts } = useMsal();
  let graphClient = undefined;

  const scopes = [
    'openid',
    'offline_access',
    'https://my-tanent.onmicrosoft.com/my-app/user.read',
  ];

  const authProvider = new AuthCodeMSALBrowserAuthenticationProvider(instance, {
    account: accounts[0],
    scopes,
    interactionType: InteractionType.Popup,
  });

  function ensureClient() {
    graphClient = Client.initWithMiddleware({
      authProvider: authProvider,
    });

    return graphClient;
  }

  async function getUser() {
    ensureClient();

    // Return the /me API endpoint result as a User object
    const user = await graphClient
      .api('/me')
      // Only retrieve the specific fields needed
      .select('displayName,mail,mailboxSettings,userPrincipalName')
      .get();

    console.log(user);
  }

//just to check the token
  const getAccessToken = async () => {
    try {
      const token = await instance.acquireTokenSilent({
        scopes,
      });

      console.log(token);
    } catch (error) {
      console.error(error);
    }
  };

  return (
    <>
      <UnauthenticatedTemplate>
        <h3 className="h3">Login</h3>
        <button onClick={() => instance.loginPopup(loginRequest)}>Login</button>
      </UnauthenticatedTemplate>

      <AuthenticatedTemplate>
        <div className="App">
          <header className="App-header">
            <p>Hello {accounts[0]?.name}!</p>

            <button
              onClick={() =>
                instance.logoutRedirect({ postLogoutRedirectUri: '/' })
              }
            >
              Logout
            </button>

            <button onClick={() => getUser()}>Get User</button>

            <button onClick={() => getAccessToken()}>AcquireTokenSilent</button>
          </header>
        </div>
      </AuthenticatedTemplate>
    </>
  );
};

Graph SDK = Error: Access token validation failure. Invalid audience.

In the second method I'm getting an access token but when I decrypt it, it looks like ID-Token as aud is client-ID:- check This to know more about token

 "exp": 1660120614,
  "nbf": 1660117014,
  "aud": "my-client-id",
  "sub": "df5a1676-74bb-46b6-9116-a5fa125941da",
  "name": "Parteek",
  "postalCode": "246401",
  "tfp": "B2C_1_susi",
  "nonce": "9f13aefb-1a6e-4818-a39e-4f1369ca67d8",
  "scp": "user.read",
  "azp": "93dee6ed-1f87-4f0f-bedb-fd3f1a03b0ed",
  "ver": "1.0",
  "iat": 1660117014

Second TRY with scope change

 const scopes = [
    'openid',
    'offline_access',
    'https://graph.microsoft.com/.default',
  ];

With this scope value:-

Graph SDK Error =Access token is undefined: Received empty access token from PublicClientApplication

acquireTokenSilent: The access token is empty.

Permission on my azure account enter image description here

I don't know why I'm getting these errors is this related to permission or I have implemented it in the wrong way?

Upvotes: 0

Views: 1355

Answers (1)

kavya Saraboju
kavya Saraboju

Reputation: 10859

  1. It looks like you may have to use client credential flow so that the server will call graph api on the behalf of users as it is not possible directly when authenticating against azure ad b2c.
  2. Or create profile edit user flow and then use that flow .

Also please note that: If you register an app in the B2C tenant using supported account type as any identity provider, then you may not be able to perform graph operations using that app. enter image description here

  • You can register Application in Azure AD B2C and associate that with Azure AD with client Id and secret and its details i.e;use client_credentials to call Graph API .
  • Also make sure you have correct api permission like Application.ReadWrite.All ,User.Read.All Directory.Read.All (or) Directory.ReadWrite.All are being granted admin consent.
  • Please make sure you give the API access to Web Application so that the access token is returned: See Request an access token - Azure Active Directory B2C | Microsoft Docs

References:

  1. reactjs - Can a user update their own Azure B2C account details via the Graph API? - Stack Overflow
  2. Azure AD B2C: AcquireTokenSilentAsync returns empty access token - Stack Overflow

Upvotes: 1

Related Questions