In this guide I will show you how to set up JGIT with SSH authentication using Apache MINA.
Using SSH to connect to Git instead of HTTP offers several advantages, primarily in security, convenience, and automation. SSH uses public-key cryptography, eliminating the need to enter passwords or manage personal access tokens (PATs) while ensuring encrypted communication. This makes it more secure than HTTP, which relies on credentials that can be intercepted or require frequent updates. Additionally, SSH is ideal for automation in CI/CD pipelines and scripting since authentication happens seamlessly with SSH keys. While HTTPS might be preferable in environments where setting up SSH keys is impractical or restricted, SSH remains the better choice for regular Git users due to its enhanced security, ease of use, and suitability for automation.
First of all we need to import the maven dependencies:
<dependency>
<groupId>org.eclipse.jgit</groupId>
<groupId>org.eclipse.jgit</groupId>
<artifactId>org.eclipse.jgit</artifactId>
<version>6.8.0.202311291450-r</version>
</dependency>
<dependency>
<groupId>org.eclipse.jgit</groupId>
<artifactId>org.eclipse.jgit.ssh.apache</artifactId>
<version>6.8.0.202311291450-r</version>
</dependency>
We create a ssh factory:
SshdSessionFactory sshdSessionFactory = new SshdSessionFactoryBuilder()
.setPreferredAuthentications("publickey,keyboard-interactive,password")
.setPreferredAuthentications("publickey,keyboard-interactive,password")
.setHomeDirectory(FS.DETECTED.userHome())
.setSshDirectory(sshDir)
.build(new JGitKeyCache());
SshSessionFactory.setInstance(sshdSessionFactory);
Now we can simply clone a Repository:
var repository = "git@github.com:eclipse-jgit/jgit.git";
var directory = "./directory";
Git.cloneRepository().setURI(repository)
.setDirectory(new File(directory))
.call();
Schicken Sie uns einfach eine Email an office@vorstieg.eu oder füllen Sie das folgende Kontakt-Formular aus: