I am securing my React Apps and I want to use the wrapper function below to insure that the app only gets rendered when there is a successful login. I am separating the Login from future MSAL token requests because I perceive Login to be a boolean in that you are logged in or you are not logged in. If a later MSAL request requires my user to "re-login" I will call this function to reload the app:
window.location.reload(true);
This code is for React Apps only. I am only securing the app not the endpoints. This code may be used in apps that only access public endpoints.
Sample Usage:
import { WrapWithMSAL } from './MSAL_Utils'
// Will handle Auth and then render App
WrapWithMSAL(() =>
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root'))
);
This is the Wrapper function:
import { Configuration, UserAgentApplication, AuthenticationParameters,
AuthResponse, Logger, LogLevel, } from 'msal'
// Hold the render CBR while Authenticating
let appRender:CallableFunction = ()=>{}
// Wrapper function to secure the Rendering of the React App
export const WrapWithMSAL = (callbackRtn:CallableFunction) => {
appRender = callbackRtn;
if (!MSALAuthAgent.getAccount())
{
// Set the MSAL CBR specifically to Login Handler
MSALAuthAgent.handleRedirectCallback(msalLoginResultCallback);
const msalAuthParams: AuthenticationParameters = {
scopes: regScopes
};
// Popup AD B2C Login,
MSALAuthAgent.loginRedirect(msalAuthParams);
}
else // Login was retrieved from Session Cache
{
appRender(); // Start the app
}
}
// Callbacks passed to MSAL
/**
* Called when the user has successfully logged in
* (the account object is created at the time of successful login)
* or null when no state is found
* @returns {@link Account} - the account object stored in MSAL
*/
const msalLoginResultCallback = (error: any, response: any) => {
if (error) {
alert(error.toString());
}
else {
appRender(); // Start the app
}
}
// MSAL Specifications
const configuration: Configuration = {
auth: {
clientId: "AZURE_APPLICATION_ID",
authority:"AZURE_USER_FLOW",
redirectUri: "https://myspa.mysite.com",
validateAuthority: false,
},
cache: {
cacheLocation: "sessionStorage",
storeAuthStateInCookie: true,
},
system: {
logger: new Logger((logLevel, message, containsPii) => {
console.log("[MSAL]: ", message)
}, {
level: LogLevel.Verbose,
piiLoggingEnabled: false
})
}
}
const regScopes : ['read.scope'];
const MSALAuthAgent = new UserAgentApplication(configuration);
export default MSALAuthAgent;
My question is does this approach secure my app?