Skip to content

Adding HttpRequestMessage logging handler causes unauthorized call #622

@LockTar

Description

@LockTar

I'm trying to upgrade to v5 of the .NET SDK. In v4 we have a handler that logs the HttpRequestMessage.
The code is slightly changed in v5 in comparison with v4.

I now following the documentation in the repo and following the documentation in the Microsoft docs.

I think the documentation of Microsoft docs is better because the documentation here in the repository uses an overload of GraphClientFactory.CreateDefaultHandlers(authenticationProvider); that doesn't exist anymore.
So I'm following the Microsoft docs with the following code:

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

var authProvider = new AzureIdentityAuthenticationProvider(clientSecretCredential, scopes);

var handlers = GraphClientFactory.CreateDefaultHandlers();

// Add logging handler before the compression handler. Compression handler is created by CreateDefaultHandlers()
HttpRequestMessageLoggingHandler loggingHandler = new();
handlers.Insert(0, loggingHandler);

var httpClient = GraphClientFactory.Create(handlers);

var graphClient = new Microsoft.Graph.Beta.GraphServiceClient(httpClient, authProvider);

Simple logging handler:

public class HttpRequestMessageLoggingHandler : DelegatingHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage httpRequest, CancellationToken cancellationToken)
    {
        // log the request before it goes out.
        Console.WriteLine($"Sending request => method: '{httpRequest.Method.Method}', uri: '{httpRequest.RequestUri?.AbsoluteUri}'");

        // Always call base.SendAsync so that the request is forwarded through the pipeline.
        HttpResponseMessage httpResponse = await base.SendAsync(httpRequest, cancellationToken);

        // log the response as it comes back.
        Console.WriteLine(
            $"Received response => httpStatusCode: {(int)httpResponse.StatusCode}, reason: '{httpResponse.ReasonPhrase}'");

        return httpResponse;
    }
}

Expected behavior

Getting log of the request through my HttpRequestMessageLoggingHandler and result of the call that I make to the MS Graph.

Actual behavior

Steps to reproduce the behavior

Follow above code to create graph service client and make a call to an endpoint. You will get a 401.
User? user = await graphClient.Me.GetAsync();

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions