0

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.

H.G. Sandhagen
  • 772
  • 6
  • 13
  • WebRequest/WebResponse and related classes are deprecated. You should be using System.Net.HttpClient – Camilo Terevinto Aug 15 '21 at 13:04
  • I found [HttpClientHandler UseDefaultCredentials in .NET Core](https://stackoverflow.com/q/64443362/8967612) and [HttpClient, UseDefaultCredentials, Windows Authentication, .NET Core 2.0+ console application receives 401 Unauthorized](https://stackoverflow.com/q/46306508/8967612) but I can't test right now. See if any of the suggestions work for you. – 41686d6564 stands w. Palestine Aug 15 '21 at 14:11
  • Thank you. [HttpClientHandler UseDefaultCredentials in .NET Core](https://stackoverflow.com/questions/64443362/httpclienthandler-usedefaultcredentials-in-net-core) helped. – H.G. Sandhagen Aug 15 '21 at 16:04

1 Answers1

1

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 works in .NET Core and in .NET Framework I constantly received 401 Unathorized response.