Software Development

Authenticating with JGit

JGit is a lightweight, pure Java library implementing the Git version control system. You can do a lot of operations using Java language such as create or clone Git repos, create branches, make commits, rebase or tag, you can see

this repo to learn how to use JGit and how to code the different commands.

But one thing that does not cover extensively is the authentication process. In this post I am going to show you how how to authenticate to a Git repository with
JGit.

First thing to do is add JGit as dependency:

dependency>
  <groupId>org.eclipse.jgit</groupId>
  <artifactId>org.eclipse.jgit</artifactId>
  <version>4.5.0.201609210915-r</version>
</dependency>
<dependency>
  <groupId>org.slf4j</groupId>
  <artifactId>slf4j-api</artifactId>
  <version>1.7.21</version>
</dependency>

Then let’s see a simple clone without authentication:

@Test
public void should_connect_to_public_repo() throws IOException, GitAPIException {
  final String REMOTE_URL = "https://github.com/lordofthejars/wildfly-example.git";

  // prepare a new folder for the cloned repository
  File localPath = File.createTempFile("TestGitRepository", "");
  localPath.delete();

  // then clone
  try (Git result = Git.cloneRepository()
            .setURI(REMOTE_URL)
            .setDirectory(localPath)
            .call()) {
        // Important to close the repo after being used
            System.out.println("Having repository: " + result.getRepository().getDirectory());
  }
}

In this case no authentication method is set. Now let’s see how to add a username and password in case of for example private repos:

@Test
public void should_connect_using_user_pass() throws IOException, GitAPIException {
  final String REMOTE_URL = "https://asotobu@bitbucket.org/asotobu/backup.git";

  // prepare a new folder for the cloned repository
  File localPath = File.createTempFile("TestGitRepository", "");
  localPath.delete();

  // then clone
  try (Git result = Git.cloneRepository()
            .setURI(REMOTE_URL)
            .setCredentialsProvider(new UsernamePasswordCredentialsProvider("username", "password"))
            .setDirectory(localPath)
            .call()) {
            
          System.out.println("Having repository: " + result.getRepository().getDirectory());
  }
}

In this case you only need to set as credential provider theUsernameAndPasswordCredentialsProvider and pass the required username and password.

The final scenario I am going to show here is how to authenticate against a git repository using your ssh keys, that is using (~/.ssh/id_rsa) and setting the passphrase to access it.

@Test
public void should_connect_to_public_ssh() throws IOException, GitAPIException {
  final String REMOTE_URL = "git@github.com:lordofthejars/wildfly-example.git";

  SshSessionFactory sshSessionFactory = new JschConfigSessionFactory() {
    @Override
    protected void configure(OpenSshConfig.Host host, Session session ) {
            session.setUserInfo(new UserInfo() {
              @Override
              public String getPassphrase() {
                return "passphrase";
              }

              @Override
              public String getPassword() {return null;}

              @Override
              public boolean promptPassword(String message) {return false;}

              @Override
              public boolean promptPassphrase(String message) {return true;}

              @Override
              public boolean promptYesNo(String message) {return false;}

              @Override
              public void showMessage(String message) {}
            });
        }
      };

  File localPath = File.createTempFile("TestGitRepository", "");
  localPath.delete();

  try (Git result = Git.cloneRepository()
          .setURI(REMOTE_URL)
          .setTransportConfigCallback(transport -> {
              SshTransport sshTransport = ( SshTransport )transport;
              sshTransport.setSshSessionFactory( sshSessionFactory );
          })
          .setDirectory(localPath)
          .call()) {
        System.out.println("Having repository: " + result.getRepository().getDirectory());
  }

}

In this case you need to extend JSchConfigSessionFactory to be able to set passphrase to access to private key. To do it you set a custom UserInfoimplementation where the getPassphrase method returns the passphrase to use andpromptPassphrase method should return true.

After that you only need to set the transport configuration to the one created.

We keep learning,
Alex.

Chan eil inneal-ciùil a ghleusar, ‘Dhùisgeas smuain mo chléibh gu aoibh, Mar nì duan o bheul nan caileag, Oidhche mhath leibh, beannachd leibh (Oidche Mhath Leibh – Ossian)

Music: https://www.youtube.com/watch?v=mi4SCOYAdEk

Reference: Authenticating with JGit from our JCG partner Alex Soto at the One Jar To Rule Them All blog.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button