1

I'm not too far into the implementation and have it pretty bear bones and not refactored (and not great coding practices).

This is an Admin portal that uses the company's Azure Active Directory to validate users as opposed to username/password, etc. The flow is this:

  1. User navigates to /admin.
  2. useEffect() starts checking if user isAuthenticated.
  3. If not, they are automatically redirected to login.
  4. Once they have logged in, or are verified as already being isAuthenticated, they can now access components that are children of <AuthenticatedTemplate>.

The only child component currently is <Token>, which for testing purposes, just prints out the JWT token returned from the API. Essentially what happens here is:

  1. The accessToken, idToken, oid are automatically sent to my API for validation server-side as well.
  2. When they are validated, the user is checked against the DB... if they exist, send a JWT... if not, add them and send a JWT.
  3. JWT is saved to sessionStorage and is used subsequently for client-API communication.

The problem I'm running into my API is getting queried four or more times:

enter image description here

This is what I have so far:

// index.tsx

import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/App';
import { PublicClientApplication } from '@azure/msal-browser';
import { MsalProvider } from '@azure/msal-react';
import { msalConfig } from './utils/authConfig';

// Instantiate MSAL that encapsulates the entire app
const msalInstance = new PublicClientApplication(msalConfig);

ReactDOM.render(
  <React.StrictMode>
    <MsalProvider instance={msalInstance}>
      <App />
    </MsalProvider>
  </React.StrictMode>,
  document.getElementById('root')
);
// App.tsx

import React, { useEffect } from 'react';
import {
  AuthenticatedTemplate,
  useMsal,
  useAccount,
  useIsAuthenticated,
} from '@azure/msal-react';
import { graphConfig, loginRequest } from '../utils/authConfig';
import { InteractionStatus } from '@azure/msal-browser';
import axios from 'axios';

const Token = (props: any) => {

  if (props.account) {
    props.instance
      .acquireTokenSilent({
        ...loginRequest,
        account: props.account,
      })
      .then((response: any) => {
        axios
          .post('/api/v2/auth/aad_token/validate/', {
            access_token: response.accessToken,
            id_token: response.idToken,
            oid: response.uniqueId,
          })
          .then((response) => {
            console.log(response.data);
          })
          .catch((error) => {
            console.log(error);
          });
      });
  }
  return <div>Test</div>;
};

const App = () => {
  const isAuthenticated = useIsAuthenticated();
  const { instance, inProgress, accounts } = useMsal();
  const account = useAccount(accounts[0] || {});

  useEffect(() => {
    if (inProgress === InteractionStatus.None && !isAuthenticated) {
      instance.loginRedirect(loginRequest);
    }
  });

  return (
    <div className='App'>
      <AuthenticatedTemplate>
        <Token account={account} instance={instance} />
      </AuthenticatedTemplate>
    </div>
  );
};

export default App;

Suggestions for how to limit this?

cjones
  • 8,384
  • 17
  • 81
  • 175

1 Answers1

0

This fixed it for me... forgot the dependency array:

const Token = () => {
  const { accounts, instance } = useMsal();
  const account = useAccount(accounts[0] || {});

  useEffect(() => {
    // Check if account object exists
    if (account) {
      // If it does then acquire an accessToken
      instance
        .acquireTokenSilent({
          ...loginRequest,
          account: account,
        })
        .then((response: any) => {
          axios
            .post('/api/v2/auth/aad_token/validate/', {
              access_token: response.accessToken,
              id_token: response.idToken,
              oid: response.uniqueId,
            })
            .then((response) => {
              console.log(response.data);
            })
            .catch((error) => {
              console.log(error);
            });
        });
    }
  }, []);
};
cjones
  • 8,384
  • 17
  • 81
  • 175