10

I have the following set up:

JS client -> Web Api -> Web Api

I need to send the auth cookie all the way down. My problem is sending it from one web api to another. Because of integration with an older system, that uses FormsAuthentication, I have to pass on the auth cookie.

For performance reasons I share a list of HttpClients (one for each web api) in the following dictionary:

private static ConcurrentDictionary<ApiIdentifier, HttpClient> _clients = new ConcurrentDictionary<ApiIdentifier, HttpClient>();

So given an identifier I can grab the corresponding HttpClient.

The following works, but I'm pretty sure this is bad code:

HttpClient client = _clients[identifier];
var callerRequest = HttpContext.Current.Items["MS_HttpRequestMessage"] as HttpRequestMessage;
string authCookieValue = GetAuthCookieValue(callerRequest);

if (authCookieValue != null)
{
    client.DefaultRequestHeaders.Remove("Cookie");
    client.DefaultRequestHeaders.Add("Cookie", ".ASPXAUTH=" + authCookieValue);
}

HttpResponseMessage response = await client.PutAsJsonAsync(methodName, dataToSend);

// Handle response...

Whats wrong about this is that 1) it seems wrong to manipulate DefaultRequestHeaders in a request and 2) potentially two simultanious requests may mess up the cookies, as the HttpClient is shared.

I've been searching for a while without finding a solution, as most having a matching problem instantiates the HttpClient for every request, hence being able to set the required headers, which I'm trying to avoid.

At one point I had get requests working using a HttpResponseMessage. Perhaps that can be of inspiration to a solution.

So my question is: is there a way to set cookies for a single request using a HttpClient, that will be safe from other clients using the same instance?

Casper
  • 179
  • 1
  • 1
  • 11

1 Answers1

21

Instead of calling PutAsJsonAsync() you can use HttpRequestMessage and SendAsync():

Uri requestUri = ...;
HttpMethod method = HttpMethod.Get /*Put, Post, Delete, etc.*/;
var request = new HttpRequestMessage(method, requestUri);
request.Headers.TryAddWithoutValidation("Cookie", ".ASPXAUTH=" + authCookieValue);
request.Content = new StringContent(jsonDataToSend, Encoding.UTF8, "application/json");
var response = await client.SendAsync(request);

UPDATE: To make sure that your HTTP client does not store any cookies from a response you need to do this:

var httpClient = new HttpClient(new HttpClientHandler() { UseCookies = false; });

Otherwise you might get unexpected behavior by using one client and sharing other cookies.

Serge Semenov
  • 9,232
  • 3
  • 23
  • 24
  • Thank you very much! I have been really close it seems, but you made it over the finishing line. One question: is it possible to have GET request use the stringcontent as well? If my `jsonDataToSend` is a complex object, it doesn't pass it along, but if I convert it to a querystring myself and pass it as the `method` it works. Would be nice to have a generic method :) – Casper Mar 01 '16 at 08:44
  • np :) Usually GET does not contain body, but it's not prohibited by the spec. You can use `new ObjectContent(value, new JsonMediaTypeFormatter(), "application/json")` instead of `StringContent` – Serge Semenov Mar 01 '16 at 17:01