Skip to content

Instantly share code, notes, and snippets.

@gbvanrenswoude
Created September 15, 2022 20:41
Show Gist options
  • Save gbvanrenswoude/2c7faa7ce77babb27a0111f94cecb20a to your computer and use it in GitHub Desktop.
Save gbvanrenswoude/2c7faa7ce77babb27a0111f94cecb20a to your computer and use it in GitHub Desktop.
React app with Azure AD forced login on entering the WebApp
import React from 'react';
import { AuthenticationState, AzureAD } from 'react-aad-msal';
import ReactDOM from 'react-dom/client';
import { BrowserRouter } from 'react-router-dom';
import App from './App';
import './index.css';
import reportWebVitals from './reportWebVitals';
import { LoginType, MsalAuthProvider } from 'react-aad-msal';
// Msal Configurations
const config = {
auth: {
authority: 'https://login.microsoftonline.com/<tenant-id>',
clientId: '<client-id>',
redirectUri: 'http://localhost:3000/',
},
cache: {
cacheLocation: 'localStorage',
storeAuthStateInCookie: true,
},
};
// Authentication Parameters
const authenticationParameters = {
scopes: ['user.read'],
};
// Options
const options = {
loginType: LoginType.Popup,
tokenRefreshUri: window.location.origin + '/auth.html',
};
// @ts-ignore
const authProvider = new MsalAuthProvider(config, authenticationParameters, options);
const root = ReactDOM.createRoot(document.getElementById('root') as HTMLElement);
root.render(
// @ts-ignore
<AzureAD provider={authProvider} forceLogin={true}>
{/*
// @ts-ignore*/}
{({ login, logout, authenticationState, error, accountInfo }) => {
switch (authenticationState) {
case AuthenticationState.Authenticated:
return (
<React.StrictMode>
<BrowserRouter>
<App
name={accountInfo.account.userName}
email={accountInfo.account.userName}
logout={logout}
jwtIdToken={accountInfo.jwtIdToken}
/>
</BrowserRouter>
</React.StrictMode>
);
case AuthenticationState.Unauthenticated:
return (
<div>
{error && (
<p>
<span>An error occured during authentication.</span>
</p>
)}
<p>
<span>Login again</span>
<button onClick={login}>Login</button>
</p>
</div>
);
case AuthenticationState.InProgress:
return <p>Authenticating...</p>;
}
}}
</AzureAD>,
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment