asp.netasp.net-coresession-cookiescookiecontainerasp.net-session

Reverse proxy in .NET Core Middleware “set-cookie” response does not set in browser and not showing in HttpResponseMessage


Here I am making a reverse proxy server to bypass an ASP.NET web application (following this tutorial). I am trying to read the session ID cookie from HttpResponseMessage. I used a cookie container as well but am unable to find it. Implemented in ASP.NET core invoke method, session is working properly but unable to catch session ID in request or response.

            public async Task Invoke(HttpContext context, IBrowserDetector detector)
            {
                //context.Session.SetString(SessionKeyName, "The Doctor");
                var browser = detector.Browser;
                var targetUri = BuildTargetUri(context.Request);
                if (context.Request.Method != HttpMethod.Get.Method)
                {
                    var remoteIp = context.Connection.RemoteIpAddress;
                    //var gg= context.Request.Headers.ContainsKey.;
                    var clienttdatetime = context.Request.Headers["Date"].ToString();
                    //_logger.LogDebug("Request from Remote IP address: {RemoteIp}", remoteIp);
                    var badIp = true;
                    var bytes = remoteIp.GetAddressBytes();
                    //var testIp = IPAddress.Parse(address);
                    //if (testIp.GetAddressBytes().SequenceEqual(bytes))
                    //{
                    //    badIp = false;
                    //    break;
                    //}
                    if (remoteIp.IsIPv4MappedToIPv6)
                    {
                        remoteIp = remoteIp.MapToIPv4();
                    }
                    IPAddress remoteIpAddress = context.Request.HttpContext.Connection.RemoteIpAddress;
                    string result = "";
                    if (remoteIpAddress != null)
                    {
                        // If we got an IPV6 address, then we need to ask the network for the IPV4 address 
                        // This usually only happens when the browser is on the same machine as the server.
                        if (remoteIpAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6)
                        {
                            remoteIpAddress = System.Net.Dns.GetHostEntry(remoteIpAddress).AddressList
                    .First(x => x.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork);
                        }
                        result = remoteIpAddress.ToString();
                    }
                    if (badIp)
                    {
                        //_logger.LogWarning(
                        //    "Forbidden Request from Remote IP address: {RemoteIp}", remoteIp);
                        //context.Response.StatusCode = StatusCodes.Status403Forbidden;
                        //return;
                    }
                }
    
    
                if (targetUri != null)
                {
                    CookieContainer cookies = new CookieContainer();
                    HttpClientHandler handler = new HttpClientHandler();
                    handler.CookieContainer = cookies;
                    var targetRequestMessage = CreateTargetMessage(context, targetUri);
    
                    using (var responseMessage = await _httpClient.SendAsync(targetRequestMessage, HttpCompletionOption.ResponseHeadersRead, context.RequestAborted))
                    {
                        IEnumerable<Cookie> responseCookies = cookies.GetCookies(targetUri).Cast<Cookie>();
                        foreach (Cookie cookie_ in responseCookies)
                           Console.WriteLine(cookie_.Name + ": " + cookie_.Value);
                        // ExtractCookiesFromResponse(responseMessage);
                        context.Response.StatusCode = (int)responseMessage.StatusCode;
                        CopyFromTargetResponseHeaders(context, responseMessage);
                        await responseMessage.Content.CopyToAsync(context.Response.Body);
                        //if(responseMessage.RequestMessage.RequestUri.ToString()== "http://localhost:51125/Menu.aspx")
                        //{
                        //Uri uri = new Uri("http://localhost:5000/login.aspx");
                        //Build the request
                       //Uri site = targetUri;
                       // HttpWebRequest request = (HttpWebRequest)WebRequest.Create(site);
                       // CookieContainer cookiesq = new CookieContainer();
                       // request.CookieContainer = cookiesq;
    
                       // //Print out the number of cookies before the response (of course it will be blank)
                       // Console.WriteLine(cookiesq.GetCookieHeader(site),"1");
    
                       // //Get the response and print out the cookies again
                       // using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                       // {
                       //     Console.WriteLine(cookiesq.GetCookieHeader(site), "2");
                       // }
    
                       // Console.ReadKey();
    
    
                        //}
                        var cookie = context.Request.Cookies["ASP.NET_SessionId"];
                    }
                    return;
                }
                await _nextMiddleware(context);
            }

------------------------------------------------------------------------------------
      public static IDictionary<string, string> ExtractCookiesFromResponse(HttpResponseMessage response)
        {
            IDictionary<string, string> result = new Dictionary<string, string>();
            IEnumerable<string> values;
            if (response.Headers.TryGetValues("Set-Cookie", out values))
            {
                SetCookieHeaderValue.ParseList(values.ToList()).ToList().ForEach(cookie =>
                {
                    result.Add(cookie.Name.ToString(), cookie.Value.ToString());
                });
            }
            return result;
        }

Solution

  •                CookieContainer cookies = new CookieContainer();
                   HttpClientHandler handler = new HttpClientHandler();
                   handler.CookieContainer = cookies;
                   _httpClient = new HttpClient(handler);
                    var targetRequestMessage = CreateTargetMessage(context, targetUri);
    
                    using (var responseMessage = await _httpClient.SendAsync(targetRequestMessage, HttpCompletionOption.ResponseHeadersRead, context.RequestAborted))
                    {
                        //var responseCookies = cookies.GetCookies(targetUri).Cast<Cookie>();
                        IEnumerable<Cookie> responseCookies = cookies.GetCookies(targetUri).Cast<Cookie>();
                        foreach (Cookie cookie in responseCookies)
                        {
                            if(cookie.Name=="ASP.NET_SessionId")
                            {
                                Console.WriteLine(cookie.Name + ": " + cookie.Value);
                                context.Response.Headers.Add("Set-Cookie", cookie.Name+"="+cookie.Value);
                            }
                            
                        }