DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • How To Convert Image Files Into GIF or WebP Format Using Java
  • How To Validate Names Using Java
  • How to Convert a PDF to Text (TXT) Using Java
  • JGit Library Examples in Java

Trending

  • Unlocking Data with Language: Real-World Applications of Text-to-SQL Interfaces
  • Mastering Fluent Bit: Installing and Configuring Fluent Bit on Kubernetes (Part 3)
  • Ethical AI in Agile
  • A Modern Stack for Building Scalable Systems
  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Deployment
  4. How to Authenticate With JGit

How to Authenticate With JGit

In this post, Alex Soto shows you how to authenticate to a Git repository with JGit.

By 
Alex Soto user avatar
Alex Soto
·
Sep. 26, 16 · Tutorial
Likes (6)
Comment
Save
Tweet
Share
31.3K Views

Join the DZone community and get the full member experience.

Join For Free

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 look at 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 to authenticate to a Git repository with JGit.

The first thing to do is add JGit as a 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 the UsernameAndPasswordCredentialsProvider 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 the passphrase to access to the private key. To do it you set a custom UserInfo implementation where the getPassphrase method returns the passphrase to use and promptPassphrase method should return true.

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

Git Version control authentication Repository (version control) Java (programming language) Clone (Java method) Dependency Pass (software)

Published at DZone with permission of Alex Soto, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • How To Convert Image Files Into GIF or WebP Format Using Java
  • How To Validate Names Using Java
  • How to Convert a PDF to Text (TXT) Using Java
  • JGit Library Examples in Java

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!