How to authenticate users with Azure AD using MSAL.js
- Get link
- X
- Other Apps
How to authenticate users with Azure AD using MSAL.js ( @azure/msal-browser )
Step 1: Install MSAL.js
npm install @azure/msal-browser
Step 2: Configure MSAL.js
Create a file called authConfig.js
in the src
directory of your React.js application and add the following code:
const config = { auth: { clientId: '<your-client-id>', authority: 'https://login.microsoftonline.com/<your-tenant-id>', redirectUri: 'http://localhost:3000', }, cache: { cacheLocation: 'localStorage', storeAuthStateInCookie: true, }, }; export default config;
Replace <your-client-id>
with the client ID of your Azure AD application and <your-tenant-id>
with the ID of your Azure AD tenant.
Step 3: Create a login component
Create a file called Login.js
in the src
directory of your React.js application and add the following code:
import { PublicClientApplication } from '@azure/msal-browser'; import config from './authConfig'; const Login = () => { const msalInstance = new PublicClientApplication(config); const login = async () => { try { await msalInstance.loginPopup(); console.log('User logged in'); } catch (error) { console.log(error); } }; return ( <div> <button onClick={login}>Login with Azure AD</button> </div> ); }; export default Login;
This component creates an instance of the PublicClientApplication
class with the configuration we defined in the authConfig.js
file. It also defines a login
function that uses the loginPopup
method to initiate the authentication flow.
Step 4: Use the login component
Open the App.js
file in the src
directory of your React.js application and replace its contents with the following code:
import Login from './Login'; function App() { return ( <div className="App"> <h1>React.js Azure AD Authentication</h1> <Login /> </div> ); } export default App;
This code imports the Login
component and renders it in the App
component.
Step 5: Test the authentication flow
Start your React.js application by running the following command in a terminal:
npm start
- Get link
- X
- Other Apps
Comments