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:
- User navigates to
/admin
. useEffect()
starts checking if userisAuthenticated
.- If not, they are automatically redirected to login.
- 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:
- The
accessToken
,idToken
,oid
are automatically sent to my API for validation server-side as well. - 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.
- 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:
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?