How to pass MSAL access token to react elastic search App connector

315 Views Asked by At

AM trying to get a access token for MSAL to pass to our backend API(that eventually calls APP Search). As the access token is from msal promise i cannot initialize the token somewhere globally and access with in other function. is there a way to wait until the promise completed ?

Here is some code:

export default function App() {

  const isAuthenticated = useIsAuthenticated();
  const {instance, accounts, inProgress} = useMsal();

  const { hostIdentifier, searchKey, endpointBase, engineName } = getConfig();

  if (!isAuthenticated && inProgress === InteractionStatus.None) {
    instance.loginRedirect(loginRequest).catch(e => {
      console.error(e);
    });
  }


  const connector= null;
  if( accounts[0]){
    const request = {
    ...{scopes:['api://.....']},
    account: accounts[0]
    };
    console.log('Before access token');
    getAccessToken(request);
    //console.log(`After access token ${accessToken}`);
  }  
       let config;
        async function getAccessToken(request){
        const accessTokenPromise = await instance.acquireTokenSilent(request);
          const searchKey = accessTokenPromise.accessToken;
           const connector = new AppSearchAPIConnector({
            searchKey,
            engineName,
            hostIdentifier,
            endpointBase,
          });
          console.log('After COnnector'+connector);
          
    
           config = {
            searchQuery: {
              facets: buildFacetConfigFromConfig(),
              ...buildSearchOptionsFromConfig(),
            },
            autocompleteQuery: buildAutocompleteQueryConfig(),
            apiConnector: connector,
            alwaysSearchOnInitialLoad: false,
          };  
        }
     
      return (
        <PageLayout>
          <AuthenticatedTemplate>
            <SearchProvider config={config}>
              <WithSearch
                mapContextToProps={({ wasSearched }) => ({ wasSearched })}
                 ........

with this code , am getting below error:

Events.js:16 Uncaught No onSearch handler provided and no Connector provided. You must configure one or the other.

any idea , on how to pass access token to App connector ?

1

There are 1 best solutions below

0
On

Yes, there is a way to wait until the promise is complete. You can use await keyword before the promise and when you use the await keyword you must add the async keyword in function declaration because adding async keyword is required when you use await keyword before the promise code.

When you complete the promise and use the await keyword then you can store the access token in some variable and lastly send it to the app connector.