Is It Necessary to Have So Much Code to Get an Access Token Throughout Your React App?

Andrew 1 Reputation point
2022-03-25T23:20:40.4+00:00

Hi. Reading through "https://learn.microsoft.com/en-us/azure/active-directory/develop/tutorial-v2-react#acquire-a-token" and you'll notice that in order to call an API, you need to get a token (make sense), however, think of this at scale. I was using a previous provider and was able to get a token inside of a (service) class in react, but now switching to MSAL, it seems that I have to use similar code as below in every single component, every single time I call an API...

 instance.acquireTokenSilent(request).then((response) => {  
            callMsGraph(response.accessToken).then(response => setGraphData(response));  
        }).catch((e) => {  
            instance.acquireTokenPopup(request).then((response) => {  
                callMsGraph(response.accessToken).then(response => setGraphData(response));  
            });  
        });  

I tried looking online, but I can't seem to find any solutions to avoid this. Is it not possible to do this OUTSIDE of every component? If the library ever changes, I wouldn't want to go into every component that calls an API and change all of this. Note, I am also oversimplifying the above code... it's much longer in a real life example.

Azure
Azure
A cloud computing platform and infrastructure for building, deploying and managing applications and services through a worldwide network of Microsoft-managed datacenters.
1,054 questions
Microsoft Entra ID
Microsoft Entra ID
A Microsoft Entra identity service that provides identity management and access control capabilities. Replaces Azure Active Directory.
20,151 questions
{count} votes

1 answer

Sort by: Most helpful
  1. James Hamil 22,886 Reputation points Microsoft Employee
    2022-04-04T19:33:06.463+00:00

    Hi @Andrew , I was given a document showing how to require an access token outside of a react component.

    189894-react.png

    Please let me know if this helps or if you have any questions.

    If this answer helped you please mark it as "Verified" so other users can reference it.

    Thank you,
    James