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?