RestSharp - Authorization Header not coming across to WCF REST service

Chris Hawkins picture Chris Hawkins · Jul 20, 2013 · Viewed 32k times · Source

I am trying to call a locally hosted WCF REST service over HTTPS with basic auth.

This works and the Authorization header comes thru just fine and all is happy:

ServicePointManager.ServerCertificateValidationCallback = ValidateServerCertficate;
var request = (HttpWebRequest)WebRequest.Create("https://localhost/MyService/MyService.svc/");
request.Method = "GET";
request.ContentType = "application/json";
request.Headers.Add(
  System.Net.HttpRequestHeader.Authorization,
  "Basic " + this.EncodeBasicAuthenticationCredentials("UserA", "123"));

WebResponse webResponse = request.GetResponse();
using (Stream webStream = webResponse.GetResponseStream())
{
    if (webStream != null)
    {
        using (StreamReader responseReader = new StreamReader(webStream))
        {
            string response = responseReader.ReadToEnd();
        }
    }
}

When I try to use RestSharp however, the Authorization header never comes thru on the request:

ServicePointManager.ServerCertificateValidationCallback = ValidateServerCertficate;

var credentials = this.EncodeBasicAuthenticationCredentials("UserA", "123");

var client = new RestSharp.RestClient("https://localhost/MyService/MyService.svc/");   
var restRq = new RestSharp.RestRequest("/");
restRq.Method = Method.GET;
restRq.RootElement = "/";
restRq.AddHeader("Authorization", "Basic " + credentials);
var restRs = client.Execute(restRq);

What am i doing wrong with the RestSharp method?

I know that the AddHeader method works because this:

restRq.AddHeader("Rum", "And Coke");

will come thru, only "Authorization" seems stripped out/missing.

Answer

wal picture wal · Jul 20, 2013

instead of adding the header 'manually' do the following:

var client = new RestSharp.RestClient("https://localhost/MyService/MyService.svc/");
client.Authenticator = new HttpBasicAuthenticator("UserA", "123");