简体   繁体   中英

Different behaviour of HttpWebRequest/HttpClient in .NET Core and .NET Framework

I am writing a console application which uses SSO (Windows Authentication) for login into a third party web API. The code works with .NET Framework 4.6.1, but not with .NET Core 3.1.

During the tests I reduced the problem to the request to get the token from the identity provider and created two application, one with .NET Framework 4.6.1 and one with .NET Core 3.1 with exact the same code in Main:

string uri = "http://<server>/connection/single-sign-on/identity-providers/90c22f9b-0a9d-4474-87f4-b48eccbe3095?singleSignOnCapabilities=saml2Redirect";
try {
   using (HttpClient client = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true })) {
      var response = client.GetAsync(uri).Result;
      Console.WriteLine(response.StatusCode);
      if (response.IsSuccessStatusCode) {
         // Get token from response header
         // This works with .NET 4.6.1 
      }
   }
}
catch {
    // In .NET Core 3.1 I get an exception: The remote server returned an error: (401) Unauthorized.
}

Because of the comment from Camilo Terevinto, I changed the example to HttpClient with the same result.

Btw: Can experience the same behaviour with Windows Powershell and Powershell Core. It seems to be a general different implementation on Framework and Core.

In addition to reponse in comments I found different problem with HttpClient on .NET Core vs .NET Framework. If you have authorization defined in cookies in .NET Framework you have to do it with CookieContainer in HttpHandler:

var cookieContainer = new CookieContainer();
var handler = new HttpClientHandler
{
   CookieContainer = cookieContainer
};

Instead of doing it by HttpRequestMessage header:

var message = new HttpRequestMessage(HttpMethod.Post, <ip>);
message.Headers.Add("Cookie", <cookie>);

The second way only work in .NET Core and in .NET Framework I constantly received 401 Unathorized response.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM