6

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).

steakoverflow
  • 1,206
  • 2
  • 15
  • 24

2 Answers2

2

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.

Ian H.
  • 3,840
  • 4
  • 30
  • 60
Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
  • Same thing happens, I get 403 forbidden. – steakoverflow Aug 31 '15 at 05:18
  • I'm copy pasting between Postman and my app, and the base64 representation of username:password in Basic header is the same. – steakoverflow Aug 31 '15 at 10:18
  • 1
    It seems the api url, upon successful auth, immediately 302 redirects to another url in the same subdir, but basic auth header doesn't move along with the redirect. There is a post with an example of creating a custom authenticator, but I could not get it to work in my case. http://stackoverflow.com/questions/28195208/restsharp-authenticator-follow-302-redirect I was wondering if there's a way to tell if there was a successful auth on first api url, then capture the redirected url and try the same auth on that. Not clean but could work with that. – steakoverflow Aug 31 '15 at 18:54
  • 1
    @vani Have you tried using `HttpClient` instead? I'd suggest using it with `HttpClientHandler`. – Yuval Itzchakov Aug 31 '15 at 19:09
  • 1
    Yes, I think I'll go with that route (httpclient), I'll take a httpstatus.found (302) as a successful login with basic authentication on first url, anything else returned will be considered as rejection. How can I mark your comment as correct answer here at StackO? – steakoverflow Sep 01 '15 at 05:32
  • 1
    @vani I've edited my answer to include what I've said in the comments. If you wish, you can mark that as the answer. – Yuval Itzchakov Sep 01 '15 at 08:12
0

[Solution] Use the below line for the header

Headers.Add("User-Agent: Other");

Thilina Chamika
  • 206
  • 3
  • 4