Skip to content

Latest commit

 

History

History
533 lines (401 loc) · 32.7 KB

File metadata and controls

533 lines (401 loc) · 32.7 KB

Node.js & Express web app using Security Groups to implement Role-Based Access Control

  1. Overview
  2. Scenario
  3. Contents
  4. Prerequisites
  5. Setup
  6. Registration
  7. Running the sample
  8. Explore the sample
  9. More information
  10. Community Help and Support
  11. Contributing

Overview

This sample demonstrates a Node.js & Express web app that is secured with the Microsoft Authentication Library for Node.js (MSAL Node). The app implements Role-based Access Control (RBAC) by using Microsoft Entra ID Security Groups. In the sample, users in TaskUser role can perform CRUD operations on their todo list, while users in TaskAdmin role can see all other users' tasks.

Access control in Microsoft Entra ID can be done with App Roles as well, as we covered in the previous tutorial. Security Groups and App Roles in Microsoft Entra ID are by no means mutually exclusive - they can be used in tandem to provide even finer grained access control.

ℹ️ Check out the recorded session on this topic: An introduction to Microsoft Graph for developers

Scenario

  1. The client application uses MSAL Node (via msal-node-wrapper) to sign-in a user and obtain an ID Token from Microsoft Entra ID.
  2. The ID Token contains the groups claim that is used to control access to protected routes.

Overview

Contents

File/folder Description
AppCreationScripts/ Contains Powershell scripts to automate app registration.
ReadmeFiles/ Contains illustrations and screenshots.
App/authConfig.js Authentication parameters and settings.
App/app.js Application entry point.

Prerequisites

  • 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 Microsoft Entra ID tenant. For more information, see: How to get a Microsoft Entra tenant
  • A user account in your Microsoft Entra ID tenant.

Setup

Step 1: Clone or download this repository

From your shell or command line:

    git clone https://github.com/Azure-Samples/ms-identity-javascript-nodejs-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.

Step 2: Install project dependencies

    cd 4-AccessControl/2-security-groups/App
    npm install

Registration

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 Microsoft Entra 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.

  1. Ensure that you have PowerShell 7 or later.

  2. Run the script to create your Microsoft Entra application and configure the code of the sample application accordingly.

  3. 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.

ℹ️ This sample can make use of client certificates. You can use AppCreationScripts to register a Microsoft Entra application with certificates. See: How to use certificates instead of client secrets

Choose the Microsoft Entra tenant where you want to create your applications

  1. Sign in to the Microsoft Entra admin center.
  2. If your account is present in more than one Microsoft Entra 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 Microsoft Entra tenant.

Register the client app (msal-node-webapp)

  1. Navigate to the Microsoft Entra admin center and select the Microsoft Entra ID service.
  2. Select the App Registrations blade on the left, then select New registration.
  3. 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-node-webapp.
    • Under Supported account types, select Accounts in this organizational directory only.
    • In the Redirect URI (optional) section, select Web in the combo-box and enter the following redirect URI: http://localhost:4000/redirect.
  4. Select Register to create the application.
  5. In the app's registration screen, find and note the Application (client) ID. You use this value in your app's configuration file(s) later in your code.
  6. Select Save to save your changes.
  7. In the app's registration screen, select the Certificates & secrets blade in the left to open the page where you can generate secrets and upload certificates.
  8. In the Client secrets section, select New client secret:
    • Type a key description (for instance app secret),
    • Select one of the available key durations (6 months, 12 months or Custom) as per your security posture.
    • The generated key value will be displayed when you select the Add button. Copy and save the generated value for use in later steps.
    • You'll need this key later in your code's configuration files. This key value will not be displayed again, and is not retrievable by any other means, so make sure to note it from the Microsoft Entra admin center before navigating to any other screen or blade.

    ⚠️ For enhanced security, consider using certificates instead of client secrets. See: How to use certificates instead of secrets.

  9. 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 Microsoft APIs tab is selected.
    • In the Commonly used Microsoft APIs section, select Microsoft Graph
    • In the Delegated permissions section, select the User.Read, GroupMember.Read.All in the list. Use the search box if necessary.
    • Select the Add permissions button at the bottom.
    • Finally, grant admin consent for these scopes (required to handle the overage scenario)

Configure Optional Claims

  1. Still on the same app registration, select the Token configuration blade to the left.
  2. Select Add optional claim:
    1. Select optional claim type, then choose Access.
    2. 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.

    1. Select Add to save your changes.

Configure the client app (msal-node-webapp) to use your app registration

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".

  1. Open the App/authConfig.js file.
  2. Find the key clientId and replace the existing value with the application ID (clientId) of msal-node-webapp app copied from the Microsoft Entra admin center.
  3. Find the key tenantId and replace the existing value with your Microsoft Entra tenant ID.
  4. Find the key clientSecret and replace the existing value with the key you saved during the creation of msal-node-webapp copied from the Microsoft Entra admin center.
  5. Find the key redirectUri and replace the existing value with the Redirect URI for msal-node-webapp. (by default http://localhost:4000/redirect).

ℹ️ For redirectUri, you can simply enter the path component of the URI instead of the full URI. For example, instead of http://localhost:4000/redirect, you can simply enter /redirect. This may come in handy in deployment scenarios.

  1. Open the App/app.js file.
  2. Find the string ENTER_YOUR_SECRET_HERE and replace it with a secret that will be used when encrypting your app's session using the express-session package.

Create Security Groups

⚠️ You may already have security groups with the names defined below in your tenant and/or you may not have permissions to create new security groups. In that case, skip the steps below and update the configuration files in your project(s) with the desired names/IDs of existing groups in your tenant.

  1. Navigate to the Microsoft Entra admin center and select the Microsoft Entra ID service.
  2. Select Groups blade on the left.
  3. In the Groups blade, select New Group.
    1. For Group Type, select Security
    2. For Group Name, enter GroupAdmin
    3. For Group Description, enter Admin Security Group
    4. Add Group Owners and Group Members as you see fit.
    5. Select Create.
  4. In the Groups blade, select New Group.
    1. For Group Type, select Security
    2. For Group Name, enter GroupMember
    3. For Group Description, enter User Security Group
    4. Add Group Owners and Group Members as you see fit.
    5. Select Create.
  5. Assign the user accounts that you plan to work with to these security groups.

For more information, visit: Create a basic group and add members using Microsoft Entra ID

Configure Security Groups

You have two different options available to you on how you can further configure your application to receive the groups claim.

  1. Receive all the groups that the signed-in user is assigned to in a Microsoft Entra tenant, included nested groups.
  2. Receive the groups claim values from a filtered set of groups that your application is programmed to work with (Not available in the Microsoft Entra ID Free edition).

To get the on-premise group's samAccountName or On Premises Group Security Identifier instead of Group ID, please refer to the document Configure group claims for applications with Microsoft Entra ID.

Configure your application to receive all the groups the signed-in user is assigned to, including nested groups

  1. In the app's registration screen, select the Token Configuration blade in the left to open the page where you can configure the claims provided tokens issued to your application.
  2. Select the Add groups claim button on top to open the Edit Groups Claim screen.
  3. Select Security groups or the All groups (includes distribution lists but not groups assigned to the application) option. Choosing both negates the effect of Security Groups option.
  4. Under the ID section, select Group ID. This will result in Microsoft Entra ID sending the object id of the groups the user is assigned to in the groups claim of the ID Token that your app receives after signing-in a user.

Configure your application to receive the groups claim values from a filtered set of groups a user may be assigned to

Prerequisites, benefits and limitations of using this option
  1. This option is useful when your application is interested in a selected set of groups that a signing-in user may be assigned to and not every security group this user is assigned to in the tenant. This option also saves your application from running into the overage issue.
  2. This feature is not available in the Microsoft Entra ID Free edition.
  3. Nested group assignments are not available when this option is utilized.
Steps to enable this option in your app
  1. In the app's registration screen, select the Token Configuration blade in the left to open the page where you can configure the claims provided tokens issued to your application.
  2. Select the Add groups claim button on top to open the Edit Groups Claim screen.
  3. Select Groups assigned to the application.
    1. Choosing additional options like Security Groups or All groups (includes distribution lists but not groups assigned to the application) will negate the benefits your app derives from choosing to use this option.
  4. Under the ID section, select Group ID. This will result in Microsoft Entra ID sending the object id of the groups the user is assigned to in the groups claim of the ID Token that your app receives after signing-in a user.
  5. If you are exposing a Web API using the Expose an API option, then you can also choose the Group ID option under the Access section. This will result in Microsoft Entra ID sending the Object ID of the groups the user is assigned to in the groups claim of the Access Token issued to the client applications of your API.
  6. In the app's registration screen, select on the Overview blade in the left to open the Application overview screen. Select the hyperlink with the name of your application in Managed application in local directory (note this field title can be truncated for instance Managed application in ...). When you select this link you will navigate to the Enterprise Application Overview page associated with the service principal for your application in the tenant where you created it. You can navigate back to the app registration page by using the back button of your browser.
  7. Select the Users and groups blade in the left to open the page where you can assign users and groups to your application.
    1. Select the Add user button on the top row.
    2. Select User and Groups from the resultant screen.
    3. Choose the groups that you want to assign to this application.
    4. Click Select in the bottom to finish selecting the groups.
    5. Select Assign to finish the group assignment process.
    6. Your application will now receive these selected groups in the groups claim when a user signing in to your app is a member of one or more these assigned groups.
  8. Select the Properties blade in the left to open the page that lists the basic properties of your application.Set the User assignment required? flag to Yes.

💡 Important security tip

When you set User assignment required? to Yes, Microsoft Entra ID 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.

Running the sample

    cd 4-AccessControl/1-security-groups/App
    npm start

Explore the sample

  1. Open your browser and navigate to http://localhost:4000.
  2. Sign-in using the button on top-right.
  3. Click on the TodoList button to access your (the signed-in user's) todo list.
  4. 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.
  5. 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.

We'd love your feedback!

Were we successful in addressing your learning objective? Consider taking a moment to share your experience with us.

Implementing role-based access control

In appSettings.js, we create an access matrix that defines the required roles and allowed HTTP methods for each route that we like to grant role-based access:

{
    accessMatrix: {
        todolist: {
            methods: ["GET", "POST", "DELETE"],
            groups: ["Enter_the_ObjectId_of_GroupAdmin", "Enter_the_ObjectId_of_GroupMember"]
        },
        dashboard: {
            methods: ["GET"],
            groups: ["Enter_the_ObjectId_of_GroupAdmin"]
        }
    }
}

Then, in app.js, we create an instance of the MsalWebAppAuthClient class.

const express = require('express');
const session = require('express-session');
const MsIdExpress = require('microsoft-identity-express');

const appSettings = require('./appSettings.js');
const mainRouter = require('./routes/mainRoutes');

const SERVER_PORT = process.env.PORT || 4000;

// initialize express
const app = express(); 

app.use(session({
    secret: 'ENTER_YOUR_SECRET_HERE',
    resave: false,
    saveUninitialized: false,
    cookie: {
        secure: false, // set this to true on production
    }
}));

app.use(express.urlencoded({ extended: false }));
app.use(express.json());

// instantiate the wrapper
const msid = new MsIdExpress.WebAppAuthClientBuilder(appSettings).build();

// initialize the wrapper
app.use(msid.initialize());

// pass the instance to your routers
app.use(mainRouter(msid));

app.listen(SERVER_PORT, () => console.log(`Msal Node Auth Code Sample app listening on port ${SERVER_PORT}!`));

module.exports = app;

The msid object exposes the middleware we can use to protect our app routes. This can be seen in mainRoutes.js:

const express = require('express');

module.exports = (msid) => {

    // initialize router
    const router = express.Router();

    // app routes
    router.get('/', (req, res, next) => res.redirect('/home'));
    router.get('/home', mainController.getHomePage);

    // authentication routes
    router.get('/signin', msid.signIn({ postLoginRedirect: '/' }));
    router.get('/signout', msid.signOut({ postLogoutRedirect: '/' }));

    // secure routes
    router.get('/id', msid.isAuthenticated(), mainController.getIdPage);

    router.use('/todolist',
        msid.isAuthenticated(),
        msid.hasAccess({
            accessRule: config.accessMatrix.todolist
        }),
        todolistRouter // users have to satisfy hasAccess middleware for all routes under /todolist
    );

    router.use('/dashboard',
        msid.isAuthenticated(),
        msid.hasAccess({
            accessRule: config.accessMatrix.dashboard
        }),
        dashboardRouter // users have to satisfy hasAccess middleware for all routes under /dashboard
    );

    return router;
}

Under the hood, the hasAccess middleware checks the signed-in user's ID token's groups claim to determine whether she has access to this route given the access matrix provided in appSettings.js:

    hasAccess(options: GuardOptions): RequestHandler {
        return async (req: Request, res: Response, next: NextFunction): Promise<void> => {
            if (!this.webAppSettings.accessMatrix) {
                this.logger.error(ConfigurationErrorMessages.NO_ACCESS_MATRIX_CONFIGURED);
                return next(new Error(ConfigurationErrorMessages.NO_ACCESS_MATRIX_CONFIGURED));
            }

            if (!req.session.account?.idTokenClaims) {
                this.logger.error(ErrorMessages.ID_TOKEN_CLAIMS_NOT_FOUND);
                return next(new Error(ErrorMessages.ID_TOKEN_CLAIMS_NOT_FOUND));
            }

            const checkFor = options.accessRule.hasOwnProperty(AccessControlConstants.GROUPS)
                ? AccessControlConstants.GROUPS
                : AccessControlConstants.ROLES;

            switch (checkFor) {
                case AccessControlConstants.GROUPS:
                    // ...
                    break;

                case AccessControlConstants.ROLES:
                    if (!req.session.account.idTokenClaims[AccessControlConstants.ROLES]) {
                        return res.redirect(this.webAppSettings.authRoutes.unauthorized);
                    } else {
                        const roles = req.session.account.idTokenClaims[AccessControlConstants.ROLES] as string[];

                        if (!this.checkAccessRule(req.method, options.accessRule, roles, AccessControlConstants.ROLES)) {
                            return res.redirect(this.webAppSettings.authRoutes.unauthorized);
                        }
                    }

                    next();
                    break;

                default:
                    break;
            }
        };
    };

The groups overage claim

To ensure that the token size doesn’t exceed HTTP header size limits, the Microsoft Identity Platform limits the number of object Ids that it includes in the groups claim.

If a user is member of more groups than the overage limit (150 for SAML tokens, 200 for JWT tokens, 6 for single-page applications), then the Microsoft identity platform does not emit the group IDs in the groups claim in the token. Instead, it includes an overage claim in the token that indicates to the application to query the MS Graph API to retrieve the user’s group membership.

We strongly advise you use the group filtering feature (if possible) to avoid running into group overages.

Create the overage scenario for testing

  1. You can use the BulkCreateGroups.ps1 provided in the App Creation Scripts folder to create a large number of groups and assign users to them. This will help test overage scenarios during development. Remember to change the user's objectId provided in the BulkCreateGroups.ps1 script.

When attending to overage scenarios, which requires a call to Microsoft Graph to read the signed-in user's group memberships, your app will need to have the User.Read and GroupMember.Read.All for the getMemberGroups function to execute successfully.

⚠️ For the overage scenario, make sure you have granted Admin Consent for the MS Graph API's GroupMember.Read.All scope (see the App Registration steps above).

Handle the overage scenario

When the overage occurs, the user's ID token will have the _claim_names and _claim_sources claims instead of the groups claim. Furthermore, _claim_sources claim contains the URL that we can query to get the full list of groups the user belongs to. In the hasAccess() middleware we detect if the overage, and trigger the handleOverage method to query the URL we mentioned.

    private async handleOverage(req: Request, res: Response, next: NextFunction, rule: AccessRule): Promise<void> {
        if (!req.session.account?.idTokenClaims) {
            this.logger.error(ErrorMessages.ID_TOKEN_CLAIMS_NOT_FOUND);
            return next(new Error(ErrorMessages.ID_TOKEN_CLAIMS_NOT_FOUND));
        }

        const { _claim_names, _claim_sources, ...newIdTokenClaims } = req.session.account.idTokenClaims;

        const silentRequest: SilentFlowRequest = {
            account: req.session.account,
            scopes: AccessControlConstants.GRAPH_MEMBER_SCOPES.split(' '),
        };

        try {
            // acquire token silently to be used in resource call
            const tokenResponse = await this.msalClient.acquireTokenSilent(silentRequest);

            if (!tokenResponse) return res.redirect(this.webAppSettings.authRoutes.unauthorized);

            try {
                const graphResponse = await FetchManager.callApiEndpointWithToken(
                    AccessControlConstants.GRAPH_MEMBERS_ENDPOINT,
                    tokenResponse.accessToken
                );

                /**
                 * Some queries against Microsoft Graph return multiple pages of data either due to server-side paging
                 * or due to the use of the $top query parameter to specifically limit the page size in a request.
                 * When a result set spans multiple pages, Microsoft Graph returns an @odata.nextLink property in
                 * the response that contains a URL to the next page of results. Learn more at https://docs.microsoft.com/graph/paging
                 */
                if (graphResponse.data[AccessControlConstants.PAGINATION_LINK]) {
                    try {
                        const userGroups = await FetchManager.handlePagination(
                            tokenResponse.accessToken,
                            graphResponse.data[AccessControlConstants.PAGINATION_LINK]
                        );

                        req.session.account.idTokenClaims = {
                            ...newIdTokenClaims,
                            groups: userGroups,
                        };

                        if (
                            !this.checkAccessRule(
                                req.method,
                                rule,
                                req.session.account.idTokenClaims[AccessControlConstants.GROUPS] as string[],
                                AccessControlConstants.GROUPS
                            )
                        ) {
                            return res.redirect(this.webAppSettings.authRoutes.unauthorized);
                        } else {
                            return next();
                        }
                    } catch (error) {
                        next(error);
                    }
                } else {
                    req.session.account.idTokenClaims = {
                        ...newIdTokenClaims,
                        groups: graphResponse.data['value'].map((v: any) => v.id),
                    };

                    if (
                        !this.checkAccessRule(
                            req.method,
                            rule,
                            req.session.account.idTokenClaims[AccessControlConstants.GROUPS] as string[],
                            AccessControlConstants.GROUPS
                        )
                    ) {
                        return res.redirect(this.webAppSettings.authRoutes.unauthorized);
                    } else {
                        return next();
                    }
                }
            } catch (error) {
                next(error);
            }
        } catch (error) {
            next(error);
        }
    };

More information

Configure your application:

Learn more about the Microsoft identity platform:

For more information about how OAuth 2.0 protocols work in this scenario and other scenarios, see Authentication Scenarios for Microsoft Entra ID.

Community Help and Support

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 nodejs ms-identity adal msal].

If you find a bug in the sample, raise the issue on GitHub Issues.

To provide feedback on or suggest features for Microsoft Entra ID, visit User Voice page.

Contributing

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.