1

Good evening all.

Am a bit new to C#, but am having a play with the github api, and I'm trying to get my head around some basic authentication. I've written a console app who's sole aim is to link up the github site and pull down my profile from there. When I do a call that doesn't require authentication, then it works fine.

However if I try and authenticate using basic authentication, I get a 401 error, even though I've put in the right user name and password. I've googled, and it looks like my code is correct, but I can't figure out why I'm not authorised.

I've attached the code below, and all the using stuff is present and correct.

class gitHubConnection : ConnectionManager
{
    public override string getRepositories()
    {
        string web_response = null;
        try
        {
            CredentialCache cache = new CredentialCache();
            NetworkCredential nc = new NetworkCredential("githubUsername", "githubPassword");
            cache.Add(new Uri("https://api.github.com/user"), "Basic", nc);
            WebRequest request = (HttpWebRequest)WebRequest.Create("https://api.github.com/user");

            request.Credentials = nc;
            WebResponse response = request.GetResponse();

            web_response = response.ToString();
        }
        catch (UriFormatException e)
        {
            Console.WriteLine("rats!!!!" + e.StackTrace);
        }
        catch (IOException ioe)
        {
            Console.WriteLine("something went pop " + ioe.StackTrace);
        }
        return web_response;
    }
}

Many thanks for your time to look at this. I'm sure I've forgotten something but I just don't know what.

Welshboy

  • 1
    In case you're interested your question got me curious, so I've tried some research why your code didn't work. That leaded me to ask the following question: http://stackoverflow.com/q/19764113/849741 – Jos Vinke Nov 04 '13 at 08:44

1 Answers1

1

It works if you add the authentitication header like this:

WebRequest request = (HttpWebRequest)WebRequest.Create("https://api.github.com/user");
request.Headers.Add(HttpRequestHeader.Authorization, "Basic " + Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes("user:password")));

WebResponse response = request.GetResponse();
Jos Vinke
  • 2,704
  • 3
  • 26
  • 45
  • Thanks Jos, that's excellent, thank you very much indeed :-) It worked perfectly. –  Nov 03 '13 at 23:51