5

My code is making an HTTP GET to a web service URL that requires basic authentication.

I've implemented this using an HttpClient with an HttpClientHandler that has the Credentials property defined.

This all works perfectly.. Except for one of my use-cases where I'm making the authenticated GET to: http://somedomain.com which redirects to http://www.somedomain.com.

It seems that the HttpClientHandler clears the authentication header during the redirect. How can I prevent this? I want the credentials to be sent regardless of redirects.

This is my code:

// prepare the request
var request = new HttpRequestMessage(method, url);
using (var handler = new HttpClientHandler { Credentials = new NetworkCredential(username, password) , PreAuthenticate = true })
using (var client = new HttpClient(handler))
{
    // send the request
    var response = await client.SendAsync(request);

Note: this is a related question: Keeping HTTP Basic Authentification alive while being redirected But since I'm using different classes for making the request, there might be a better, more specific solution

slugster
  • 49,403
  • 14
  • 95
  • 145
talkol
  • 12,564
  • 11
  • 54
  • 64
  • side note, I think the designed behavior makes no sense in this case. I set the credentials as part of my client, not per a specific URI (the request). Since the same client can perform multiple requests and the authorization will be sent regardless of their URIs, this is quite silly – talkol Oct 21 '13 at 11:59

2 Answers2

3

The default HttpClientHandler uses the same HttpWebRequest infrastructure under the covers. Instead of assigning a NetworkCredential to the Credentials property, create a CredentialCache and assign that.

This is what I use in place of the AutoRedirect and with a little async/await fairy dust it would probably be a whole lot prettier and more reliable.

 public class GlobalRedirectHandler : DelegatingHandler {

    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) {
        var tcs = new TaskCompletionSource<HttpResponseMessage>();

        base.SendAsync(request, cancellationToken)
            .ContinueWith(t => {
                HttpResponseMessage response;
                try {
                    response = t.Result;
                }
                catch (Exception e) {
                    response = new HttpResponseMessage(HttpStatusCode.ServiceUnavailable);
                    response.ReasonPhrase = e.Message;
                }
                if (response.StatusCode == HttpStatusCode.MovedPermanently
                    || response.StatusCode == HttpStatusCode.Moved
                    || response.StatusCode == HttpStatusCode.Redirect
                    || response.StatusCode == HttpStatusCode.Found
                    || response.StatusCode == HttpStatusCode.SeeOther
                    || response.StatusCode == HttpStatusCode.RedirectKeepVerb
                    || response.StatusCode == HttpStatusCode.TemporaryRedirect

                    || (int)response.StatusCode == 308) 
                {

                    var newRequest = CopyRequest(response.RequestMessage);

                    if (response.StatusCode == HttpStatusCode.Redirect 
                        || response.StatusCode == HttpStatusCode.Found
                        || response.StatusCode == HttpStatusCode.SeeOther)
                    {
                        newRequest.Content = null;
                        newRequest.Method = HttpMethod.Get;

                    }
                    newRequest.RequestUri = response.Headers.Location;

                    base.SendAsync(newRequest, cancellationToken)
                        .ContinueWith(t2 => tcs.SetResult(t2.Result));
                }
                else {
                    tcs.SetResult(response);
                }
            });

        return tcs.Task;
    }

    private static HttpRequestMessage CopyRequest(HttpRequestMessage oldRequest) {
        var newrequest = new HttpRequestMessage(oldRequest.Method, oldRequest.RequestUri);

        foreach (var header in oldRequest.Headers) {
            newrequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
        }
        foreach (var property in oldRequest.Properties) {
            newrequest.Properties.Add(property);
        }
        if (oldRequest.Content != null) newrequest.Content = new StreamContent(oldRequest.Content.ReadAsStreamAsync().Result);
        return newrequest;
    }
}
Darrel Miller
  • 139,164
  • 32
  • 194
  • 243
  • The problem with CredentialCache is that I need to know prematurely the URI post redirection - which I don't. The API endpoint is configurable by users and these users might forget to give the www, or decide to buy a new domain some day.. – talkol Oct 21 '13 at 11:54
  • 1
    @talkol Ok. Then turn off the autoredirect and write your own message handler to do the redirect. It's fairly easy to do. Just be aware of the security concerns of sending those credentials to any arbitrary site. – Darrel Miller Oct 21 '13 at 12:27
  • yeah thanks, that's what I ended up doing. with async-await fairy dust of course ;) – talkol Oct 21 '13 at 12:40
  • @DarrelMiller See my answer, I improved your code a bit and also included a simple check to avoid sending the credentials to different hosts. – Jürgen Steinblock Feb 18 '20 at 09:28
0

I used @DarrelMiller 's solution and it works. However, I did some improvements

I refactored the code so everything is in CopyRequest which now takes the response as an argument.

var newRequest = CopyRequest(response);

base.SendAsync(newRequest, cancellationToken)
    .ContinueWith(t2 => tcs.SetResult(t2.Result));

This is the CopyRequest method with my improvements

  • Instead of creating a new StreamContent and set it to null for Redirect / Found / SeeOther the content is only set if necesarry.
  • RequestUri is only set if Location is set and takes into account that it may not be a relative uri.
  • Most important: I check for the new Uri and if the host does not match I do not copy the autorization header, to prevent leaking your credentials to an external host.
private static HttpRequestMessage CopyRequest(HttpResponseMessage response)
{
    var oldRequest = response.RequestMessage;

    var newRequest = new HttpRequestMessage(oldRequest.Method, oldRequest.RequestUri);

    if (response.Headers.Location != null)
    {
        if (response.Headers.Location.IsAbsoluteUri)
        {
            newRequest.RequestUri = response.Headers.Location;
        }
        else
        {
            newRequest.RequestUri = new Uri(newRequest.RequestUri, response.Headers.Location);
        }
    }

    foreach (var header in oldRequest.Headers)
    {
        if (header.Key.Equals("Authorization", StringComparison.OrdinalIgnoreCase) && !(oldRequest.RequestUri.Host.Equals(newRequest.RequestUri.Host)))
        {
            //do not leak Authorization Header to other hosts
            continue;
        }
        newRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
    }

    foreach (var property in oldRequest.Properties)
    {
        newRequest.Properties.Add(property);
    }

    if (response.StatusCode == HttpStatusCode.Redirect
        || response.StatusCode == HttpStatusCode.Found
        || response.StatusCode == HttpStatusCode.SeeOther)
    {
        newRequest.Content = null;
        newRequest.Method = HttpMethod.Get;
    }
    else if (oldRequest.Content != null)
    {
        newRequest.Content = new StreamContent(oldRequest.Content.ReadAsStreamAsync().Result);
    }

    return newRequest;
}
Jürgen Steinblock
  • 30,746
  • 24
  • 119
  • 189
  • Oh, thanks. I didn't realize my original solution didn't have the host check. I should make sure our Graph middleware includes your optimizations https://github.com/microsoftgraph/msgraph-sdk-dotnet-core/blob/dev/src/Microsoft.Graph.Core/Requests/Middleware/RedirectHandler.cs – Darrel Miller Feb 18 '20 at 15:19
  • Thanks for pointing me to the code. That solved another problem I had (the `CloneAsync` extension method in particular): `// HttpClient doesn't rewind streams and we have to explicitly do so.`. Also I looks like the code already has the propper host check. – Jürgen Steinblock Feb 20 '20 at 07:45