1

The below code worked fine before I changed the URL(Constants.UrlLoginUser) to a subdomain. I'm using "Basic" authentication. When I use the raw URL, it works fine. I'm aware that the HttpClient Authentication header is being cleared when the redirection happens. Is there a way to make it work with redirect URLs? I've tried to use the CredentialCache without any success. I get a "401 Unauthorized" response with the redirect URL.

using (var client = new HttpClient())
{
   client.DefaultRequestHeaders.Add("email", TxtEmail.Text);
   client.DefaultRequestHeaders.Add("password", TxtPassword.Text);
   client.DefaultRequestHeaders.Authorization = HttpClientHelper.NdAuth;
   var result = await client.GetAsync(Constants.UrlLoginUser);
} 

There's a potential solution provided here in this answer but It's kind of a hack.

if (response.StatusCode == HttpStatusCode.Unauthorized)
{
    // Authorization header has been set, but the server reports that it is missing.
    // It was probably stripped out due to a redirect.

    var finalRequestUri = response.RequestMessage.RequestUri; // contains the final location after following the redirect.

    if (finalRequestUri != requestUri) // detect that a redirect actually did occur.
    {
        if (IsHostTrusted(finalRequestUri)) // check that we can trust the host we were redirected to.
        {
           response = client.GetAsync(finalRequestUri).Result; // Reissue the request. The DefaultRequestHeaders configured on the client will be used, so we don't have to set them again.
        }
    }
}

Is there a cleaner way to accomplish this on Xamarin Forms?

Community
  • 1
  • 1
Heshan
  • 913
  • 8
  • 30
  • How is the redirect implemented? It could potentially have an impact on how the HttpClient works. – fredrik Feb 10 '17 at 06:45

0 Answers0