Forum Xamarin.iOS

didReceivedAuthenitcationChallange implementation in HttpClient PCL project.

Below native application code is working fine for me with objectiveC for Server Authentication Challenge.

NSString *authStr = [NSString stringWithFormat:@%@:%@",username,password];
NSString *authValue = [NSString stringWithFormat:@Basic %@",[self base64Encode:authStr]];

NSURL *url= [NSURL URLWithString:requestURL];

NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60.0];

[theRequest setValue:authValue forHTTPHeaderField:@Authorization];

-(void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust])
id sender = [challenge sender];
SecTrustRef trust = [[challenge protectionSpace] serverTrust];

    NSURLCredential *credential = [[NSURLCredential alloc] initWithTrust:trust];
    [sender useCredential:credential forAuthenticationChallenge:challenge];

I am creating same application with Xamarin.iOS, I have written below code with PCL and trying to fetch api using HttpClient. But how to provide certificate credentials and trust it, i have tried various method like providing it with
HttpClientHandler _handler = new HttpClientHandler() { Credentials = new System.Net.NetworkCredential(“username”, “Password”) };

but nothing is working at my end. Could you please let me know how to write code for ‘didReceiveAuthenticationChallenge’ method in xamarin.iOS PCL using HttpClient to trust certificate.

            string responseJsonString = null;
                using (var httpClient = new HttpClient())
                    var authData = string.Format("{ 0}:{ 1}", userName, passWord);
                    var authHeaderValue = Convert.ToBase64String(Encoding.UTF8.GetBytes(authData));
                    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authHeaderValue);

                        Task<HttpResponseMessage> getResponse = httpClient.GetAsync(“https://someapiurl”);
                        HttpResponseMessage response = await getResponse;
                        if (response.IsSuccessStatusCode)
                          responseJsonString = await response.Content.ReadAsStringAsync();
                           summaryDetails = JsonConvert.DeserializeObject<ClassObject>(responseJsonString);
                    catch (Exception)

Sign In or Register to comment.