为JGit指定SSH密钥

nst*_*ess 9 java git ssh jsch jgit

我想知道如何使用jgit连接到github使用指定的ssh密钥文件(即不在〜/ .ssh /中).

不幸的是,我不确定如何JschConfigSessionFactory正确使用.我尝试创建一个类似于本文中的设置:使用JGit键来安全地访问Git存储库

我使用git调用git.push().setRemote(remotePath).call();但是,我收到此错误(日志中省略了特定的存储库):

org.eclipse.jgit.api.errors.TransportException: https://github.com/user/repo: not authorized
    at org.eclipse.jgit.api.PushCommand.call(PushCommand.java:160)
    at gitio.GitInterface.pushToRemote(GitInterface.java:145)
    at engine.GitInterfaceTester.main(GitInterfaceTester.java:25)
Caused by: org.eclipse.jgit.errors.TransportException: https://github.com/user/repo: not authorized
    at org.eclipse.jgit.transport.TransportHttp.connect(TransportHttp.java:479)
    at org.eclipse.jgit.transport.TransportHttp.openPush(TransportHttp.java:396)
    at org.eclipse.jgit.transport.PushProcess.execute(PushProcess.java:154)
    at org.eclipse.jgit.transport.Transport.push(Transport.java:1173)
    at org.eclipse.jgit.api.PushCommand.call(PushCommand.java:156)
    ... 2 more
Run Code Online (Sandbox Code Playgroud)

我注意到JschConfigSessionFactory实际上没有实际调用自定义覆盖方法.这几乎肯定是问题的原因......但不知道为什么不调用它们; 我将自定义传递JschConfigSessionFactorySshSessionFactory使用SshSessionFactory.setInstance(sessionFactory);

有人知道我做错了什么吗?

Rüd*_*ann 7

GitHub将密码认证用于https URL,将公钥认证用于SSH URL(请参阅https://gist.github.com/grawity/4392747)。

SshSessionFactory只征询SSH的URL像git@github.com:用户/ repo.git。要验证https URL,可以使用CredentialsProvider。可以建立连接的命令的基类是,TransportCommand并具有setCredentialsProvider()方法。如果装备PushCommandCredentialsProvider该设备的用户名和密码,你应该能够成功建立连接。

有关使用JGit进行身份验证的更多详细信息,您可能需要阅读以下文章:http : //www.codeaffine.com/2014/12/09/jgit-authentication/

  • 啊,我明白了;我使用了错误的 URL 样式。git@github.com:user/repo.git 有效。谢谢你! (2认同)