NGit making a connection with a private key file

荒凉一梦 提交于 2019-11-30 21:16:21

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();
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!