Search code examples
.netmicrosoft-graph-apihttpclient.net-7.0

.NET 7.0: HttpClient not sending DefaultRequestHeaders when executing a 301 redirect


I'm puzzled at seeing how a HttpClient instance is not sending DefaultRequestHeaders (specifically the Authorization header) when following a 301 redirect. Considering the name of the collection (i.e., DefaultRequestHeaders) I would expect these to be always sent. Is this a bug or a behavior to be expected?

To provide a bit more context to the failure I'm facing, I'm trying to call the Microsoft Graph getOffice365GroupsActivityDetail API and starting yesterday this API is forcing with a 301 http response code a redirect to location https://reportsweu.office.com/graph/v1.0/data/[tenant-id]/Microsoft.O365Reporting.getOffice365GroupsActivityDetail and the unexpected thing is that a different token seems to be required since making a call with the bearer token valid for calling the original API (i.e. https://graph.microsoft.com/v1.0/reports/getOffice365GroupsActivityDetail) fails with a "S2S auth failed" error.


Solution

  • I just now discovered that this behavior is by design as the documentation on HttpClientHandler.AllowAutoRedirect Property states:

    The Authorization header is cleared on auto-redirects and the handler automatically tries to re-authenticate to the redirected location. No other headers are cleared. In practice, this means that an application can't put custom authentication information into the Authorization header if it is possible to encounter redirection. Instead, the application must implement and register a custom authentication module.

    To me this behavior is not intuitive as after the 301 redirect the HttpClient still shows the header as present in the DefaultRequestHeaders collection and yet it will not be sent when the redirect is followed. At this point it's probably better to add this header to the Headers collection on the HttpRequestMessage object other than to the DefaultRequestHeaders collection on the HttpClient object as this allows greater control over adding it or not to the new HttpRequestMessage object required for following the redirect.