page_type | services | client | service | level | languages | products | platform | endpoint | urlFragment | name | description | |||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
sample |
ms-identity |
React SPA |
Node.js web API |
300 |
|
|
JavaScript |
AAD v2.0 |
ms-identity-javascript-react-tutorial |
Add authorization using App roles to a React single-page app that signs-in users and calls a protected Node.js Web Api |
Add authorization using App roles to a React single-page app that signs-in users and calls a protected Node.js Web Api |
Add authorization using App roles to a React single-page app that signs-in users and calls a protected Node.js Web Api
- Overview
- Scenario
- Contents
- Prerequisites
- Setup the sample
- Explore the sample
- Troubleshooting
- About the code
- Next Steps
- Contributing
- Learn More
This sample demonstrates a cross-platform application suite involving an React single-page application (TodoListSPA) calling an Node.js & Express web API (TodoListAPI) secured with the Microsoft identity platform. In doing so, it implements Role-based Access Control (RBAC) by using Azure AD App Roles.
Role based access control in Azure AD can be done with Delegated and App permissions and Security Groups as well. we will cover RBAC using Security Groups in the next tutorial. Delegated and App permissions, Security Groups and App Roles in Azure AD are by no means mutually exclusive - they can be used in tandem to provide even finer grained access control.
ℹ️ See the community call: Deep dive on using MSAL.js to integrate React Single-page applications with Azure Active Directory
ℹ️ See the community call: Implement authorization in your applications with the Microsoft identity platform
In the sample, a dashboard component allows signed-in users to see the tasks assigned to users and is only accessible by users assigned to app role named TaskAdmin. A user needs to be assigned an app role TaskUser to be able to create tasks for themselves
- The TodoListSPA uses MSAL React to authenticate a user with the Microsoft identity platform.
- The app then obtains an access token from Azure AD on behalf of the authenticated user for the TodoListAPI. The API maintains the To-Do list and ensures access to the right users based on permissions
- TodoListAPI uses passport-azure-ad to protect its endpoint and accept only authorized calls.
- TodoListAPI maintains the To-Do list and ensures access to the right users based on permissions.
File/folder | Description |
---|---|
SPA/src/authConfig.js |
Authentication parameters for SPA project reside here. |
SPA/src/components/RouteGuard.jsx |
This component protects other components that require a user to be in a role. |
SPA/src/index.js |
MSAL React is initialized here. |
API/authConfig.json |
Authentication parameters for web API project. |
API/auth/guard.js |
Custom middleware protecting app routes that require a user to be in a role. |
API/app.js |
passport-azure-ad is initialized here. |
- 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. This sample uses ES6 conventions and will not run on Internet Explorer.
- 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 5-AccessControl\1-call-api-roles\API
npm install
cd 5-AccessControl\1-call-api-roles\SPA
npm install
ℹ️ While there are multiple projects in this sample, we'd register just one app with Azure AD and use the registered app's client id in both apps. This reuse of app ids (client ids) is used when the apps themselves are just components of one larger app topology.
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:
- # 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.
:information_source: Below, we are using a single app registration for both SPA and web API projects.
- 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:
- In the app's registration screen, select the Expose an API blade to the left to open the page where you can publish the permission as an API for which client applications can obtain access tokens for. The first thing that we need to do is to declare the unique resource URI that the clients will be using to obtain access tokens for this API. To declare an resource URI(Application ID URI), follow the following steps:
- Select Set next to the Application ID URI to generate a URI that is unique for this app.
- For this sample, accept the proposed Application ID URI (
api://{clientId}
) by selecting Save. Read more about Application ID URI at Validation differences by supported account types (signInAudience).
- All APIs must publish a minimum of one scope, also called Delegated Permission, for the client apps to obtain an access token for a user successfully. To publish a scope, follow these steps:
- Select Add a scope button open the Add a scope screen and Enter the values as indicated below:
- For Scope name, use
access_via_approle_assignments
. - Select Admins and users options for Who can consent?.
- For Admin consent display name type in Access 'msal-react-spa' as the signed-in user assigned to App role.
- For Admin consent description type in Allow the app to access the 'msal-react-spa' as a signed-in user assigned to one or more App roles.
- For User consent display name type in Access 'msal-react-spa' on your behalf after App role assignment.
- For User consent description type in Allow the app to access the 'msal-react-spa' on your behalf after assignment to one or more App roles.
- Keep State as Enabled.
- Select the Add scope button on the bottom to save this scope.
- For Scope name, use
- Select the Manifest blade on the left.
- Set
accessTokenAcceptedVersion
property to 2. - Select on Save.
- Set
ℹ️ Follow the principle of least privilege whenever you are publishing permissions for a web API.
- Since this app signs-in users, we will now proceed to select delegated permissions, which is is required by apps signing-in users.
- In the app's registration screen, select the API permissions blade in the left to open the page where we add access to the APIs that your application needs:
- Select the Add a permission button and then:
- Ensure that the My APIs tab is selected.
- In the list of APIs, select the API
msal-react-spa
. - In the Delegated permissions section, select access_via_approle_assignments in the list. Use the search box if necessary.
- Select the Add permissions button at the bottom.
- Still on the same app registration, select the App roles blade to the left.
- Select Create app role:
- For Display name, enter a suitable name, for instance TaskAdmin.
- For Allowed member types, choose User.
- For Value, enter TaskAdmin.
- For Description, enter Admins can read and write any user's todo list.
Repeat the steps above for another role named TaskUser
- Select Apply to save your changes.
To add users to this app role, follow the guidelines here: Assign users and groups to roles.
💡 Important security tip
When you set User assignment required? to Yes, Azure AD will check that only users assigned to your application in the Users and groups blade are able to sign-in to your app. You can assign users directly or by assigning security groups they belong to.
For more information, see: How to: Add app roles in your application and receive them in the token
- Still on the same app registration, select the Token configuration blade to the left.
- Select Add optional claim:
- Select optional claim type, then choose ID.
- Select the optional claim acct.
Provides user's account status in tenant. If the user is a member of the tenant, the value is 0. If they're a guest, the value is 1.
- Select Add to save your changes
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
API\authConfig.js
file. -
Find the key
tenantID
and replace the existing value with your Azure AD tenant/directory ID. -
Find the key
clientID
and replace the existing value with the application ID (clientId) ofmsal-react-spa
app copied from the Azure portal. -
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_Info_Here
and replace the existing value with your Azure AD tenant/directory ID. -
Find the key
Enter_the_Web_Api_App_Id_Uri_Here
and replace the existing value with the application ID (clientId) ofmsal-react-spa
app copied from the Azure portal.
From your shell or command line, execute the following commands:
cd 5-AccessControl\1-call-api-roles\SPA
npm start
In a separate console window, execute the following commands:
cd 5-AccessControl\1-call-api-roles\API
npm start
- Open your browser and navigate to
http://localhost:3000
. - Sign-in using the button on top-right:
- Click on the TodoList button to access your (the signed-in user's) todo list:
- If the signed-in user has the right privileges (i.e. in the right "role"), click on the Dashboard button to access every users' todo list:
- If the signed-in user does not have the right privileges, clicking on the Dashboard will give an error:
ℹ️ 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. Make sure that your questions or comments are tagged with [
azure-active-directory
react
ms-identity
adal
msal
].
If you find a bug in the sample, raise the issue on GitHub Issues.
The client application React SPA has a RouteGuard component that checks whether a user has the right privileges to access a protected route. It does this by checking roles
claim in the ID token of the signed-in user:
export const RouteGuard = ({ ...props }) => {
const { instance } = useMsal();
const [isAuthorized, setIsAuthorized] = useState(false);
const onLoad = async () => {
const currentAccount = instance.getActiveAccount();
if (currentAccount && currentAccount.idTokenClaims['roles']) {
let intersection = props.roles.filter((role) => currentAccount.idTokenClaims['roles'].includes(role));
if (intersection.length > 0) {
setIsAuthorized(true);
}
}
};
useEffect(() => {
onLoad();
}, [instance]);
return (
<>
{isAuthorized ? (
<div>{props.children}</div>
) : (
<div className="data-area-div">
<h3>You are unauthorized to view this content.</h3>
</div>
)}
</>
);
};
We then enable RouteGuard in App.jsx as follows:
const Pages = () => {
return (
<Routes>
<Route
exact
path="/todolist"
element={
<RouteGuard roles={[appRoles.TaskUser, appRoles.TaskAdmin]}>
<TodoList />
</RouteGuard>
}
/>
<Route
exact
path="/dashboard"
element={
<RouteGuard roles={[appRoles.TaskAdmin]}>
<Dashboard />
</RouteGuard>
}
/>
<Route path="/redirect" element={<Redirect />} />
<Route path="/" element={<Home />} />
</Routes>
);
};
However, it is important to be aware of that no content on the front-end application can be truly secure. That is, our RouteGuard component is primarily responsible for rendering the correct pages and other UI elements for a user in a particular role; in the example above, we allow only users in the TaskAdmin
role to see the Dashboard
component. In order to truly protect data and expose certain REST operations to a selected set of users, we enable RBAC on the back-end/web API as well in this sample. This is shown next.
As mentioned before, in order to truly implement RBAC and secure data, we allow only authorized calls to our web API. We do this by defining an access matrix and protecting our routes with a routeGuard
custom middleware (see guard):
const routeGuard = (accessMatrix) => {
return (req, res, next) => {
if (!req.authInfo.hasOwnProperty('roles')) {
return res.status(403).json({ error: 'No roles claim found!' });
}
const roles = req.authInfo['roles'];
if (!requestHasRequiredAttributes(accessMatrix, req.path, req.method, roles)) {
return res.status(403).json({ error: 'User does not have the role, method or path' });
}
next();
};
};
We defined these roles in authConfig.js as follows:
accessMatrix: {
todolist: {
path: '/todolist',
methods: ['GET', 'POST', 'PUT', 'DELETE'],
roles: ['TaskUser', 'TaskAdmin'],
},
dashboard: {
path: '/dashboard',
methods: ['GET'],
roles: ['TaskAdmin'],
},
},
Finally, in app.js, we add the routeGuard middleware to /api
route:
const bearerStrategy = new BearerStrategy(options, (token, done) => {
// Send user info using the second argument
done(null, {}, token);
});
const app = express();
app.use(passport.initialize());
passport.use(bearerStrategy);
app.use('/api',
passport.authenticate('oauth-bearer', { session: false }),
roleGuard(config.accessMatrix),
router
);
app.listen(port, () => {
console.log('Listening on port ' + port);
});
ℹ️ Did the sample not work for you as expected? Then please reach out to us using the GitHub Issues page.
Learn how to:
- Use MSAL React to call a protected web API using Security Groups to implement Role-Based Access Control
- Use MSAL React to call a protected web API using Conditional Access auth context to perform step-up authentication
- Sign-in users interactively server-side (Node.js) and silently acquire a token for MS Graph from a React single-page app (SPA)
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 opencode@microsoft.com with any additional questions or comments.
- Microsoft identity platform (Azure Active Directory for developers)
- 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
- Azure AD code samples
- 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