Tutorial: Access Microsoft Graph from a secured app as the user

Learn how to access Microsoft Graph from a web app running on Azure App Service.

Diagram that shows accessing Microsoft Graph.

You want to add access to Microsoft Graph from your web app and perform some action as the signed-in user. This section describes how to grant delegated permissions to the web app and get the signed-in user's profile information from Azure Active Directory (Azure AD).

In this tutorial, you learn how to:

  • Grant delegated permissions to a web app.
  • Call Microsoft Graph from a web app for a signed-in user.

If you don't have an Azure subscription, create an Azure free account before you begin.

Prerequisites

Grant front-end access to call Microsoft Graph

Now that you've enabled authentication and authorization on your web app, the web app is registered with the Microsoft identity platform and is backed by an Azure AD application. In this step, you give the web app permissions to access Microsoft Graph for the user. (Technically, you give the web app's Azure AD application the permissions to access the Microsoft Graph Azure AD application for the user.)

In the Azure portal menu, select Azure Active Directory or search for and select Azure Active Directory from any page.

Select App registrations > Owned applications > View all applications in this directory. Select your web app name, and then select API permissions.

Select Add a permission, and then select Microsoft APIs and Microsoft Graph.

Select Delegated permissions, and then select User.Read from the list. Select Add permissions.

Configure App Service to return a usable access token

The web app now has the required permissions to access Microsoft Graph as the signed-in user. In this step, you configure App Service authentication and authorization to give you a usable access token for accessing Microsoft Graph. For this step, you need to add the User.Read scope for the downstream service (Microsoft Graph): https://graph.microsoft.com/User.Read.

Important

If you don't configure App Service to return a usable access token, you receive a CompactToken parsing failed with error code: 80049217 error when you call Microsoft Graph APIs in your code.

Go to Azure Resource Explorer and using the resource tree, locate your web app. The resource URL should be similar to https://resources.azure.com/subscriptions/subscriptionId/resourceGroups/SecureWebApp/providers/Microsoft.Web/sites/SecureWebApp20200915115914.

The Azure Resource Explorer is now opened with your web app selected in the resource tree. At the top of the page, select Read/Write to enable editing of your Azure resources.

In the left browser, drill down to config > authsettingsV2.

In the authsettingsV2 view, select Edit. Find the login section of identityProviders -> azureActiveDirectory and add the following loginParameters settings: "loginParameters":[ "response_type=code id_token","scope=openid offline_access profile https://graph.microsoft.com/User.Read" ] .

"identityProviders": {
    "azureActiveDirectory": {
      "enabled": true,
      "login": {
        "loginParameters":[
          "response_type=code id_token",
          "scope=openid offline_access profile https://graph.microsoft.com/User.Read"
        ]
      }
    }
  }
},

Save your settings by selecting PUT. This setting can take several minutes to take effect. Your web app is now configured to access Microsoft Graph with a proper access token. If you don't, Microsoft Graph returns an error saying that the format of the compact token is incorrect.

Call Microsoft Graph

Your web app now has the required permissions and also adds Microsoft Graph's client ID to the login parameters.

Using the Microsoft.Identity.Web library, the web app gets an access token for authentication with Microsoft Graph. In version 1.2.0 and later, the Microsoft.Identity.Web library integrates with and can run alongside the App Service authentication/authorization module. Microsoft.Identity.Web detects that the web app is hosted in App Service and gets the access token from the App Service authentication/authorization module. The access token is then passed along to authenticated requests with the Microsoft Graph API.

To see this code as part of a sample application, see the sample on GitHub.

Note

The Microsoft.Identity.Web library isn't required in your web app for basic authentication/authorization or to authenticate requests with Microsoft Graph. It's possible to securely call downstream APIs with only the App Service authentication/authorization module enabled.

However, the App Service authentication/authorization is designed for more basic authentication scenarios. For more complex scenarios (handling custom claims, for example), you need the Microsoft.Identity.Web library or Microsoft Authentication Library. There's a little more setup and configuration work in the beginning, but the Microsoft.Identity.Web library can run alongside the App Service authentication/authorization module. Later, when your web app needs to handle more complex scenarios, you can disable the App Service authentication/authorization module and Microsoft.Identity.Web will already be a part of your app.

Install client library packages

Install the Microsoft.Identity.Web and Microsoft.Identity.Web.MicrosoftGraph NuGet packages in your project by using the .NET Core command-line interface or the Package Manager Console in Visual Studio.

.NET Core command line

Open a command line, and switch to the directory that contains your project file.

Run the install commands.

dotnet add package Microsoft.Identity.Web.MicrosoftGraph

dotnet add package Microsoft.Identity.Web

Package Manager Console

Open the project/solution in Visual Studio, and open the console by using the Tools > NuGet Package Manager > Package Manager Console command.

Run the install commands.

Install-Package Microsoft.Identity.Web.MicrosoftGraph

Install-Package Microsoft.Identity.Web

Startup.cs

In the Startup.cs file, the AddMicrosoftIdentityWebApp method adds Microsoft.Identity.Web to your web app. The AddMicrosoftGraph method adds Microsoft Graph support.

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Identity.Web;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;

// Some code omitted for brevity.
public class Startup
{
    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
                .AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAd"))
                    .EnableTokenAcquisitionToCallDownstreamApi()
                        .AddMicrosoftGraph(Configuration.GetSection("Graph"))
                        .AddInMemoryTokenCaches();

        services.AddRazorPages();
    }
}

appsettings.json

AzureAd specifies the configuration for the Microsoft.Identity.Web library. In the Azure portal, select Azure Active Directory from the portal menu and then select App registrations. Select the app registration created when you enabled the App Service authentication/authorization module. (The app registration should have the same name as your web app.) You can find the tenant ID and client ID in the app registration overview page. The domain name can be found in the Azure AD overview page for your tenant.

Graph specifies the Microsoft Graph endpoint and the initial scopes needed by the app.

{
  "AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "Domain": "fourthcoffeetest.onmicrosoft.com",
    "TenantId": "[tenant-id]",
    "ClientId": "[client-id]",
    // To call an API
    "ClientSecret": "[secret-from-portal]", // Not required by this scenario
    "CallbackPath": "/signin-oidc"
  },

  "Graph": {
    "BaseUrl": "https://graph.microsoft.com/v1.0",
    "Scopes": "user.read"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}

Index.cshtml.cs

The following example shows how to call Microsoft Graph as the signed-in user and get some user information. The GraphServiceClient object is injected into the controller, and authentication has been configured for you by the Microsoft.Identity.Web library.

using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Graph;
using System.IO;
using Microsoft.Identity.Web;
using Microsoft.Extensions.Logging;

// Some code omitted for brevity.

[AuthorizeForScopes(Scopes = new[] { "user.read" })]
public class IndexModel : PageModel
{
    private readonly ILogger<IndexModel> _logger;
    private readonly GraphServiceClient _graphServiceClient;

    public IndexModel(ILogger<IndexModel> logger, GraphServiceClient graphServiceClient)
    {
        _logger = logger;
        _graphServiceClient = graphServiceClient;
    }

    public async Task OnGetAsync()
    {
        try
        {
            var user = await _graphServiceClient.Me.Request().GetAsync();
            ViewData["Me"] = user;
            ViewData["name"] = user.DisplayName;

            using (var photoStream = await _graphServiceClient.Me.Photo.Content.Request().GetAsync())
            {
                byte[] photoByte = ((MemoryStream)photoStream).ToArray();
                ViewData["photo"] = Convert.ToBase64String(photoByte);
            }
        }
        catch (Exception ex)
        {
            ViewData["photo"] = null;
        }
    }
}

Clean up resources

If you're finished with this tutorial and no longer need the web app or associated resources, clean up the resources you created.

Next steps

In this tutorial, you learned how to:

  • Grant delegated permissions to a web app.
  • Call Microsoft Graph from a web app for a signed-in user.