如何跳过SSL在克隆远程存储库时使用JGit进行验证?

时间:2017-12-13 11:26:47

标签: jgit

当我尝试使用JGit api克隆现有的远程git存储库时,我收到以下错误。

异常:org.eclipse.jgit.api.errors.TransportException:http://admin@localhost:7990/scm/cp/myrepo.git  由于SSL问题,无法建立与https://admin@localhost:7990/scm/cp/myrepo.git的安全连接

在我的课程中,我使用以下方法来克隆存储库。

public static void cloneRepoTemp(String cloneRepoUrl, String username, String password)
            throws FileNotFoundException, IOException {

        Git git;
        try {

            git = Git.cloneRepository().setURI(cloneRepoUrl)
                    .setCredentialsProvider(new UsernamePasswordCredentialsProvider(username, password))
                    .setDirectory(new File("C:/temp/testrepo")).setBranch("integration").call();
            git.close();
        } catch (GitAPIException e) {
            System.out.println("Exception:" + e);
    }

我知道我可以使用以下命令来解决这个问题,

git config --global http.sslVerify false

但是,由于我使用的是JGit api,我想通过api本身启用它,而不是在主机上显式设置。另外,我打算让这个库分布在多台机器中,所以不要在用户的机器上进行更改,以使我的代码能够进行更改。

有没有办法在代码中实现这一点,而无需在git配置文件中添加条目。

2 个答案:

答案 0 :(得分:1)

JGit确实具有自己的存储库配置内部表示,这使您(如@eugène-adell所述)可以更改设置。可通过Repository.getConfig()获得。问题在于cloneRepository命令创建了Repository对象并原子地(从您的角度)调用了克隆序列(fecth + checkout),因此您没有时间更改Repository设置。

为解决此问题,我建议一个穷人克隆:init-> configure-> add remote-> pull(https://stackoverflow.com/a/33999922/3837873建议使用init-> configure-> fetch-> checkout,两者均有效)。 (完整的)代码如下所示:

Repositoryrepo = Git.init().setDirectory(this.tempGitDir.toFile()).call();
repo.getRepository()
        .getConfig()
        .setBoolean("http", "https://selfsigned.server.com", "sslVerify", false);
URIish u = createURIish();
repo.remoteAdd()
        .setName("origin")
        .setUri(u)
        .call();
repo.pull()
        .setCredentialsProvider(new UsernamePasswordCredentialsProvider("token", pat))
        .setRemote("origin")
        .setRemoteBranchName("master")
        .call(); 

我们首先在其中初始化存储库,然后更改其sslVerify设置。 注意:始终首选按仓库,按服务器sslVerify忽略;全局设置标志是一个安全问题。将该URL替换为您要连接到的服务器的特定“基本” URL。

createURIish方法仅使用远程URI创建一个新的URIish对象,我使用另一种方法来降低复杂性(嵌套尝试):

private URIish createURIish() throws InvalidRemoteException {
    URIish u = null;
    try {
        u = new URIish(this.gitUrl);
    } catch (URISyntaxException e) {
        throw new InvalidRemoteException(
                MessageFormat.format(JGitText.get().invalidURL, this.gitUrl), e);
    }
    return u;
}

然后将URIish添加为新的远程服务器,最后调用pull命令。为此,我使用了UsernamePasswordCredentialsProvider,以便可以传递所连接的TFS服务器使用的PAT,但是您使用的username:pasword也应该可以使用。

答案 1 :(得分:0)

也许看看Config类,使用Config.setBoolean(" branch"," master"," isSslVerify",false)

相关问题