I have some trouble understanding the MSAL authentication and authorization. I have a single page app developed in React. I have setup the MSAL Azure SSO authentication by registering the web app on the Azure AD. Now, I have a Web API (in .Net Core) which is running on a separate app service. How do I integrate the authentication from my React app to the Web API?
Few questions coming to mind:
Please share your thoughts. Let me know if I can explain any better.
If your react app is standalone app (not a part of Asp.net app) you can use msal. js to login with AzureAD and then use openId token to login to your web API. Also you can use access token to access services secured by Azure (e.g. Microsoft Graph) directly from React.
Acquiring an access token react-aad-msal exposes a getAccessToken method you can use to obtain an access token before calling an API. import { MsalAuthProvider } from "react-aad-msal"; const authProvider = new MsalAuthProvider(config, authenticationParameters, options); const accessToken = authProvider.
Here is a complete video tutorial and source code on how to use MSAL with React to call Microsoft Graph.
The only different in your case will be that instead of calling Microsoft Graph, you will call your own API.
Bottomline is - there is no direct integration package yet for react. Which can also be read from the official statement on the msal-js repo:
After our current libraries are up to standards, we will begin balancing new feature requests, with new platforms such as react and node.js.
If your React app is standalone app and if you are going to access "downstream" API (like Microsoft Graph) from Web API, you need to implement On-Behalf-Of mechanism on your Web API. In two words: - user login with React app and access Web API with openId token; - Web API acquires new access token based on token sent from client - Web API access Microsoft Graph with this new access token.
You can find Server side example here. Client side example from another answer works in this case, but you need to send row openId to Web API instead on access token.
P.S. You can use access token instead of idToken to access your WebAPI as well, but in this case you need to define separate scope for your WebAPI in Azure as well. After that you can use this scope to access your WebAPI and separate set of scopes to access MS Graph.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With