solvingJ
solvingJ

Reputation: 1359

C# System.Net.HttpClient intermittent 401 Unauthorized with Github API

I'm using System.Net.Http HttpClient to call Github's rest API.

About 5 out of every 10 requests I make with the HTTP client generated below respond with "401 Unauthorized". I put the same URL and headers in postman and never get any "401 Unauthorized" responses. Clearly, my problem is on the client side.

A reasonable search returned a lot of different advice. The most common was to use an HttpHandler, or webrequest, but it's still not clear why some requests fail. My best guesses were that Github occasionally redirects and the client doesn't handle it well. I saw some references about caching credentials, but those examples all showed "NetworkCredential" object, and but for OAuth we just put the bearer token in the header as shown below, so I'm not sure if that applies to my case.

Can anyone explain the cause of the issue?

        public static HttpClient GetClient(string bearerToken)
    {
        HttpClient client = new HttpClient();
        client.BaseAddress = _githubApiUri;
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(_mediaTypeWithQualityHeaderValue));
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", bearerToken);
        client.DefaultRequestHeaders.Add("User-Agent", "System.Net.Http Agent");
        return client;
    }

Upvotes: 0

Views: 902

Answers (1)

solvingJ
solvingJ

Reputation: 1359

It turned out that my clock was 15 seconds fast, making the tokens I was generating invalid because they were "from the future" from Githubs perspective. So, if I paused with a breakpoint, and happened to wait 15 seconds, or more, it would work.

Upvotes: 1

Related Questions