2

I'm trying to make a connection to a Github API endpoint using basic authentication. And no matter what I do, I'm getting 403 status as an answer. Has anyone ever experienced this ?

    HttpClient client = new HttpClient();
    client.DefaultRequestHeaders.Clear();
    var basicAuthentication = Encoding.ASCII.GetBytes($"{_username}:{_password}");
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(basicAuthentication));

    var result = await client.GetAsync("https://api.github.com/user");
    var content = await result.Content.ReadAsStringAsync();
    Console.WriteLine(content);

Could someone help, please?

  • Try with postman first. Find out if it's a C# issue or a request issue. – Wyck May 20 '20 at 20:20
  • Hi, I do this request in postman an curl and i have the response. – Rodrigo Galante May 20 '20 at 20:29
  • Turn on tracing with [these instructions](https://stackoverflow.com/a/25683524/1563833) and see if your request matches the one you sent in postman. If not, find the differences. – Wyck May 20 '20 at 20:41
  • I don't think you need to `ToBase64String` the header value. Is that it? – Wyck May 20 '20 at 20:54
  • Thanks for your help @Wyck I found the solution: I need increase this line: client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("XXX", "1.0")); after read github documentation api. Thanks for your help! – Rodrigo Galante May 20 '20 at 21:17

1 Answers1

1

I experienced the same issue. I was calling this URL (https://api.github.com/repos/thomasgalliker/PiWeatherStation/releases) in the browser and it worked well. When I use an HttpClient with a GET request, it fails with 403 Forbidden.

var response = await this.httpClient.GetStringAsync("https://api.github.com/repos/thomasgalliker/PiWeatherStation/releases");

Adding this line of code before issuing the GetStringAsync request resolved the issue (no idea why):

this.httpClient.DefaultRequestHeaders.UserAgent.TryParseAdd("request");
thomasgalliker
  • 1,279
  • 13
  • 19