Microsoft Graph Node.js Express Sample Application

repository·main·Indexed 41 days ago

https://github.com/microsoftgraph/msgraph-sample-nodeexpressapp

A sample application demonstrating how to integrate the Microsoft Graph JavaScript SDK into a Node.js Express environment to access Office 365 data. It features authentication using @azure/msal-node, session management with express-session, and examples of interacting with Microsoft Graph APIs for calendars and user profiles.

Tokens
2K
Snippets
8
Records
12
Agent score
52%

What's inside Microsoft Graph Node.js Express Sample

  1. Configure and install the sample

    main

    Follow these steps to set up your environment variables and dependencies:

    1. Rename the example.env file to .env.
    2. Open .env and update the following placeholders with the values from your Azure App Registration:
      • Replace YOUR_CLIENT_ID_HERE with your Application (client) ID.
      • Replace YOUR_CLIENT_SECRET_HERE with your client secret value.
    3. Navigate to the graph-sample directory in your terminal.
    4. Install the required dependencies using npm install.
    npm install
  2. Register a web application in Azure Active Directory

    main

    To allow the application to authenticate with Microsoft Graph, you must register it in the Azure Active Directory admin center:

    1. Navigate to the Azure Active Directory admin center.
    2. Under Manage, select App registrations and then New registration.
    3. Configure the registration with these specific values:
      • Name: Node.js Graph Sample
      • Supported account types: Accounts in any organizational directory and personal Microsoft accounts
      • Redirect URI: Set type to Web and value to http://localhost:3000/auth/callback
    4. Click Register.
    5. Copy the Application (client) ID; you will need this for configuration.
    6. Under Manage, select Certificates & secrets and click New client secret.
    7. Provide a description, select an expiration, and click Add.
    8. IMPORTANT: Copy the client secret value immediately. It will not be visible again after you leave the page.
  3. Configure session and flash middleware

    main

    The application uses express-session for session management and connect-flash for temporary messaging (like error notifications).

    Warning: The current implementation uses the default in-memory session store, which is not suitable for production environments. In production, you should use a store like Redis or a database.

    Session configuration used:

    • secret: A string used to sign the session ID cookie.
    • resave: false
    • saveUninitialized: false
    • unset: 'destroy'
    app.use(session({
      secret: 'your_secret_value_here',
      resave: false,
      saveUninitialized: false,
      unset: 'destroy'
    }));
    
    app.use(flash());
  4. Configure MSAL for Microsoft Graph authentication

    main

    The application uses @azure/msal-node to handle authentication via a ConfidentialClientApplication. Configuration is driven by environment variables and is stored in app.locals.msalClient for access throughout the application.

    Required environment variables:

    • OAUTH_CLIENT_ID: The Client ID of your registered Azure AD application.
    • OAUTH_AUTHORITY: The authority URL (e.g., https://login.microsoftonline.com/{tenantId}).
    • OAUTH_CLIENT_SECRET: The Client Secret for your application.

    Note: The sample uses an in-memory app.locals.users object to store logged-in users. For production, use a persistent storage mechanism.

    const msalConfig = {
      auth: {
        clientId: process.env.OAUTH_CLIENT_ID || '',
        authority: process.env.OAUTH_AUTHORITY,
        clientSecret: process.env.OAUTH_CLIENT_SECRET
      },
      system: {
        loggerOptions: {
          loggerCallback(loglevel, message, containsPii) {
            if (!containsPii) console.log(message);
          },
          piiLoggingEnabled: false,
          logLevel: msal.LogLevel.Verbose,
        }
      }
    };
    
    // Create msal application object
    app.locals.msalClient = new msal.ConfidentialClientApplication(msalConfig);
  5. Use the eventDateTime Handlebars helper

    main

    To display date and time values returned by the Microsoft Graph API in your Handlebars (.hbs) templates, use the eventDateTime helper. This helper parses ISO date strings and formats them into a human-readable format: M/d/yy h:mm a.

    Example usage in a template: {{eventDateTime .start.dateTime}}

    var hbs = require('hbs');
    var dateFns = require('date-fns');
    
    // Helper to format date/time sent by Graph
    hbs.registerHelper('eventDateTime', function(dateTime) {
      const date = dateFns.parseISO(dateTime);
      return dateFns.format(date, 'M/d/yy h:mm a');
    });
  6. Define the home route in the Express router

    main

    The index router defines the root path (/) for the application. When a GET request is made to /, it renders the index view template and passes a params object containing { active: { home: true } }. This object is typically used by the view engine to manage active navigation states in the UI.

    var express = require('express');
    var router = express.Router();
    
    /* GET home page. */
    router.get('/', function(req, res) {
      let params = {
        active: {
          home: true
        }
      };
    
      res.render('index', params);
    });
    
    module.exports = router;
  7. Application Route Structure

    main

    The Express application is organized into several functional routers:

    • /: Handled by indexRouter (Home/Index).
    • /auth: Handled by authRouter (Authentication logic/MSAL flows).
    • /calendar: Handled by calendarRouter (Microsoft Graph Calendar interactions).
    • /users: Handled by usersRouter (User management/profile).
    app.use('/', indexRouter);
    app.use('/auth', authRouter);
    app.use('/calendar', calendarRouter);
    app.use('/users', usersRouter);