Search code examples
c#httpclientrestsharpwp-api

Restsharp returns 403 while Postman returns 200


This is the (modified) snippet that Postman gives for successful call to my page.

var client = new RestClient("http://sub.example.com/wp-json/wp/v2/users/me");
var request = new RestRequest(Method.GET);
request.AddHeader("authorization", "Basic anVyYTp3MmZacmo2eGtBOHJsRWrt");
IRestResponse response = client.Execute(request);

But when placed in my c# app it returns 403 forbidden, while Postman makes it and recieves 200. The same thing happens when I use httpclient in my app (403).


Solution

  • Use RestClient.Authenticator instead:

    var client = new RestClient("http://sub.example.com/wp-json/wp/v2/users/me")
    { 
          Authenticator = new HttpBasicAuthenticator("User", "Pass")
    };
    
    var request = new RestRequest(Method.GET);
    IRestResponse response = client.Execute(request);
    

    Edit:

    Since the issue (as mentioned in the comments) is the fact that RestSharp doesn't flow the authentication through redirects, I'd suggest going with a combination of HttpClient with a HttpClientHandler where you set the authentication to flow.