1

Context

I have a working ASP.NET Core Web App, which uses Entra ID authentication:

builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
    .AddInMemoryTokenCaches();

For this authentication to work I've created an Azure App registration and the configuration of the authentication contains the respective Client ID, Client secret and Tenant Id. I've added the necessary graph permissions for the Azure App registration.

I would like to call the Graph API in this web applicationfor example:

var meeting = new OnlineMeeting() { Subject = "demo meeting" };
var result = await graphClient.Me.OnlineMeetings.PostAsync(meeting);

All sample code I found is either uses device flow to get the graphClient, or uses depreciated or breaking changed authentication to create the graphClient

Question

How can I create a graphClient?

1
  • You are using Graph sdk v5 as you have OnlineMeetings.PostAsync(meeting);, so that you can create a web mvc app in .net 8 via VS 2022 and choose Microsoft Identity platform as Authentication type, .net 7 template uses v4 SDK. then you will integrate AAD auth into your web app, then follow the code snippets shared below to add AddMicrosoftGraph, then you can get GraphServiceClient after injecting into Controller. Because you are using graphClient.Me so that Aad auth is necessary. Commented May 3, 2024 at 6:30

2 Answers 2

2

Your appsettings.json should contain something like this:

{
  "AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "ClientId": "<client_app_id>",
    "TenantId": "common",

   // To call an API
   "ClientCredentials": [
    {
      "SourceType": "ClientSecret",
      "ClientSecret":"<client_secret>"
    }
  ]
 },
 "GraphV1": {
    "BaseUrl": "https://graph.microsoft.com/v1.0",
    "Scopes": ["<scope>"]
    }
}

Add NuGet packages Microsoft.Identity.Web and Microsoft.Identity.Web.GraphServiceClient.

To initialize Graph service client:

using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.Identity.Web;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services
  .AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
  .AddMicrosoftIdentityWebApp(builder.Configuration, "AzureAd")
      .EnableTokenAcquisitionToCallDownstreamApi()
          .AddMicrosoftGraph(builder.Configuration.GetSection("GraphV1"))
      .AddInMemoryTokenCaches();

Now in your controller, add GraphServiceClient into the constructor, it should be automatically resolved.

public HomeController(ILogger<HomeController> logger, GraphServiceClient graphClient)
{
    _logger = logger;
    _client = graphClient;
}

Be aware that with client secret, you can't call me endpoint, you need to call users/{user_id}.

var meeting = new OnlineMeeting() { Subject = "demo meeting" };
var result = await graphClient.Users["{user_id}"].OnlineMeetings.PostAsync(meeting);
Sign up to request clarification or add additional context in comments.

1 Comment

Many thx. interestingly I can successfully call the me endpoint to. Although neither with me, neither with the userid (and also this userid is set up as organizer) the meeting does not show up in the user's calendar, but this is an other story... stackoverflow.com/q/78424960/1157814
2

The GraphServiceClient constructor takes a TokenProvider as first parameter, so you can use a ClientSecretCredential as below (from Microsoft documentation):

// The client credentials flow requires that you request the
// /.default scope, and pre-configure your permissions on the
// app registration in Azure. An administrator must grant consent
// to those permissions beforehand.
var scopes = new[] { "https://graph.microsoft.com/.default" };

// Values from app registration
var clientId = "YOUR_CLIENT_ID";
var tenantId = "YOUR_TENANT_ID";
var clientSecret = "YOUR_CLIENT_SECRET";

// using Azure.Identity;
var options = new ClientSecretCredentialOptions
{
    AuthorityHost = AzureAuthorityHosts.AzurePublicCloud,
};

// https://learn.microsoft.com/dotnet/api/azure.identity.clientsecretcredential
var clientSecretCredential = new ClientSecretCredential(
    tenantId, clientId, clientSecret, options);

var graphClient = new GraphServiceClient(clientSecretCredential, scopes);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.