Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NGit making a connection with a private key file

Tags:

git

c#

ngit

I am trying to use NGit to connect to Github (ie using a private key as well as a password).

Can someone walk me through it?

My normal fetch would be:

            var git = Git.CloneRepository()
            .SetDirectory(_properties.OutputPath)
            .SetURI(_properties.SourceUrlPath)
            .SetBranchesToClone(new Collection<string>() { "master" })
            .SetCredentialsProvider(new UsernamePasswordCredentialsProvider("username","password"))
            .SetTimeout(3600)
            .Call();

how would I do this with a private key?

like image 751
Doug Avatar asked Oct 06 '22 17:10

Doug


1 Answers

After a long battle, many many google searches for Jgit examples and much more pain, I have found the solution!

Basically you override and SessionFactory with your own and inject your certificate at connection time:

public class CustomConfigSessionFactory : JschConfigSessionFactory
{
    public string PrivateKey { get; set; }
    public string PublicKey { get; set; }

    protected override void Configure(OpenSshConfig.Host hc, Session session)
    {
        var config = new Properties();
        config["StrictHostKeyChecking"] = "no";
        config["PreferredAuthentications"] = "publickey";
        session.SetConfig(config);

        var jsch = this.GetJSch(hc, FS.DETECTED);
        jsch.AddIdentity("KeyPair", Encoding.UTF8.GetBytes(PrivateKey), Encoding.UTF8.GetBytes(PublicKey), null);
    }
}

And then inject it like so:

var customConfigSessionFactory = new CustomConfigSessionFactory();
customConfigSessionFactory.PrivateKey = properties.PrivateKey;
customConfigSessionFactory.PublicKey = properties.PublicKey;

NGit.Transport.JschConfigSessionFactory.SetInstance(customConfigSessionFactory);

var git = Git.CloneRepository()
          .SetDirectory(properties.OutputPath)
          .SetURI(properties.SourceUrlPath)
          .SetBranchesToClone(new Collection<string>() { "master" })
          .Call();
like image 173
Doug Avatar answered Oct 10 '22 02:10

Doug