bbrinck
bbrinck

Reputation: 1103

@azure/msal-react Call .NET Api immediately after Authentication

I am completely new to React and I was wondering how I can call my .NET Core Backend API automatically after I logged in with the msal-react library?

For the Login I followed the tutorial on Microsoft (https://learn.microsoft.com/en-us/azure/active-directory/develop/tutorial-v2-react) and I am using the @azure/msal-react package.

My app automatically opens the Microsoft Login page when accessing the app due to the MsalAuthenticationTemplate.

But is there a way to listen to an event or something else to immediately call my API after login?

<MsalAuthenticationTemplate interactionType={InteractionType.Redirect}></MsalAuthenticationTemplate>
<AuthenticatedTemplate>
                <div className="App">
                    <header className="App-header">
                        <img src={logo} className="App-logo" alt="logo"/>
                        <p>
                            <ProfileContent></ProfileContent>
                            <SignOutButton></SignOutButton>
                        </p>
                    </header>
                </div>
            </AuthenticatedTemplate>

So what I want to achieve:

  1. Login via MSAL (DONE)
  2. Call my Backend API to retrieve user permissions: Where and How?

Upvotes: 0

Views: 1010

Answers (1)

Rutha
Rutha

Reputation: 805

You must use useeffect to automatically call your API after logging in.

const [userData, setUserData] = useState([]);

 useEffect(() => {

   axios

     .get("your_api_url/user/")

     .then(({ data }) => {

       setUserData(data);

     })

     .catch((err) => console.log(err));

 }, []);

Read more here in additional to the tutorial you mentioned above.

https://github.com/Azure-Samples/ms-identity-javascript-react-spa

Upvotes: 1

Related Questions