This article is a follow-up blog from my previous one for authentication with Azure AD in the front-end.

Link to post: https://www.bilot.fi/authentication-with-azure-ad-using-msal-react-app/

 

Src: Microsoft Documentation

 

Above is the process of securing your web app and web APIs using Azure AD. First, you need to register your Web APIs with Azure to make sure that it doesn’t allow anonymous requests. User then logins to authenticate him/herself and requests access token from Azure AD. Azure AD will provision access token for authenticated users, then you write codes to attach token to header before users call any APIs.

In your React app,  create a separate file for calling APIs, then import msalApp from ‘auth-utils’. msalApp is an object instance of UserAgentApplication, which comes with the built-in methods like getAccount() and acquireTokenSilent().  GetAccount() returns the account object, which contains account info, after user successfully login. Check if there is account info, then call acquireTokentSilent to acquire access token from cache or from hidden frames if not available before every call to API. Last but not least, attach the token in your request header.

 

import axios from 'axios'
import { msalApp, GRAPH_REQUESTS } from './auth-utils'
//Call AcquireTokenSilent to acquire token
async function getToken() {
  // grab current state
  const account = await msalApp.getAccount()
  const token =
    account && (await msalApp.acquireTokenSilent(GRAPH_REQUESTS.LOGIN))
  return {
    headers: {
      Authorization: `Bearer ${token.accessToken}`, // the token is a variable which holds the token
    },
  }
}
export const get = async (path, params = {}) => {
  const item = await getToken()
  return axios.get(`${BASE_URL}${path}`, item, params).then(res => res.data)
}
export const getUserInfo = () => {
  return get(`User`)
}

 

For further instruction on how to secure your APIs in Azure using OAuth 2.0 protocol, please follow the link here:

https://docs.microsoft.com/en-us/azure/api-management/api-management-howto-protect-backend-with-aad