Skip to content

[Cookie] HttpClient does not handle cookies with a non-matching path #25226

Closed

Description

@Tratcher

From @dgweldon on February 15, 2018 22:28

I have an interesting problem related to OpenID Connect Authentication in ASP .NET Core. We have an Identity Server 3 OIDC implementation that uses a client certificate authentication provider. When migrating to ASP .NET Core, we had no problem integrating with our existing OIDC server. At least when launched from a browser (Edge, Chrome).

However, we have a small ClickOnce application (using the full .NET framework) that also authenticates and makes calls through the ASP. It does this by using a HttpClient with a certificate selected by the user. This ClickOnce application fails during authentication. The code is pretty simple.

using (WebRequestHandler certHandler = new WebRequestHandler
{
   CookieContainer = new CookieContainer(),
   ClientCertificateOptions = ClientCertificateOption.Manual,
   UseDefaultCredentials = true,
   AllowAutoRedirect = true
})
{
   // Init
   certHandler.ClientCertificates.Add(certificate);

   using (HttpClient client = new HttpClient(certHandler) { BaseAddress = baseUri })
   {
      HttpResponseMessage response = a_client.GetAsync(ssoLoginUri).GetAwaiter().GetResult();
      response.EnsureSuccessStatusCode();

      // Process self submitting form responses as long as needed
      do
      {
         response = ProcessFormAutoSubmit(a_client, response);
      }
      while (response != null);
   }
}

After moving to ASP .NET Core, this code no longer works. The issue is that when MVC redirects to Identity Server, it includes 2 cookies (.ASPNetCore.Correlation.OpenIdConnect and .AspNetCore.OpenIdConnect.Nonce). Those cookies never make it into my CookieContainer (other cookies from Identity Server are handled fine). When the signin-oidc callback is made, MVC fails with the error: "Correlation failed: .AspNetCore.Correlation.OpenIdConnect.9N18bzJ1hcpG5YjRMw_QgUJ_PnapfVx2lBmdvb8Q_zA' cookie not found.". Makes sense. But why is the cookie not added?

After playing around, I was able to get around this by handling each redirect and manually adding any cookies that had a path (both of which the 2 missing cookies had). The code now looks like this:

...
HttpResponseMessage response = a_client.GetAsync(ssoLoginUri).GetAwaiter().GetResult();
Regex cookiePathRegex = new Regex(@"path=([^;]*);?");

do
{
   // Ideally we would just use automatic redirects in the HttpClient, but we need to intercept cookies for special processing
   if (response.StatusCode == HttpStatusCode.Redirect)
   {
      Uri requestUri = response.Headers.Location;
      if (!requestUri.IsAbsoluteUri)
      {
         requestUri = UriUtil.Combine(response.RequestMessage.RequestUri.GetLeftPart(UriPartial.Authority), response.Headers.Location.OriginalString);
      }

      response = a_client.GetAsync(requestUri).GetAwaiter().GetResult();

      IEnumerable<string> responseCookies = null;
      if (response.Headers.TryGetValues("set-cookie", out responseCookies))
      {
         // Cookies that have a path aren't currently supported with HttpClient
         // Such cookies are used with the new ASP .NET Core OpenId Connect implementation
         // Just manually add these cookies
         foreach (string sCookie in responseCookies)
         {
            Match pathMatch = cookiePathRegex.Match(sCookie);
            if (pathMatch.Success)
            {
               a_webRequestHandler.CookieContainer.SetCookies(
                  UriUtil.Combine(requestUri.GetLeftPart(UriPartial.Authority), pathMatch.Groups[1].Value),
                  cookiePathRegex.Replace(sCookie, String.Empty));
            }
         }
      }
   }
   else
   {
      response.EnsureSuccessStatusCode();
      response = ProcessFormAutoSubmit(a_client, response);
   }
}
while (response != null);

This works, but seems like a hack. Any idea why these cookies aren't handled by HttpClient?

I realize this may not be directly be an ASP .NET Core issue, but wanted to start here since it seems to be related to cookies from ASP .NET Core.

Thanks,

--David

Copied from original issue: dotnet/aspnetcore#2880

Activity

  1. Tratcher commented on Feb 27, 2018

    @Tratcher
    MemberAuthor

    From @Eilon on February 16, 2018 5:30

    Hi, a few things I'm wondering:

    • Is there any difference on the wire (using Fiddler or a similar sniffer) about what the cookies look like?
    • Which version of ASP.NET Core is this?
  2. Tratcher commented on Feb 27, 2018

    @Tratcher
    MemberAuthor

    From @dgweldon on February 16, 2018 13:12

    I apologize for leaving out those details. That's how I actually found this issue. In Fiddler, I can see that the 2 cookies mentioned are not passed to signin-oidc. Also, we are using ASP.NET Core 2.0.5. And on the ClickOnce application we are using 5.2.4 of Microsoft.AspNet.WebApi.Client for HttpClient.

  3. Tratcher commented on Feb 27, 2018

    @Tratcher
    MemberAuthor

    From @Eilon on February 18, 2018 23:50

    @dgweldon thanks for the info. Is there any difference in the cookies sent by the server to the client, comparing ASP.NET's cookies to ASP.NET Core?

    Ultimately I don't think HttpClient particularly cares who sent it the cookies, so presumably there's a difference in what it got from the initial request, and thus isn't sending the cookie to the subsequent request.

  4. Tratcher commented on Feb 27, 2018

    @Tratcher
    MemberAuthor

    From @dgweldon on February 20, 2018 16:34

    Just to be clear, I'm talking about 2 clients (web browser and ClickOnce app using HttpContext) going through the same ASP .NET Core server. There is no ASP .NET server in play in this problem scenario.

    But the cookies sent to each client look very similar.

    Here are the ones sent to the web browser:

    Set-Cookie: .AspNetCore.OpenIdConnect.Nonce.CfDJ8DuLivGqBmBIhlg8v1hx8hkKoV4aMEN4JZQIZh8XtW6QOylzcoWYSl6-9oTiyqNz3ArlloCOVv9GrsNmqRyHzTIhA5Nbupb2NMefUOnZrwHJWi2DJxhKptMSn0KfBG-mk73roMSV6D27NdDmKL6qDVc4IjrBMZLLI7avVrgUVKipSN_T-AIof4YklPwbTRiArvDX39OrCaJNYTOrxXYLS2LaZEBoLHYcQJyTFfxukg8BVjteWW2CjVl56of9h7AUfqhRLS5Z9X9U19r-pdHsdAw=N; expires=Tue, 20 Feb 2018 16:04:02 GMT; path=/signin-oidc; httponly
    Set-Cookie: .AspNetCore.Correlation.OpenIdConnect.njpwnuOhyXgnuPTpHRLeoqB5VQizR9sBstbpHH1siGI=N; expires=Tue, 20 Feb 2018 16:04:02 GMT; path=/signin-oidc; httponly
    

    And then the ones sent to the ClickOnce application:

    Set-Cookie: .AspNetCore.OpenIdConnect.Nonce.CfDJ8DuLivGqBmBIhlg8v1hx8hlbU81DRN2Mv3WVlAN1Jtppk6oTfVekJX-3NHQCZYIrKrRMs-jN6QjX0CEyzuU-ITgZbV1v-QdaXNsiFPtISGJRQz46UolBB37sEW5iE9ZYULv6A8i__LzABeEqWgS_0GBzLmPnmQf6VbdbvYSgj4KzCOxxOCDgNsc2FzvPCvXPYfqSQxqP9jR4ZFXXUirH71aXviqV2N5CmhJ6Nrnc-HkG_qKq0xfpjZAAKvqTF30uky19YJ1lQb14QaFuo0D36NI=N; expires=Tue, 20 Feb 2018 16:37:03 GMT; path=/signin-oidc; httponly
    Set-Cookie: .AspNetCore.Correlation.OpenIdConnect.NSHyU3cdAgXTmx62gb34ZoojeFBintc8gKxp__DLDtc=N; expires=Tue, 20 Feb 2018 16:37:03 GMT; path=/signin-oidc; httponly
    
  5. Tratcher commented on Feb 27, 2018

    @Tratcher
    MemberAuthor

    From @danroth27 on February 20, 2018 17:45

    @Tratcher

  6. Tratcher commented on Feb 27, 2018

    @Tratcher
    MemberAuthor

    This is a client bug. https://github.com/dotnet/corefx/blob/ac58f7e99e7745ba9ab85fe7b47c348260b6ef26/src/System.Net.Http/src/uap/System/Net/cookie.cs#L574
    The client requires the cookie path to be less specific than the current request (e.g. request is /foo/bar and cookie can be /foo) but we are setting a path that's more specific (e.g. request is / and we set /signin-oidc). There's no provision for this behavior in the spec (https://tools.ietf.org/html/rfc6265.html#section-5.2.4) and browsers handle it fine.

    I did find one difference between net461 and netcoreapp2. For net461 if you have one cookie rejected due to the path then you still get the other cookie. With netcoreapp2 if you have any cookies rejected then they are all rejected.

    I'll redirect this to the corefx team.

    Repro code:

    using System;
    using System.IO;
    using System.Net;
    using System.Net.Http;
    
    namespace ConsoleApp5
    {
        class Program
        {
            static void Main(string[] args)
            {
                Console.WriteLine("Hello World!");
    
                var listener = new HttpListener();
                listener.Prefixes.Add("http://localhost:12345/");
                listener.Start();
                var requestTask = listener.GetContextAsync();
    
                var handler = new HttpClientHandler();
                handler.CookieContainer = new CookieContainer();
                var container = handler.CookieContainer;
                handler.UseCookies = true;
                var client = new HttpClient(handler);
                var responseTask = client.GetAsync("http://localhost.fiddler:12345/"); // Breaks
                // var responseTask = client.GetAsync("http://localhost.fiddler:12345/path"); // Works
    
                var request = requestTask.Result;
                request.Response.SetCookie(new Cookie("name0", "value0"));
                request.Response.SetCookie(new Cookie("name1", "value1", "/path"));
                request.Response.Close();
    
                var response = responseTask.Result;
                Console.WriteLine(response);
    
                Console.WriteLine("Cookies: " + container.Count);
    
                requestTask = listener.GetContextAsync();
                
                responseTask = client.GetAsync("http://localhost.fiddler:12345/path");
    
                request = requestTask.Result;
                using (var writer = new StreamWriter(request.Response.OutputStream))
                {
                    foreach (var cookie in request.Request.Cookies)
                    {
                        var c = (Cookie)cookie;
                        writer.Write($"{c.Name}={c.Value},");
                    }
                }
                request.Response.Close(); // 200
    
                response = responseTask.Result;
                Console.WriteLine(response);
                Console.WriteLine(response.Content.ReadAsStringAsync().Result);
            }
        }
    }
    <Project Sdk="Microsoft.NET.Sdk">
    
      <PropertyGroup>
        <OutputType>Exe</OutputType>
        <TargetFrameworks>netcoreapp2.1;net461</TargetFrameworks>
      </PropertyGroup>
    
      <ItemGroup Condition=" '$(TargetFramework)' == 'net461' ">
        <Reference Include="System.Net.Http" />
      </ItemGroup>
    </Project>
  7. Tratcher commented on Feb 27, 2018

    @Tratcher
    MemberAuthor

    On a different note, the OIDC protocol is not designed for programmatic usage like this. You'd be better off using a bearer token model.

  8. davidsh commented on Feb 27, 2018

    @davidsh
    Contributor

    The client requires the cookie path to be less specific than the current request (e.g. request is /foo/bar and cookie can be /foo) but we are setting a path that's more specific (e.g. request is / and we set /signin-oidc). There's no provision for this behavior in the spec (https://tools.ietf.org/html/rfc6265.html#section-5.2.4) and browsers handle it fine.

    Currently .NET Core and .NET Framework do NOT implement RFC 6265.

    Related: #19746

  9. caesar-chen commented on Apr 26, 2018

    @caesar-chen
    Contributor

    I think it's duplicated of #22372.

  10. changed the title [-]HttpClient does not handle cookies with a non-matching path[/-] [+][Cookie] HttpClient does not handle cookies with a non-matching path[/+] on May 8, 2018
  11. caesar-chen commented on May 11, 2018

    @caesar-chen
    Contributor

    Tracked in #26141.

  12. added a commit that references this issue on Nov 6, 2018
  13. added a commit that references this issue on Feb 11, 2019
  14. transferred this issue fromdotnet/corefxon Jan 31, 2020
  15. added this to the 3.0 milestone on Jan 31, 2020
  16. ghost locked as resolved and limited conversation to collaborators on Dec 18, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions