Search code examples
c#.netmicrosoft-graph-api

How can i add request adapter in updated version of Microsoft.Graph?


I am new in .NET C#. I have no idea how can I add request adapter. I have old version code available but that is not working in latest version. Please guide me how can I fix this.

OLD CODE

        private GraphServiceClient CreateGraphServiceClient()
        {
            var scopes = new[] { "https://graph.microsoft.com/.default" };
            var tenantId = _configuration["Microsoft-Graph:tenantId"];
            var clientId = _configuration["Microsoft-Graph:clientId"];
            var clientSecret = _configuration["Microsoft-Graph:clientSecretValue"];
            var confidentialClient = ConfidentialClientApplicationBuilder
                 .Create(clientId)
                 .WithAuthority($"https://login.microsoftonline.com/" + tenantId + "/v2.0")
                 .WithClientSecret(clientSecret)
                 .Build();
            GraphServiceClient graphClient = new GraphServiceClient(new DelegateAuthenticationProvider(async (requestMessage) =>
            {
                // Retrieve an access token for Microsoft Graph (gets a fresh token if needed).
                var authResult = await confidentialClient.AcquireTokenForClient(scopes).ExecuteAsync();

                // Add the access token in the Authorization header of the API
                requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken);
            }));
            return graphClient;
        }

LATEST CODE

 public static GraphServiceClient Create()
 {
     var scopes = new[] {"https://graph.micorsoft.com/.default"};
     var tenantId = "";
     var clientId = "";
     var clientSecret = "";


     GraphServiceClient graphClient = new GraphServiceClient();

     return graphClient;
 }

Any solution appreciated!


Solution

  • There are many ways to do that. Using your example we can do something like that:

     public static GraphServiceClient Create()
     {
         var scopes = new[] {"https://graph.micorsoft.com/.default"};
         var tenantId = "";
         var clientId = "";
         var clientSecret = "";
    
         var clientSecretCredential = 
              new ClientSecretCredential(tenantId, clientId, clientSecret);
         var graphClient = new GraphServiceClient(clientSecretCredential, scopes);
    
         return graphClient;
     }