gitgithubgithub-apilibgit2sharpoctokit.net

Authenticate with Octokit.net and push with LibGit2Sharp to GitHub repository


I use the LibGit2Sharp library to clone/push the authenticated user's GitHub repository, but LibGit2Sharp doesn't accept an access token to authorize the user.

 LibGit2Sharp.Credentials credentials = new UsernamePasswordCredentials()
        {
            Username = "username",
            Password = "password"
        };

So I have an access token comes from Octokit.NET and I want to use this token to push to the authorized user repository with LibGit2Sharp.

Are there any way to do this trick? If I know well, Octokit.NET couldn't perform push requests at this time.

UPDATE

As Carlos Martín Nieto and Ivan Zuzak suggest, I modified the code:

 LibGit2Sharp.Credentials credentials = new UsernamePasswordCredentials()
    {
        Username = "the-access-token",
        Password = string.Empty
    };

And after I use my push logic:

 var pushOptions = new PushOptions() { Credentials = credentials};

 Remote remote = repo.Network.Remotes["origin"];

 LibGit2Sharp.Signature author = new LibGit2Sharp.Signature("name", "email", DateTime.Now);

 repo.Network.Push(remote,"HEAD",@"refs/heads/master",pushOptions, author, null);

This logic works fine with the hard-coded username and password, but now I have got an exception at the last line, says " LibGit2Sharp.LibGit2SharpException: Request failed with status code: 403"

I missed something from the implementation or I made a mistake at Push() method?

Thank you very much!


Solution

  • libgit2sharp supports using authentication tokens with GitHub the same way git does. You pass in the token as the username and leave the password blank.

    git does not have any support for authentication tokens over simply using HTTP Basic Auth, so GitHub have implemented this by accepting the token as the username. Simply use it the same way you'd use it on the command line.