11

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?

Rüdiger Herrmann
  • 20,512
  • 11
  • 62
  • 79
user1745356
  • 4,462
  • 7
  • 42
  • 70

1 Answers1

18

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.

Rüdiger Herrmann
  • 20,512
  • 11
  • 62
  • 79
  • 5
    turns out it is sufficient to include the token in the credentials provider. There is no need to reformat repository url. But anyways it works. – user1745356 Jan 23 '15 at 15:03
  • @user1745356 Thanks for the feedback. I've updated the answer accordingly. – Rüdiger Herrmann Jan 23 '15 at 16:12
  • @RüdigerHerrmann I also have similar question which is using `jgit` [here](http://stackoverflow.com/questions/28380719/how-to-use-jgit-to-clone-the-existing-repositories-to-new-github-instance). If possible, can you help me out? Started learning `jgit` today so got stuck. Any help will be greatly appreciated. – john Feb 07 '15 at 10:07
  • 1
    @RüdigerHerrmann Did anyone test this for `git push`? I get back just `not authorized` when trying to push a tag I created. Also in the github URL do you need to substitute the `user/repo.git` part with the actual name/owner of the repo? – sydd Aug 04 '15 at 18:12
  • 1
    @sydd yes, this works for the `PushCommand` and yes you need to supply the actual username/repo. – Rüdiger Herrmann Aug 05 '15 at 10:55
  • 3
    This approach is not working for bitbucket. Any idea on how to connect to bitbucket using token? – Santosh Sawant May 20 '20 at 14:39