Microsoft 365: Build a Web App with the Graph API

Are you a developer wanting to connect your web application to Microsoft 365 services? Do you need to access user data like emails, calendars, or files? You are in the right place.

Building a Microsoft 365 web app unlocks powerful integrations. You can create tools that read user profiles, manage calendars, or interact with OneDrive files. This guide shows you how to build a simple web application. It will authenticate users and access their Microsoft 365 data using the Microsoft Graph API.

We cover two popular technology stacks: Flask with Python and ASP.NET Core with C#. Choose the one that fits your skills. You will learn how to register your app, handle authentication, and make API calls. Get ready to build your first Microsoft 365 web app!

Prerequisites

Before you start building your Microsoft 365 web app, make sure you have a few things ready. You need an Azure subscription. This lets you register your application and manage its identity. You also need a Microsoft 365 account. This provides the data you will access.

For the Python/Flask example, install Python and the Flask framework. You also need the `msal` and `requests` libraries. For the ASP.NET Core/C# example, install the .NET SDK and an IDE like Visual Studio. You need basic knowledge of web development. Understanding REST APIs and OAuth 2.0 helps greatly.

Registering Your Application in Azure AD

Your web application needs an identity to interact with Microsoft 365. You give it this identity by registering it in Azure Active Directory (Azure AD). This process enables your app to use OAuth 2.0 for authentication.

First, go to the Azure portal. Navigate to “Azure Active Directory”. Then select “App registrations” and click “New registration”. Give your application a name. Choose the supported account types. For a typical web app accessing user data, select “Accounts in any organizational directory (Any Azure AD directory – Multitenant) and personal Microsoft accounts (e.g. Skype, Xbox)”.

Next, set the Redirect URI. This is where Azure AD sends the user back after they log in. For a web application, select “Web” as the platform. Enter the URL where your application’s callback function runs. For local testing, this might be `http://localhost:5000/callback` for Flask or a similar URL for ASP.NET Core.

After registration, Azure AD gives you a Client ID (also called Application ID). Note this down. You also need a client secret for a web app. Go to “Certificates & secrets” and create a new client secret. Copy the secret’s value immediately. You cannot see it again after leaving the page.

Finally, configure API permissions. Your app needs permission to access Microsoft 365 data. Go to “API permissions”. Click “Add a permission”. Select “Microsoft Graph”. Then choose “Delegated permissions”. Select the permissions your app needs. Recommended permissions include:

  • User.Read: Reads the signed-in user’s basic profile.
  • Mail.Read: Reads the signed-in user’s mail.
  • Calendars.Read: Reads the signed-in user’s calendars.

Click “Add permissions”. For delegated permissions, users consent when they first sign in. For some permissions or organizational apps, an admin might need to grant consent.

Building the Web Application

Now you build the core of your Microsoft 365 web app. We cover two popular frameworks. Choose the one you prefer.

Python/Flask Microsoft 365 Web App

Create a new Flask project. Install the necessary libraries using pip:

pip install flask msal requestsCode language: DOS .bat (dos)

Use the MSAL (Microsoft Authentication Library) for Python to handle the OAuth 2.0 flow. You need your Client ID, Client Secret, and Redirect URI from the Azure AD registration. Store these securely, perhaps in environment variables.

Here is basic code showing the authorization code flow. This code uses environment variables for sensitive information. Replace ‘YOUR_SECRET_KEY’ with a strong secret key.

from flask import Flask, render_template, request, redirect, url_for, session
import msal
import os
import request

sapp = Flask(__name__)
app.config.from_mapping(
    SECRET_KEY='YOUR_SECRET_KEY',  # Replace with a strong secret key
    CLIENT_ID=os.environ.get("CLIENT_ID"),
    CLIENT_SECRET=os.environ.get("CLIENT_SECRET"),
    AUTHORITY=os.environ.get("AUTHORITY"), #e.g., "https://login.microsoftonline.com/YOUR_TENANT_ID"
    REDIRECT_URI=os.environ.get("REDIRECT_URI"), #e.g., "http://localhost:5000/callback"
    SCOPES=["User.Read"])

# Use a file-based token cache for simplicity in this example
# In production, use a more robust storage mechanism
cache = msal.SerializableTokenCache()
if os.path.exists("msal_cache.bin"):
    cache.deserialize(open("msal_cache.bin", "r").read())

def _build_msal_app(cache=None):
    return msal.ConfidentialClientApplication(
        app.config["CLIENT_ID"],
        authority=app.config["AUTHORITY"],
        client_credential=app.config["CLIENT_SECRET"],
        token_cache=cache    )

@app.route("/")
def index():
    if not session.get("user"):
        return redirect(url_for("login"))
    # In a real app, you'd fetch and display data here
    return render_template('index.html', user=session["user"])@app.route("/login")

def login():
    msal_app = _build_msal_app(cache=cache)
    # The auto_build_authorize_request method simplifies building the auth URL
    auth_url = msal_app.get_authorization_request_url(
        app.config["SCOPES"],
        redirect_uri=app.config["REDIRECT_URI"],
        state=session.get("state", str(os.urandom(16))) # Use state to prevent CSRF
    )
    session["state"] = auth_url['state']
    return render_template("login.html", auth_url=auth_url['url'])

@app.route("/callback")
def callback():
    state = request.args.get("state")
    if state != session.get("state"):
        return "Error: State mismatch", 400 # Validate state
    code = request.args.get("code")
    if code:
        msal_app = _build_msal_app(cache=cache)
        result = msal_app.acquire_token_by_authorization_code(
            code,
            scopes=app.config["SCOPES"],
            redirect_uri=app.config["REDIRECT_URI"]
        )
        if "error" in result:
            return "Error: " + result.get("error_description")
        session["user"] = result.get("id_token_claims")
        # Save cache after acquiring token
        open("msal_cache.bin", "w").write(cache.serialize())
        return redirect(url_for("index"))
    else:
        return "Callback Error: No code received", 400

@app.route("/get_profile")
def get_profile():
  if not session.get("user"):
    return redirect(url_for("login"))
  # Get access token silently from cache
  msal_app = _build_msal_app(cache=cache)
  accounts = msal_app.get_accounts()
  result = None
  if accounts:
      result = msal_app.acquire_token_silent(app.config["SCOPES"], account=accounts[0])
  if not result or "access_token" not in result:
      # No token in cache or token expired, re-authenticate
      return redirect(url_for("login"))
  access_token = result['access_token']
  graph_data = requests.get(
  # Use token to call downstream service
      "https://graph.microsoft.com/v1.0/me",
      headers={'Authorization': 'Bearer ' + access_token},
  ).json()
  # Save cache after potential token refresh
  open("msal_cache.bin", "w").write(cache.serialize())
  return render_template('profile.html', profile=graph_data)

@app.route("/logout")
def logout():
    session.clear() # Clear Flask session
    # Clear MSAL cache for the user
    msal_app = _build_msal_app(cache=cache)
    accounts = msal_app.get_accounts()
    if accounts:
        msal_app.remove_account(accounts[0])
        open("msal_cache.bin", "w").write(cache.serialize()) # Save cache after removing account
    # Redirect to Azure AD logout endpoint
    # You need to configure a post-logout redirect URI in your Azure AD app registration
    # For simplicity, this example just clears session/cache
    # A full logout requires redirecting the user to Azure AD's end_session_endpoint
    return "Logged out successfully. <a href="/">Return home</a>"

if __name__ == "__main__":
    # Ensure environment variables are set before running
    if not all([os.environ.get("CLIENT_ID"), os.environ.get("CLIENT_SECRET"), os.environ.get("AUTHORITY"), os.environ.get("REDIRECT_URI")]):
        print("Please set CLIENT_ID, CLIENT_SECRET, AUTHORITY, and REDIRECT_URI environment variables.")
    else: 
       app.run(debug=True)Code language: Python (python)

 

This code sets up a Flask app. The `/login` route redirects the user to the Microsoft login page. The `/callback` route receives the authorization code and exchanges it for tokens. The `/get_profile` route uses the acquired access token to call the Microsoft Graph API. It retrieves the user’s profile.

Remember to create HTML templates (e.g., `index.html`, `login.html`, `profile.html`) to render the UI.

ASP.NET Core/C# Microsoft 365 Web App

Create a new ASP.NET Core Web App project. You can use the project template that includes authentication. Select “Microsoft identity platform” as the authentication type. This template automatically adds necessary packages like `Microsoft.Identity.Web`.

Install the Microsoft Graph SDK NuGet package:

Install-Package Microsoft.GraphCode language: PowerShell (powershell)

Configure your application in `appsettings.json` with your Azure AD details:

{  "AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "Domain": "[Enter the domain of your tenant, e.g. contoso.onmicrosoft.com]",
    "TenantId": "[Enter 'common', 'organizations', 'consumers' or your tenant id]",
    "ClientId": "[Enter the Client Id (aka Application Id) of your app registration]",
    "CallbackPath": "/signin-oidc"  },
  "MicrosoftGraph": {
    "Scopes": "User.Read"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*"
}Code language: JSON / JSON with Comments (json)

 

Configure authentication and add the Graph service in `Program.cs` (or `Startup.cs` for older versions):

using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.Identity.Web;
using Microsoft.Identity.Web.UI;
using Microsoft.Graph;

var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
// Configure Microsoft identity platform 

authenticationbuilder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"))
    // Add Graph service client access
    .EnableTokenAcquisitionToCallDownstreamApi(builder.Configuration.GetSection("MicrosoftGraph:Scopes").Get() )
    .AddMicrosoftGraph(builder.Configuration.GetSection("MicrosoftGraph"))
    .AddInMemoryTokenCaches(); // Use in-memory token cache for simplicity

builder.Services.AddControllersWithViews(options =>{
    // Require authenticated users for all controllers
    var policy = new AuthorizationPolicyBuilder()
        .RequireAuthenticatedUser()
        .Build();
    options.Filters.Add(new AuthorizeFilter(policy));
}).AddMicrosoftIdentityUI(); // Add UI for sign-in/sign-out

builder.Services.AddRazorPages();
var app = builder.Build();
// Configure the HTTP request pipeline.

if (!app.Environment.IsDevelopment()){
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication(); 

// Add authentication middleware
app.UseAuthorization(); // Add authorization middleware
app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.MapRazorPages();
app.Run();Code language: C# (cs)

 

This code configures the app to use Microsoft identity platform authentication. It also sets up the GraphServiceClient. The GraphServiceClient uses the authenticated user’s token to make API calls.

Create a controller to handle Graph API calls, for example, a `ProfileController`:

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Graph; // Using Microsoft Graph SDK
using System.Threading.Tasks;
using Microsoft.Identity.Web; // For GetAccountId() and GetMsalAccountId()

namespace YourWebApp.Controllers{
    [Authorize] // Ensure user is authenticated
    [MicrosoftIdentityScopedService] // Indicates this controller uses services from Microsoft.Identity.Web
    public class ProfileController : Controller
    {
        private readonly GraphServiceClient _graphServiceClient;
        // Inject the GraphServiceClient
        public ProfileController(GraphServiceClient graphServiceClient)
        {
            _graphServiceClient = graphServiceClient;
        }
        // Action to display user profile
        public async Task Index()
        {
            try
            {
                // Call the Graph API to get the user's profile
                var user = await _graphServiceClient.Me.Request().GetAsync();
                // Pass the user object to the view
                return View(user);
            }
            catch (ServiceException ex)
            {
                // Handle Graph API errors, e.g., insufficient permissions
                ViewData["Error"] = $"Graph API Error: {ex.Message}";
                return View("Error"); // Redirect to an error view
            }
        }
    }
}Code language: C# (cs)

 

This controller uses the injected `GraphServiceClient`. It calls the `/me` endpoint to get the signed-in user’s profile. The `[Authorize]` attribute ensures only logged-in users can access this controller. Create a corresponding Razor view (e.g., `Views/Profile/Index.cshtml`) to display the user data.

Retrieving Data from Microsoft 365

You use the Microsoft Graph API to get data from Microsoft 365. The Graph API is a single endpoint (`https://graph.microsoft.com`) for accessing various Microsoft services. You make HTTP requests to specific URLs, called endpoints, to get data.

For example, to get the signed-in user’s profile, you use the `/me` endpoint. The full URL is `https://graph.microsoft.com/v1.0/me`. To get the user’s emails, you use `/me/messages`. For calendar events, use `/me/events`.

You must include the access token in the `Authorization` header of your HTTP request. The header value looks like `Bearer YOUR_ACCESS_TOKEN`. Both the Python `requests` library and the ASP.NET Core `GraphServiceClient` handle this for you after you acquire the token.

In Python, after getting the access token:

import requests

access_token = "YOUR_ACCESS_TOKEN" # Get this from MSAL
graph_url = "https://graph.microsoft.com/v1.0/me/messages" 
# Example: Get emails
headers = {
    'Authorization': 'Bearer ' + access_token,
    'Content-Type': 'application/json'}

response = requests.get(graph_url, headers=headers)
if response.status_code == 200:
    emails = response.json()
    # Process the emails data
    print(emails)
else:
    print(f"Error fetching emails: {response.status_code} - {response.text}")Code language: Python (python)

In ASP.NET Core using the Graph SDK, you use the `GraphServiceClient` instance:

using Microsoft.Graph;
using System.Threading.Tasks;

// Assume _graphServiceClient is injected
public async Task<List> GetUserEmailsAsync(){
    try
    {
        // Get the first 10 emails
        var messages = await _graphServiceClient.Me.Messages
            .Request()
            .Top(10) // Limit the number of results
            .GetAsync();
        return messages.ToList(); // Returns a List of messages
    }
    catch (ServiceException ex)
    {
        // Handle exceptions, e.g., InsufficientPermissions
        Console.WriteLine($"Error getting emails: {ex.Message}");
        return null; // Or throw the exception
    }
}

public async Task<List> GetUserCalendarEventsAsync(){
    try
    {
        // Get calendar events for the next 7 days
        var queryOptions = new List()
        {
            new QueryOption("startDateTime", DateTimeOffset.UtcNow.ToString("o")),            new QueryOption("endDateTime", DateTimeOffset.UtcNow.AddDays(7).ToString("o"))
        };
        var events = await _graphServiceClient.Me.Calendar.Events            .Request(queryOptions)
            .GetAsync();
        return events.ToList(); // Returns a List of events
    }
    catch (ServiceException ex)
    {
        Console.WriteLine($"Error getting events: {ex.Message}");
        return null;
    }
}Code language: C# (cs)

The Graph API returns data in JSON format. You parse the JSON response to extract the information you need. For large datasets like emails or events, the response might be paginated. You need to handle pagination to fetch all results if necessary. Always include error handling. Check the response status code and handle potential API errors, such as insufficient permissions.

Displaying the Data in the Web Application

After you retrieve the data from Microsoft 365, you need to show it to the user. Your web application’s view templates handle this. You pass the data you fetched from the Graph API to the view. Then, you use the template language (like Jinja2 for Flask or Razor for ASP.NET Core) to render the data.

For example, if you fetch the user profile, you might display their name and email. In a Flask template (profile.html):

<!DOCTYPE html>
<html>
<head>
    <title>User Profile</title>
</head>
<body>
    <h2>Your Microsoft 365 Profile</h2>
    {% if profile %}
        <p><strong>Display Name:</strong> {{ profile.displayName }}</p>
        <p><strong>Given Name:</strong> {{ profile.givenName }}</p>
        <p><strong>Surname:</strong> {{ profile.surname }}</p>
        <p><strong>User Principal Name:</strong> {{ profile.userPrincipalName }}</p>
    {% else %}
        <p>Could not load profile data.</p>
    {% endif %}
    <p><a href="/">Back to Home</a></p>
</body>
</html>Code language: HTML, XML (xml)

In an ASP.NET Core Razor view (Views/Profile/Index.cshtml), assuming you passed a User object as the model:

@model Microsoft.Graph.User@{
    ViewData["Title"] = "User Profile";
}
<h2>Your Microsoft 365 Profile</h2>
@if (Model != null){
    <p><strong>Display Name:</strong> @Model.DisplayName</p>
    <p><strong>Given Name:</strong> @Model.GivenName</p>
    <p><strong>Surname:</strong> @Model.Surname</p>
    <p><strong>User Principal Name:</strong> @Model.UserPrincipalName</p>
}else{
    <p>Could not load profile data.</p>
    @if (ViewData["Error"] != null)
    {
        <p><strong>Error:</strong> @ViewData["Error"]</p>
    }}
<p><a asp-area="" asp-controller="Home" asp-action="Index">Back to Home</a></p>Code language: C# (cs)

For displaying lists of items like emails or calendar events, you typically use loops in your template. You iterate through the list of items and display relevant details for each one. Use HTML elements like tables, lists (`ul`/`ol`), or cards to structure the data. Make sure the presentation is clear and easy for the user to understand.

Security Considerations

Building a Microsoft 365 web app requires careful attention to security. You handle sensitive user data and interact with powerful APIs. Securely store and manage your application’s credentials, like the client secret. Do not hardcode secrets directly in your code. Use environment variables or secure configuration systems.

Always use HTTPS for all communication between your application, the user’s browser, and Microsoft services. This encrypts data in transit. Validate all user input to prevent common web vulnerabilities like injection attacks. Implement proper authorization checks within your application. Ensure that an authenticated user can only access data they own or are permitted to see.

Follow the principle of least privilege when requesting API permissions in Azure AD. Only request the permissions your application absolutely needs to function. Requesting excessive permissions increases the risk if your application is compromised.

Best Practices

Adopt these best practices for building robust Microsoft 365 web apps. Use a modern authentication library like MSAL (Microsoft Authentication Library). MSAL simplifies the authentication flow and handles token caching and refreshing. For applications hosted in Azure, use Managed Identities where possible. Managed Identities provide an identity for your service without needing to manage credentials yourself.

Implement thorough error handling and logging. Catch exceptions when calling the Graph API and provide informative error messages to the user or log them for debugging. Monitor your application’s activity and performance. Follow the specific best practices recommended by Microsoft for using the Microsoft Graph API. This includes efficient querying and handling rate limits.

Troubleshooting Common Issues

You might encounter issues when building your Microsoft 365 web app. Authentication errors are common. Check your Azure AD app registration details: Client ID, Client Secret, and Redirect URI must match exactly. Ensure your token is not expired. MSAL libraries usually handle token refreshing automatically, but verify the configuration.

Permission errors mean your application lacks the necessary rights. Go back to your Azure AD app registration. Verify that you added the required API permissions (scopes). Remember that for delegated permissions, the signed-in user must also have permission to access the data. Incorrect API endpoint URLs cause errors. Double-check the Graph API documentation for the correct endpoint path and version (e.g., `v1.0` or `beta`). Invalid JSON responses can happen if the API returns an error or unexpected data. Inspect the raw response to diagnose the problem.

Conclusion

You now understand the key steps to build a simple Microsoft 365 web app. You register your application in Azure AD, set up authentication using libraries like MSAL or Microsoft.Identity.Web, and call the Microsoft Graph API to access data. We covered examples in Flask/Python and ASP.NET Core/C#.

Integrating your web application with Microsoft 365 opens up many possibilities. You can automate tasks, provide users with custom views of their data, and build powerful business applications. Explore other Microsoft Graph API endpoints. Access calendars, contacts, OneDrive files, and more. Start building your own custom integrations today!

Follow SOS-Admins on Google

SOS-Admins is your ultimate source for the latest updates, exclusive guides, and news. Don t miss our upcoming content, add us to your favorites and stay connected with the community on Google!