javajgit

How to use JGit to push changes to remote with OAuth access token


I am able to push to remote with this piece of code

return git.push().setCredentialsProvider(new UsernamePasswordCredentialsProvider(user, password)).setRemote("origin").call();

I also am able to get oauth access token with all necessary scopes. How do I push with access token?


Solution

  • You need to pass a UsernamePasswordCredentialsProvider with the token as its user name.

    String remoteUrl = "https://${token}@github.com/user/repo.git";
    CredentialsProvider credentialsProvider = new UsernamePasswordCredentialsProvider("${token}", "");
    git.push().setRemote(remoteUrl).setCredentialsProvider(credentialsProvider).call();
    

    The above can at least be used to authenticate with a GitHub repository. Though, I can't say if this scheme works generally.