Page 1 of 1

How to apply credentials in PTV C#.JSON clients

Posted: Tue Sep 20, 2022 2:45 pm
by Bernd Welter
Cheerio,

as some of you might have noticed: we now also provide C# Client classes which are using JSON as message protocol for the exchange with PTV xServer2. Though we added a generic description into the Developers Guide I was missing the specific sample for the application of credentials. I already requested the chapter from DEV.

In the meantime check this piece of code to gather how to apply the credentials. The variable xtok is of course needed to be assigned first.

Code: Select all

IXServer xServerClient = new XServer(new Uri("https://xserver2-test.cloud.ptvgroup.com"), new HttpClientHandler { 
   Credentials = new System.Net.NetworkCredential { 
       UserName = "xtok",
       Password = xtok
   }
});;
Best regards,
Bernd

Re: How to apply credentials in PTV C#.JSON clients

Posted: Wed Sep 21, 2022 9:08 am
by Bernd Welter
it would have been too easy... here's some annoying info from Ralf - who commented on my recommended piece of code:
yes I found that, too, but there's is still a disadvantage: All requests are sent twice, one time without the basic auth header (responded by http 401), a second time with the basic auth header (responded by http 200). Even if I set PreAuthenticate = true for the HttpClientHandler some requests are still sent twice.

Proposed alternative solution which always sends the basic auth header is:

Code: Select all

var encoded = Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes("xtok:" + xtok));

XServer xServerClient = new XServer(new Uri("https://xserver2-test.cloud.ptvgroup.com"));

xServerClient.HttpClient.DefaultRequestHeaders.Authorization 
= new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", encoded);