page_type | name | description | languages | products | urlFragment | extensions | |||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
sample |
React single-page application using MSAL React to authenticate users against Azure Active Directory |
React single-page application using MSAL React to authenticate users against Azure Active Directory |
|
|
ms-identity-javascript-react-tutorial |
|
- Overview
- Scenario
- Contents
- Prerequisites
- Setup the sample
- Explore the sample
- Troubleshooting
- About the code
- Next Tutorial
- Contributing
- Learn More
This sample demonstrates a React single-page application (SPA) authenticating users against Azure Active Directory (Azure AD), using the Microsoft Authentication Library for React (MSAL React).
MSAL React is a wrapper around the Microsoft Authentication Library for JavaScript (MSAL.js). As such, it exposes the same public APIs that MSAL.js offers, while adding many new features customized for modern React applications.
Here you'll learn how to sign-in users and acquire ID tokens, as well as how to work with different audiences and account types.
- The client React SPA uses the to sign-in a user and obtain a JWT ID Token from Azure AD.
- The ID Token proves that the user has successfully authenticated against Azure AD.
File/folder | Description |
---|---|
App.jsx |
Main application logic resides here. |
NavigationBar.jsx |
Contains buttons for login and logout. |
authConfig.js |
Contains authentication parameters. |
- Node.js must be installed to run this sample.
- Visual Studio Code is recommended for running and editing this sample.
- VS Code Azure Tools extension is recommended for interacting with Azure through VS Code Interface.
- A modern web browser.
- An Azure AD tenant. For more information, see: How to get an Azure AD tenant
- A user account in your Azure AD tenant.
This sample will not work with a personal Microsoft account. If you're signed in to the Azure portal with a personal Microsoft account and have not created a user account in your directory before, you will need to create one before proceeding.
From your shell or command line:
git clone https://github.com/Azure-Samples/ms-identity-javascript-react-tutorial.git
or download and extract the repository .zip file.
⚠️ To avoid path length limitations on Windows, we recommend cloning into a directory near the root of your drive.
cd 1-Authentication\1-sign-in\SPA
npm install
There is one project in this sample. To register it, you can:
- follow the steps below for manually register your apps
- or use PowerShell scripts that:
- automatically creates the Azure AD applications and related objects (passwords, permissions, dependencies) for you.
- modify the projects' configuration files.
Expand this section if you want to use this automation:
⚠️ If you have never used Microsoft Graph PowerShell before, we recommend you go through the App Creation Scripts Guide once to ensure that your environment is prepared correctly for this step.
-
On Windows, run PowerShell as Administrator and navigate to the root of the cloned directory
-
In PowerShell run:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope Process -Force
-
Run the script to create your Azure AD application and configure the code of the sample application accordingly.
-
For interactive process -in PowerShell, run:
cd .\AppCreationScripts\ .\Configure.ps1 -TenantId "[Optional] - your tenant id" -AzureEnvironmentName "[Optional] - Azure environment, defaults to 'Global'"
Other ways of running the scripts are described in App Creation Scripts guide. The scripts also provide a guide to automated application registration, configuration and removal which can help in your CI/CD scenarios.
To manually register the apps, as a first step you'll need to:
- Sign in to the Azure portal.
- If your account is present in more than one Azure AD tenant, select your profile at the top right corner in the menu on top of the page, and then switch directory to change your portal session to the desired Azure AD tenant.
- Navigate to the Azure portal and select the Azure Active Directory service.
- Select the App Registrations blade on the left, then select New registration.
- In the Register an application page that appears, enter your application's registration information:
- In the Name section, enter a meaningful application name that will be displayed to users of the app, for example
msal-react-spa
. - Under Supported account types, select Accounts in this organizational directory only
- Select Register to create the application.
- In the Name section, enter a meaningful application name that will be displayed to users of the app, for example
- In the Overview blade, find and note the Application (client) ID. You use this value in your app's configuration file(s) later in your code.
- In the app's registration screen, select the Authentication blade to the left.
- If you don't have a platform added, select Add a platform and select the Single-page application option.
- In the Redirect URI section enter the following redirect URIs:
http://localhost:3000/
http://localhost:3000/redirect
- Click Save to save your changes.
- In the Redirect URI section enter the following redirect URIs:
Open the project in your IDE (like Visual Studio or Visual Studio Code) to configure the code.
In the steps below, "ClientID" is the same as "Application ID" or "AppId".
- Open the
SPA\src\authConfig.js
file. - Find the key
Enter_the_Application_Id_Here
and replace the existing value with the application ID (clientId) ofmsal-react-spa
app copied from the Azure portal. - Find the key
Enter_the_Tenant_Id_Here
and replace the existing value with your Azure AD tenant/directory ID.
cd 1-Authentication\1-sign-in\SPA
npm start
- Open your browser and navigate to
http://localhost:3000
. - Select the Sign In button on the top right corner. Choose either Popup or Redirect flows (see: MSAL.js interaction types).
ℹ️ Did the sample not work for you as expected? Then please reach out to us using the GitHub Issues page.
Were we successful in addressing your learning objective? Consider taking a moment to share your experience with us.
Expand for troubleshooting info
- Use Stack Overflow to get support from the community. Ask your questions on Stack Overflow first and browse existing issues to see if someone has asked your question before. Ask your questions on Stack Overflow first and browse existing issues to see if someone has asked your question before. Make sure that your questions or comments are tagged with [
azure-active-directory-b2c
node
ms-identity
adal
msal-js
msal
].
To provide feedback on or suggest features for Azure Active Directory, visit User Voice page.
MSAL React should be instantiated outside of the component tree to prevent it from being re-instantiated on re-renders. After instantiation, pass it as props to your application.
const msalInstance = new PublicClientApplication(msalConfig);
ReactDOM.render(
<React.StrictMode>
<App msalInstance={msalInstance}/>
</React.StrictMode>,
document.getElementById("root")
);
export default function App({msalInstance}) {
return (
<MsalProvider instance={msalInstance}>
<PageLayout>
<MainContent />
</PageLayout>
</MsalProvider>
);
}
At the top of your component tree, wrap everything between MsalProvider component. All components underneath MsalProvider will have access to the PublicClientApplication instance via context as well as all hooks and components provided by msal-react.
export default function App({msalInstance}) {
return (
<MsalProvider instance={msalInstance}>
<PageLayout>
<MainContent />
</PageLayout>
</MsalProvider>
);
}
MSAL.js exposes 3 login APIs: loginPopup()
, loginRedirect()
and ssoSilent()
. These APIs are usable in MSAL React as well:
export function App() {
const { instance, accounts, inProgress } = useMsal();
if (accounts.length > 0) {
return <span>There are currently {accounts.length} users signed in!</span>
} else if (inProgress === "login") {
return <span>Login is currently in progress!</span>
} else {
return (
<>
<span>There are currently no users signed in!</span>
<button onClick={() => instance.loginPopup()}>Login</button>
</>
);
}
}
You may also use MSAL React's useMsalAuthentication hook. Below is an example in which the ssoSilent()
API is used. When using ssoSilent()
, the recommended pattern is that you fallback to an interactive method should the silent SSO attempt fails:
function App() {
const request = {
loginHint: "[email protected]",
scopes: ["User.Read"]
}
const { login, result, error } = useMsalAuthentication(InteractionType.Silent, request);
useEffect(() => {
if (error) {
login(InteractionType.Popup, request);
}
}, [error]);
const { accounts } = useMsal();
return (
<React.Fragment>
<p>Anyone can see this paragraph.</p>
<AuthenticatedTemplate>
<p>Signed in as: {accounts[0]?.username}</p>
</AuthenticatedTemplate>
<UnauthenticatedTemplate>
<p>No users are signed in!</p>
</UnauthenticatedTemplate>
</React.Fragment>
);
}
As shown above, the components that depend on whether the user is authenticated should be wrapped inside React's AuthenticatedTemplate
and UnauthenticatedTemplate
components. Alternatively, you may use the useIsAuthenticated hook to conditionally render components.
The application redirects the user to the Microsoft identity platform logout endpoint to sign out. This endpoint clears the user's session from the browser. If your app does not go to the logout endpoint, the user may re-authenticate to your app without entering their credentials again, because they would have a valid single sign-on session with the Microsoft identity platform endpoint. For more, see: Send a sign-out request
When you receive an ID token directly from the IdP on a secure channel (e.g. HTTPS), such is the case with SPAs, there’s no need to validate it. If you were to do it, you would validate it by asking the same server that gave you the ID token to give you the keys needed to validate it, which renders it pointless, as if one is compromised so is the other.
This sample is meant to work with accounts in your organization (aka single-tenant). If you would like to allow sign-ins from other organizations and/or with other types of accounts, you have to configure your authority
string in authConfig.js
accordingly. For example:
const msalConfig = {
auth: {
clientId: "<YOUR_CLIENT_ID>",
authority: "https://login.microsoftonline.com/common", // allows sign-ins with any type of account
redirectUri: "<YOUR_REDIRECT_URI>",
},
For more information about audiences and account types, please see: Validation differences by supported account types (signInAudience)
⚠️ Be aware that making an application multi-tenant entails more than just modifying theauthority
string. For more information, please see How to: Sign in any Azure Active Directory user using the multi-tenant application pattern.
National clouds (aka sovereign clouds) are physically isolated instances of Azure. These regions of Azure are designed to make sure that data residency, sovereignty, and compliance requirements are honored within geographical boundaries. Enabling your application for sovereign clouds requires you to:
- register your application in a specific portal, depending on the cloud.
- use a specific authority, depending on the cloud in the configuration file for your application.
- in case you want to call the MS Graph, this requires a specific Graph endpoint URL, depending on the cloud.
For instance, to configure this sample for Azure AD Germany national cloud:
- Open the
App\authConfig.js
file. - Find the key
Enter_the_Application_Id_Here
and replace the existing value with the application ID (clientId) of thems-identity-javascript-tutorial-c1s1
application copied from the Azure portal. - Find the key
https://login.microsoftonline.com/Enter_the_Tenant_Info_Here
and replace the existing value withhttps://portal.microsoftazure.de/<your-tenant-id>
.
See National Clouds for more information.
Continue with the next tutorial: Call the Microsoft Graph API.
If you'd like to contribute to this sample, see CONTRIBUTING.MD.
This project has adopted the Microsoft Open Source Code of Conduct. For more information, see the Code of Conduct FAQ or contact [email protected] with any additional questions or comments.
- Microsoft identity platform (Azure Active Directory for developers)
- Azure AD code samples
- Overview of Microsoft Authentication Library (MSAL)
- Register an application with the Microsoft identity platform
- Configure a client application to access web APIs
- Understanding Azure AD application consent experiences
- Understand user and admin consent
- Application and service principal objects in Azure Active Directory
- Authentication Scenarios for Azure AD
- Building Zero Trust ready apps
- National Clouds
- Initialize client applications using MSAL.js
- Single sign-on with MSAL.js
- Handle MSAL.js exceptions and errors
- Logging in MSAL.js applications
- Pass custom state in authentication requests using MSAL.js
- Prompt behavior in MSAL.js interactive requests
- Use MSAL.js to work with Azure AD B2C