Share via

Azure AD Microsoft Identity Web App Authentication with GraphServiceClient

Venkata Ratnam Vemula 0 Reputation points
2024-07-19T00:38:00.7+00:00

We have a web application using Azure AD authentication that use GraphServiceClient to get the user details, such as DisplayName, Email and Photo. I have updated to the latest version of Graph (from 4.40.0 to 5.56.0), which is saying "DelegateAuthenticationProvider" not found. Here is the code.

May I know, how we can connect to GraphServiceClient?

services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)

.AddMicrosoftIdentityWebApp(options =>

{

Configuration.Bind("AzureAd", options);

options.Prompt = "select_account";

options.Events ??= new OpenIdConnectEvents();

var onTokenValidated = options.Events.OnTokenValidated;

options.Events.OnTokenValidated = async context =>

{

//Runs after user is authenticated

//Get user data

var tokenAcquisition = context.HttpContext.RequestServices

.GetRequiredService<ITokenAcquisition>();

var graphClient = new GraphServiceClient(

new DelegateAuthenticationProvider(async (request) =>

{

var token = await tokenAcquisition

.GetAccessTokenForUserAsync(GraphConstants.Scopes, user: context.Principal);

request.Headers.Authorization =

new AuthenticationHeaderValue("Bearer", token);

})

);

// Get user information from Graph

var user = await graphClient.Me.Request()

.Select(u => new

{

u.DisplayName,

u.Mail,

u.UserPrincipalName,

})

.GetAsync();

context.Principal?.AddUserGraphInfo(user);

//Get the user's photo

// If the user doesn't have a photo, this throws

try

{

var photo = await graphClient.Me

.Photos["48x48"]

.Content

.Request()

.GetAsync();

context.Principal?.AddUserGraphPhoto(photo);

}

catch (ServiceException ex)

{

if (ex.IsMatch("ErrorItemNotFound") ||

ex.IsMatch("ConsumerPhotoIsNotSupported"))

{

context.Principal?.AddUserGraphPhoto(null);

}

}

onTokenValidated?.Invoke(context);

//return Task.CompletedTask;

};

}) // Add ability to call web API (Graph)

// and get access tokens

.EnableTokenAcquisitionToCallDownstreamApi(options =>

{

Configuration.Bind("AzureAd", options);

}, GraphConstants.Scopes)

// Add a GraphServiceClient via dependency injection

.AddMicrosoftGraph(options =>

{

options.Scopes = string.Join(' ', GraphConstants.Scopes);

})

// Use in-memory token cache

// See https://github.com/AzureAD/microsoft-identity-web/wiki/token-cache-serialization

.AddInMemoryTokenCaches();

Microsoft Security | Microsoft Graph
Microsoft Security | Microsoft Identity Manager
{count} votes

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.