How can I initialize GraphServiceClient by providing an acessToken using Microsoft.Graph v5 sdk

Wasi Hyder 0 Reputation points
2024-02-21T07:28:38.5633333+00:00

This is Microsoft.Graph v4 implementation. Here I'm trying to invite a user to my entra id through an asp.net core web api (.net 8) . I'm creating GraphServiceClient with the accessToken i received in my request. This is working fine but the problem is now we have Microsoft.Graph v5 which is latest and v4 is outdated and in v5 we dont have DelegateAuthenticationProvider. Kindly help me out in updating same implementation v5 sdk.

var authorizationHeader = HttpContext.Request.Headers["Authorization"].FirstOrDefault();
var accessToken = authorizationHeader.Substring("Bearer ".Length);
var _graphServiceClient = new GraphServiceClient(
                new DelegateAuthenticationProvider(
                    requestMessage =>
                    {
                        requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", accessToken);
                        return Task.FromResult(0);
                    }));
var invitation = new Invitation
{
    InvitedUserEmailAddress = userEmail,
    SendInvitationMessage = true,
    InviteRedirectUrl = "https://loremipsum.app",
    InvitedUserType = "guest" // default is guest,member
};
var invite = await _graphServiceClient.Invitations
    .Request()
    .AddAsync(invitation);
return Ok(invite);
Microsoft Security | Microsoft Graph
{count} votes

1 answer

Sort by: Most helpful
  1. CarlZhao-MSFT 46,371 Reputation points
    2024-02-21T10:07:40.9133333+00:00

    Hi @Wasi Hyder In v5, you can obtain an access token using the TokenCredential method. This method is more flexible and supports various authentication schemes (including user-based authentication, client credentials, etc.).

    After that, pass the tokenCredential object to the GraphServiceClient class to instantiate the graphServiceClient object.

    using Microsoft.Graph;
    using Microsoft.Graph.Auth;
    using Microsoft.Identity.Client; 
    
    // Your existing code to extract the access token from the request headers
    var authorizationHeader = HttpContext.Request.Headers["Authorization"].FirstOrDefault();
    var accessToken = authorizationHeader.Substring("Bearer ".Length);
    
    // Create a TokenCredential using the access token
    var tokenCredential = new AccessTokenCredential(accessToken);
    
    // Initialize the GraphServiceClient with the TokenCredential
    var graphServiceClient = new GraphServiceClient(tokenCredential);
    

    Hope this helps.

    If the reply is helpful, please click Accept Answer and kindly upvote it. If you have additional questions about this answer, please click Comment.

    1 person found this answer helpful.

Your answer

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