555

I am trying to authenticate with GitHub using a personal access token. In the help files at GitHub, it states to use the cURL method to authenticate (Creating a personal access token). I have tried this, but I still cannot push to GitHub. Please note, I am trying to push from an unauthenticated server (Travis CI).

cd $HOME
git config --global user.email "emailaddress@yahoo.com"
git config --global user.name "username"

curl -u "username:<MYTOKEN>" https://github.com/username/ol3-1.git
git clone --branch=gh-pages https://github.com/username/ol3-1.git gh-pages

cd gh-pages
mkdir buildtest
cd buildtest
touch asdf.asdf

git add -f .
git commit -m "Travis build $TRAVIS_BUILD_NUMBER pushed to gh-pages"
git push -fq origin gh-pages

This code causes the errors:

remote: Anonymous access to scuzzlebuzzle/ol3-1.git denied.

fatal: Authentication failed for 'https://github.com/scuzzlebuzzle/ol3-1.git/'"

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
wayofthefuture
  • 8,339
  • 7
  • 36
  • 53
  • 3
    As of 2021-Aug-28, github CLI can be used to authenticate (no need to generating PAT, can directly login with password if browser can be opened). Checkout: https://github.com/cli/cli#installation, https://cli.github.com/manual/gh_auth_login – Nagabhushan S N Aug 28 '21 at 08:50

31 Answers31

539

Your curl command is entirely wrong. You should be using the following

curl -H 'Authorization: token <MYTOKEN>' ...

That aside, that doesn't authorize your computer to clone the repository if in fact it is private. (Taking a look, however, indicates that it is not.) What you would normally do is the following:

git clone https://scuzzlebuzzle:<MYTOKEN>@github.com/scuzzlebuzzle/ol3-1.git --branch=gh-pages gh-pages

That will add your credentials to the remote created when cloning the repository. Unfortunately, however, you have no control over how Travis clones your repository, so you have to edit the remote like so.

# After cloning
cd gh-pages
git remote set-url origin https://scuzzlebuzzle:<MYTOKEN>@github.com/scuzzlebuzzle/ol3-1.git

That will fix your project to use a remote with credentials built in.

Warning: Tokens have read/write access and should be treated like passwords. If you enter your token into the clone URL when cloning or adding a remote, Git writes it to your .git/config file in plain text, which is a security risk.

BMW
  • 42,880
  • 12
  • 99
  • 116
Ian Stapleton Cordasco
  • 26,944
  • 4
  • 67
  • 72
  • 1
    Thank you SO much for your help. It worked great. Here is a copy of my changed file: https://github.com/scuzzlebuzzle/ol3-1/blob/master/util/s.sh. I got it pretty close. For some reason it didn't push to the build1 directory I created, but it still pushed to the build directory so it worked! THANKS! – wayofthefuture Sep 21 '13 at 20:37
  • Also for some reason my github page editor button now says "Propose File Changes." Maybe I should remove the "git remote rm origin" line? – wayofthefuture Sep 21 '13 at 20:38
  • 1
    I don't know what editor button you're speaking of but removing the original remote is absolutely necessary. – Ian Stapleton Cordasco Sep 21 '13 at 21:46
  • Was talking about the button on the edit page at the bottom: https://github.com/scuzzlebuzzle/ol3-1/edit/master/util/s.sh. It still seems to save changes though so doesn't look like a problem. Again, thank you. I added a sigma rocks file in the directory! – wayofthefuture Sep 21 '13 at 23:01
  • 1
    Heh. [Cool.](https://github.com/scuzzlebuzzle/ol3-1/blob/gh-pages/sigma/sigma.rocks) Glad to help. – Ian Stapleton Cordasco Sep 22 '13 at 01:49
  • 19
    You don't have to rm the remote, you can use set-url instead, as in `git remote set-url origin https://scuzzlebuzzle:@github.com/scuzzlebuzzle/ol3-1.git` – berkus Jan 16 '17 at 07:33
  • 3
    Insecure approach. Key easily cat'd to logs on error. Use a tightly scoped deploy key instead. – Joseph Lust Jan 07 '18 at 03:34
  • Notice that you can also clone using the url with only the token like `git clone https://@github.com/scuzzlebuzzle/ol3-1.git`. The Windows client will save the token in the origin remote (that gets added automatically upon cloning), so future commands will work, BUT I discovered that the Linux client won't, except if you also add the username before the token. This answer gave me the idea to try with the username also. Thanks! – LucasMetal Dec 12 '18 at 10:46
  • btw: personal access tokens can be created here: https://github.com/settings/tokens – Datz Dec 11 '20 at 10:10
  • 1
    Note that a more secure approach is to do `git push https://username:@github.com/username/repo.git ` since that doesn't store the token in plaintext. – Kartik Soneji Jul 16 '21 at 09:55
  • 1
    @KartikSoneji - Sure it does... in you bash history. I'm unclear on how this new token based auth could be more secure than private ssh key. Every solution I've seen so far involves exposing the token in some way. – Joshua Kolden Aug 16 '21 at 20:35
  • @JoshuaKolden Sorry, I meant that as someone using Windows cmd, which doesn't store command history once the terminal exits. Also, you can prefix the command with a space to keep it out of your bash history, and you cannot normally read the `~/.bash_history` of other users. Finally, I agree that SSH keys are the most secure, but this is more useful when you need to do a push from a system (like a remote server) without having to setup too many things. – Kartik Soneji Aug 17 '21 at 16:46
  • @KartikSoneji Agreed. I'm just pointing out that GitHub (and the community) should probably be recommending a move to ssh auth, not token auth as a consequence of no password access (i.e. command line git and other manual use cases). We've had deploy keys for remote server automation for a long time now. GitHub communication is very odd on this topic. – Joshua Kolden Aug 17 '21 at 20:27
  • Normal git workflows do not expose passwords or ssh private keys to other users with read access to a repo. The above advice does. It allows anyone with read access to a copy of a local repo, including for example a shared work or school filesystem, to see the user's clear text Personal Access Token. This extends to archived copies as well, such as source tarballs that retain the .git directory. – Joshua Kolden Aug 18 '21 at 04:45
  • OMG thank you so much! I was getting a real headache with github's new two factor authentication system... – Dmitry Kamenetsky Aug 21 '21 at 03:42
  • 4
    the command you are looking for is `git remote set-url origin https://:@github.com//.git` – Lukas Sep 03 '21 at 09:35
  • @Lukas's comment worked for me. `scuzzlebuzzle` in the answer is your github username, which will be in the URL for the repository. So, get the URL (in the github settings for the repository), and prefix it with (from the URL) and , ie `:@`, in `git remote set-url origin ` – Stephen Hosking Oct 23 '21 at 09:34
  • How does one update the token in local with the new generated token if we have cloned using old access token `git clone https://username:personalaccesstoken@github.com/repo`? – Haslo Vardos Aug 01 '22 at 11:13
  • 1
    @StephenHosking When using a GitHub personal access token, the username is not required by GitHub. I could do `git push https://scuzzlebuzzle:@github.com//.git` and it will push as my user account. – wheeler Feb 02 '23 at 02:15
344

First, you need to create a personal access token (PAT). This is described here: https://help.github.com/articles/creating-an-access-token-for-command-line-use/

Laughably, the article tells you how to create it, but gives absolutely no clue what to do with it. After about an hour of trawling documentation and Stack Overflow, I finally found the answer:

$ git clone https://github.com/user-or-organisation/myrepo.git
Username: <my-username>
Password: <my-personal-access-token>

I was actually forced to enable two-factor authentication by company policy while I was working remotely and still had local changes, so in fact it was not clone I needed, but push. I read in lots of places that I needed to delete and recreate the remote, but in fact my normal push command worked exactly the same as the clone above, and the remote did not change:

$ git push https://github.com/user-or-organisation/myrepo.git
Username: <my-username>
Password: <my-personal-access-token>

(@YMHuang put me on the right track with the documentation link.)

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Echelon
  • 7,306
  • 1
  • 36
  • 34
  • 7
    I tried several times this approach, but I am facing the same issue. I generated the PTA and then tried to authenticate after push command execution, putting my username and my token. It still tells me that credentials are wrong. What am I missing in these steps? – johnny_kb Jan 26 '20 at 22:29
  • 61
    So where are we expected to get the token from in order to enter it wherever it's needed? Are we seriously expected to copy it into a file everywhere and then paste it into authentication prompts whenever we need to use Git. If so that's the shitest workflow I've ever heard of but the Git docs don't seem to have any other suggestions. – Neutrino Jan 11 '21 at 19:27
  • 6
    _"Beginning August 13, 2021, we will no longer accept account passwords when authenticating Git operations on GitHub.com."_ This should be interesting. – luizfls Apr 29 '21 at 03:09
  • I didn't have to `git push url`. Just git push was good enough, along with username, and password. – agent18 May 02 '21 at 17:35
  • 51
    Why don't they explain what to do with the token after creating it?! – Rony Tesler May 27 '21 at 20:07
  • After doing `git push https://github.com/user-or-organisation/myrepo.git` ; `git` still asks for username and password – alper Jun 20 '21 at 10:04
  • 4
    All the people here who are rightly complaining about GitHub's failure to indicate how to use the token have visitied https://docs.github.com/en/github/authenticating-to-github/keeping-your-account-and-data-secure/creating-a-personal-access-token#using-a-token-on-the-command-line and given feedback at the bottom of the page, right? – John Perry Jun 26 '21 at 06:24
  • Yes thank you! They need to update their docs. This would have saved me an hour of my time. – Droid Chris Jun 30 '21 at 20:35
  • 1
    In short, basically instead of typing in your password, you should just type in the access token. This is also for the git push. – Corey Levinson Jan 01 '22 at 04:05
  • 7
    Nobody knows their PAT from he top of their head. So they "force" us to put the PAT into the git config for the remote url where anyone can access it. I don't understand this decision from GitHub. – T3rm1 Mar 04 '22 at 10:05
  • 1
    Agreed - they explain how to generate the token, but provide no help in how to use . Since M$ bought Github it's gone to the dogs. – Molecool Mar 29 '23 at 11:13
  • @T3rm1 The tokens are scoped and can be easily managed (revoked) from the UI. You don't have to worry about your github credentials which will remain secret. Make sure to scope the tokens wisely. In that, they are a very usable packaged version of ssh keys. – akhan Apr 23 '23 at 19:43
161

Generating a token

Generate a token using the instructions from Creating a personal access token. (GitHub profile -> Settings -> Developer Settings -> Personal access tokens)

Actually using the token

  • If you already have the repository cloned locally
git remote remove origin
git remote add origin https://[TOKEN]@github.com/[REPO-OWNER]/[REPO-NAME]
git push
  • If you are cloning a new repository
git clone https://[TOKEN]@github.com/[REPO-OWNER]/[REPO-NAME]

(Replace the square brackets and what's between them with your corresponding details. The part after the the @ is the same as the repository url without https://)

Scriddie
  • 2,584
  • 1
  • 10
  • 17
  • First I used this one `git remote set-url origin https://[TOKEN]@git.mycompany.com/[ORGANIZATION]/[REPO].git` , it just worked for git pull, but when I ran command git push, git again prompt for username. Its annoying to put token in password field again and again, so above mentioned commands in same order worked for me. – Abdul Aug 24 '21 at 06:25
  • 1
    To grantee that all these steps will work while pushing to Github, you need to select the scopes, or permissions, you'd like to grant this token to access your repositories from the command line. – Noha Salah Sep 10 '21 at 07:42
  • 6
    If you try this for an organization, (and you're stupid like me), be aware that [USER] means your organization's user name and not your personal user name. – Gedde Sep 23 '21 at 09:19
  • 3
    Actually, you don't need to `remove` origin and then add. It will be overwritten so just the `add` is sufficient – testing_22 Oct 28 '21 at 03:39
  • Short & Simple for all users :) – TarangP Nov 27 '21 at 09:35
  • 2
    Worked great to update an expired token on an existing local repo. Thanks. – Milo Persic Dec 01 '22 at 15:36
  • 1
    ok, so before my account was protected by a private key using ssh, now it's unprotected. this bothers me so much... – kritzikratzi Jan 24 '23 at 22:53
  • Oh, so one goes and put a private information in the clear, in an URL, for every sniffer and router to see. And bash history. nice. – v.oddou Jul 12 '23 at 04:43
128

This worked for me using ssh:

SettingsDeveloper settingsGenerate new token.

git remote set-url origin https://[APPLICATION]:[NEW TOKEN]@github.com/[ORGANISATION]/[REPO].git
BMW
  • 42,880
  • 12
  • 99
  • 116
ccreedon1
  • 1,367
  • 1
  • 9
  • 9
  • 41
    This also works for personal access tokens using this format: `git remote add origin https://[USERNAME]:[NEW TOKEN]@github.com/[USERNAME]/[REPO].git` – CommandZ Jun 30 '19 at 21:33
  • 6
    I had to do `git remote add origin https://[USERNAME]:[TOKEN]@git.mycompany.com/[ORGANIZATION]/[REPO].git` – pacoverflow Jul 19 '19 at 18:23
  • Isn't this a bad idea? Won't the token get cached in the console history? – TheRealChx101 Sep 26 '19 at 17:29
  • 2
    Also worked for me git remote add origin https://[TOKEN]@git.mycompany.com/[ORGANIZATION]/[REPO].git – Thomas Chafiol Feb 25 '20 at 13:05
  • 5
    @TheRealChx101You can use something like `git remote set-url origin https://[TOKEN]@git.mycompany.com/[ORGANIZATION]/[REPO].git> /dev/null 2>&1` to avoid logging of insecure git output. Store the token in a variable to avoid having it in the log. But it needs to be stored somewhere. To secure further you can store it encrypted. This approach is for example supported by Travis CI. – kap Feb 27 '20 at 23:08
  • 2
    @ThomasChafiol and TheRealChx101 When your token expires or if eg, windows password updates your company-wide enterprise authentication this would be the correct approach or rather a combination of your two answers `git remote set-url origin https://[TOKEN]@git.mycompany.com/[ORGANIZATION]/[REPO].git` – ccreedon1 Sep 23 '20 at 10:37
  • This is the best answer can you share a source to this information besides is there any automated way to update token for example `git update-token my-secret-token`using `set-url` with manually edited url is error prone – Muhammed Ozdogan Oct 06 '21 at 22:38
  • You can regenerate personal access token anytime if you forgot. It will be like string ghp_nGCyfjofU5LVCTvUUkVsjP7Yd9qkya1HxCo8. Now on github it is your password to push your project on github. – PHP Laravel Developer May 17 '22 at 05:08
88

Automation / Git automation with OAuth tokens

$ git clone https://github.com/username/repo.git
  Username: your_token
  Password:

It also works in the git push command.

Reference: https://help.github.com/articles/git-automation-with-oauth-tokens/

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
John Huang
  • 1,298
  • 10
  • 14
  • 10
    The key is to set git so that you do not need to be prompted at all times for your token, as described here - https://help.github.com/articles/caching-your-github-password-in-git/ Other answers to this question will end up writing your token in plaintext to .git/config which could be considered a security risk. – jerome Oct 03 '15 at 01:20
  • This is the safest approach so far. – Ismail Jul 29 '22 at 02:42
86

Step 1: Get the access token

Go to this link: https://github.com/settings/tokens. And generate the token there.

Or from you Github account, Go to:
Settings -> Developer Settings -> Personal Access Tokens

Step 2: Use the token

git push

Username: <your username>
Password: <the access token>
Omar Magdy
  • 2,331
  • 14
  • 13
  • 15
    For anyone wanting things to work like they do for Omar, I could not get it to work unless i first did `$ git config credential.helper store`. Note: The credentials will be saved unencrypted on a file inside your home directory, therefore use it with discretion. [A better explanation can be found here](http://gmacario.github.io/2017/08/08/cmdline-git-with-github-2fa.html) – Steinarr Mar 11 '21 at 12:20
  • 3
    @Steinarr the link is not valid. – Timo Jun 21 '21 at 19:25
  • 1
    @Timo [here](https://web.archive.org/web/20201216132223/http://gmacario.github.io/2017/08/08/cmdline-git-with-github-2fa.html) is a wayback machine link to the site as it was – Steinarr Jun 22 '21 at 21:15
  • 3
    More simple than this is impossible. Thanks! – Emerson Pardo Sep 13 '21 at 16:53
  • 1
    This worked beautifully! – zero_cool Jul 10 '23 at 03:51
42

To avoid handing over "the keys to the castle"...

Note that sigmavirus24's response requires you to give Travis a token with fairly wide permissions -- since GitHub only offers tokens with wide scopes like "write all my public repos" or "write all my private repos".

If you want to tighten down access (with a bit more work!) you can use GitHub deployment keys combined with Travis encrypted yaml fields.

Here's a sketch of how the technique works...

First generate an RSA deploy key (via ssh-keygen) called my_key and add it as a deploy key in your github repo settings.

Then...

$ password=`openssl rand -hex 32`
$ cat my_key | openssl aes-256-cbc -k "$password" -a  > my_key.enc
$ travis encrypt --add password=$password -r my-github-user/my-repo

Then use the $password file to decrypt your deploy key at integration-time, by adding to your yaml file:

before_script: 
  - openssl aes-256-cbc -k "$password" -d -a -in my_key.enc -out my_deploy_key
  - echo -e "Host github.com\n  IdentityFile /path/to/my_deploy_key" > ~/.ssh/config
  - echo "github.com ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAq2A7hRGmdnm9tUDbO9IDSwBK6TbQa+PXYPCPy6rbTrTtw7PHkccKrpp0yVhp5HdEIcKr6pLlVDBfOLX9QUsyCOV0wzfjIJNlGEYsdlLJizHhbn2mUjvSAHQqZETYP81eFzLQNnPHt4EVVUh7VfDESU84KezmD5QlWpXLmvU31/yMf+Se8xhHTvKSCZIFImWwoG6mbUoWf9nzpIoaSjB+weqqUUmpaaasXVal72J+UX2B+2RPW3RcT0eOzQgqlJL3RKrTJvdsjE3JEAvGq3lGHSZXy28G3skua2SmVi/w4yCE6gbODqnTWlg7+wC604ydGXA8VJiS5ap43JXiUFFAaQ==" > ~/.ssh/known_hosts

Note: the last line pre-populates github's RSA key, which avoids the need for manually accepting at the time of a connection.

Bosh
  • 8,138
  • 11
  • 51
  • 77
39

Normally I do like this:

 git push https://$(git_token)@github.com/user_name/repo_name.git

The git_token is reading from variable config in Azure DevOps.

You can read my full blog post here.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Tony Ngo
  • 19,166
  • 4
  • 38
  • 60
  • this can invoke: remote: No anonymous write access. – Fergus Aug 16 '21 at 05:04
  • I Actually had to remove the dollar sign in order to make it work. Thus the template should actually look like this: git push https://(git_token)@github.com/user_name/repo_name.git – Bialomazur Jul 31 '22 at 11:12
39

For macOS, if you are not prompted with a username and password request, it means your password is stored in Keychain Access. Every time you try to clone or push it will try to use your old password.

Follow these three steps to solve this:

  1. Generate a PAT (personal access token) - LINK
  2. Open KeyChain Access (Via spotlight search) → search GitHub → click GitHub → change and save with your new PAT link
  3. Try to push or clone again. Now you have stored the PAT instead of your password.
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
35

You can easily change your remote Authentication, first:

Remove your current origin:

git remote remove origin

And then:

git remote add origin https://<TOKEN>@github.com/<USERNAME>/<REPO>.git

You can find how to generate your Authentication Token here.

Brunno
  • 977
  • 17
  • 28
26

I'm on Ubuntu 20.04 (Focal Fossa) and I kept getting the message that soon I wouldn't be able to log in from console. I was terribly confused.

Finally, I got to the URL below which will work. But you need to know how to create a PAT (personal access token) which you are going to have to keep in a file on your computer.

Here's what the final URL will look like:

git push https://1234567890123456789012345678901234567890@github.com/user-name/repo.git

long PAT (personal access token) value -- The entire long value between the // and the @ sign in the URL is your PAT.

user-name will be your exact username

repo.git will be your exact repository name

Also you will be able to use it this way too:

When you do a

git push

1. You'll be prompted for a username and password

2. Just submit your username as normal

3. Now submit your PAT as your password and it will work.

You need to generate a PAT following the steps at: Creating a personal access token

That will give you the PAT value that you will place in your URL.

When you create the PAT make sure you choose the following options so it has the ability to allow you to manage your repositories.

PAT settings

Save Your PAT Or Lose It

Once you have your PAT, you're going to need to save it in a file locally so you can use it again. If you don't save it somewhere there is no way to ever see it again and you'll be forced to create a new PAT.

Now you're going to need at the very least:

  1. a way to display it in your console so you can see it again.
  2. or, a way to copy it to your clipboard automatically.

For 1, just use:

cat ~/files/myPatFile.txt

Where the path is a real path to the location and file where you stored your PAT value.

For 2

xclip -selection clipboard < ~/files/myPatFile.txt

That'll copy the contents of the file to the clipboard so you can use your PAT more easily.

FYI - if you don't have xclip do the following:

sudo apt-get install xclip

It downloads and installs xclip. If you don't have apt-get, you might need to use another installer (like YUM).

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
raddevus
  • 8,142
  • 7
  • 66
  • 87
  • `git config credential.helper cache` could be used to save password for a default of 15 mins. Also `git config credential.helper store` can be used to permanently store the password for that repo (less "secure"). More info [here](http://gmacario.github.io/2017/08/08/cmdline-git-with-github-2fa.html) – agent18 May 02 '21 at 17:37
23

I previously used passwords to access my private repositories using Git CLI and had saved my credentials with git config --global credential.helper store.

As support for passwords has been dropped today, I couldn't manage to update my credentials with the token using the git config commands suggested.

If anyone else has this problem on Linux, you can manually update the ~/.git-credentials file, e.g.

nano ~/.git-credentials

Enter your token between the : and @ symbols. (To save and close the file, press Ctrl + O, Enter, Ctrl + X).

You might have to also run the following command after updating your token in the credentials file (see @guhur's comment):

git config --global credential.helper store

Note that by using Git's credential helper, anyone who has access to your home directory can see your token.

undefined
  • 1,019
  • 12
  • 24
  • 1
    Thanks, this was literally the only thing that worked for me after spending 3 hours on this. Only I deleted ~/.git-credentials, and then used git config credential.helper store – WickedElephant Aug 13 '21 at 18:40
  • Thanks. So the steps are: 1) create a personal token from Github, 2) put :@ in ~/.git-credentials, 3) run `git config --global credential.helper store` – guhur Aug 16 '21 at 11:34
  • @guhur not sure step 3 is even needed. The next time authentication is required, git directly reads from the credentials file (at least as far as I recall) – undefined Aug 16 '21 at 12:22
  • 1
    I actually needed it – guhur Aug 16 '21 at 15:25
  • 1
    Thanks!! This was what I really needed :) – fmrico Aug 23 '21 at 10:19
  • What is *"the token sugin"*? Please respond by [editing (changing) your answer](https://stackoverflow.com/posts/68776295/edit), not here in comments (***without*** "Edit:", "Update:", or similar - the answer should appear as if it was written today). – Peter Mortensen Aug 31 '21 at 12:58
  • @PeterMortensen Thanks for pointing this out; that was just a typo. I have edited my answer. – undefined Sep 01 '21 at 01:42
  • I was able to authenticate VSC via PAT but following previous steps, in cli keeing getting "fatal: credential url cannot be parsed: token" – Carmine Tambascia Sep 14 '21 at 20:47
  • @CarmineTambascia Haven't worked with VSC, but it's possible it uses its own git binary. A similar issue has been brought here https://stackoverflow.com/q/61383299/7089726, maybe that can help you solve the issue with git cli. – undefined Sep 15 '21 at 19:03
  • maybe I wasn't clear, with VSC the authentication via PAT is working fine. The issue I am facing is via Command line(ubuntu) – Carmine Tambascia Sep 16 '21 at 08:10
  • @Carmine no idea what VSC PAT is. When using git cli, make sure git credentials file doesn't have an excess empty line (as suggested in the answer I shared). Also see this answer if you are running a version older than 2.27 (`git --version`) https://stackoverflow.com/a/61704149/7089726. It suggests this could be due to a bug with URL parsing in an older version. – undefined Sep 17 '21 at 09:29
  • @undefined PAT stay for Personal Access Token, as discussed in this question. It is the new way to authorizing access to github. Nevertheless thank you for the link, I will have a look – Carmine Tambascia Sep 17 '21 at 11:04
15

I had to add oauth or oauth2 as username to successfully authenticate:

https://oauth:<TOKEN>@github.com/user/repo.git
Mechanic
  • 5,015
  • 4
  • 15
  • 38
  • 3
    It seems the username doesn't matter at all. I tried "foobar" and it still worked. But not prefixing with ":" leads to the following error: ```fatal: could not read Password for 'https://***@github.com': No such device or address``` – siwyd Nov 29 '22 at 10:00
  • @siwyd hmm... interesting, so it should work like this as well `https://:@github.com/user/repo.git` – Mechanic Nov 29 '22 at 11:40
13

The only answer that helped me in a VS Code environment and a private GitHub.

git clone https://[MY_USER_NAME]:[GITHUB_PERSONAL_ACCESS_TOKEN]@github.com/davidsonlima/davidson-myrepo.git without square brackets

MiKr13
  • 1,297
  • 13
  • 20
Davidson Lima
  • 788
  • 9
  • 17
12

The following steps works for me:

  1. git remote remove origin

  2. git remote add origin https://[TOKEN]@[REPO LINK]

For example, my repo name is: https://github.com/username/codf.git.

The command will be:

git remote add origin https://[TOKEN]@github.com/username/codf.git

  1. git push origin branchName
Ping Woo
  • 1,423
  • 15
  • 21
12

Since I am using macOS, I can answer this for macOS specifically. We can use this for Windows also. It works!! In your GitHub account, click on the top right avatar and go to settings profile.

Click on Settings:

settings

Click on Developer settings:

Developer settings

Click on Personal Access Tokens:

Personal Access Tokens

Personal Access Tokens (Details)

And then click on Generate new token:

generate new token

Give a name to your access token and check on the first option.

Scroll down and click on generate token

Now, when you push the repo, use the following syntax:

git remote add origin https:<access__token>://@github.com/<username>/<repo__name>.git

git push https://<access__token>@github.com/<username>/<repo__name>.git

In my opinion, you can use the second option, while pushing the repo provide access token and you're good to go.

9
  1. git remote remove origin
    
  2. git remote add origin https://{accesstoken}:{accesstoken}@gitlab.com/{username}/{repo}.git
    
  3. git push https://{youraccesstoken}@github.com/{username}/{repo}.git
    

This works for me.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Flame alchemist
  • 107
  • 1
  • 4
8

If you're using GitHub Enterprise and cloning the repository or pushing gives you a 403 error instead of prompting for a username/token, you can use this:

  1. Delete the repository

  2. Open a command prompt and navigate to the folder you want the repository in

  3. Type:

    git clone https://[USERNAME]:[TOKEN]@[GIT_ENTERPRISE_DOMAIN]/[ORGANIZATION]/[REPO].git
    
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Gigazelle
  • 1,424
  • 1
  • 24
  • 34
  • 1
    Normal git workflows do not expose passwords or ssh private keys to other users with read access to a repo. The above advice does. It allows anyone with read access to a copy of a local repo, including for example a shared work or school filesystem, to see the user's clear text Personal Access Token. This extends to archived copies as well, such as source tarballs that retain the .git directory. – Joshua Kolden Aug 18 '21 at 04:53
  • The only answer that helped me in a VS Code environment and a private GitHub. First generate the token here: https://github.com/settings/tokens. Second do a "cd" to the right place in your computer. Third follow as example: ```git clone https://davidsonlima:qwertyuiopasdfghjklzxcvbnm@github.com/davidsonlima/davidson-myrepo.git``` – Davidson Lima Nov 16 '21 at 19:17
7

I suffered with this problems but found a solution:

git push https://github.com/<username>/<project_name>
and
username: paste your personnal access token
password: paste your personnal access token
Ibrahima Ba
  • 133
  • 1
  • 4
6

For Windows:

  1. Open Credential Manager - Windows Credentials
  2. Find the entry of git:https://github.com, edit it
  3. replace your former password with the PAT access token
  4. Solved
Sumithran
  • 6,217
  • 4
  • 40
  • 54
Pu1se
  • 61
  • 1
  • 2
4

For those coming from GitLab, what's worked for me:

Prerequisite:

Create a token:

    1. Select the necessary permissions
    1. Select expiration date
    1. Generate by pressing create personal access token
  • Save the token!

Step 1.

Add a remote:

git remote add origin https://<access-token-name>:<access-token>@gitlab.com/path/to/project.git

Step 2.

Pull once:

https://<access-token-name>:<access-token>@gitlab.com/path/to/project.git

Now you are able to read/write to/from the repository

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Artem Kozlenkov
  • 975
  • 9
  • 11
4

Lately github is not allowing commits directly from cmd using our username and password. For that we need to generate the accesss token as elaborated here.

And then use the same access token as username and password in the command prompt for git commands git push, git pull etc. For example

git push origin master
Username for 'https://github.com': lhq_4npmklMYXXXXXXXXXXXXXXXXXXXL8SxHxU
Password for 'https://lhq_4npmklMYXXXXXXXXXXXXXXXXXXXL8SxHxU@github.com':<give same access token here as password too>

And you start to see the code logs as:

Enumerating objects: 24, done.
Counting objects: 100% (24/24), done.
Delta compression using up to 8 threads
Compressing objects: 100% (14/14), done.
Writing objects: 100% (18/18), 6.33 KiB | 539.00 KiB/s, done.
Total 18 (delta 5), reused 0 (delta 0), pack-reused 0
remote: Resolving deltas: 100% (5/5), completed with 2 local objects.
To https://github.com/xxxxxxxxxxx/xxx-xxxxx-repo.git
123456..1233456  master -> master

Hope this helps someone. Happy Coding !!! :)

Kailas
  • 7,350
  • 3
  • 47
  • 63
  • 1
    Works like a charm. Was just curious to know whether we could save our token somewhere so that we do not have to copy and paste it every time? Somewhere like in the git config? I want to run it in my Windows WSL, if that is any help. – Rahul Saxena Oct 18 '21 at 14:26
4

It can be done using github deploy keys which narrow access to a single github repo as well as making write permission optional.

Github deploy keys use a user generated ssh key using ssh-keygen which creates a private key file and a public key files.

Suppose the key name given ssh-keygen is key-test, and the private and public files live in ~/.ssh/key-test and ~/.ssh/key-test.pub respectively.

Suppose the github project name is keytest.

To add a deploy key to project via the github project web page, got settings/deploy keys and click add. Paste the contents of the public key file ~/.ssh/key-test.pub into the target box and confirm.

Modify the contents of your ~/.ssh/config file to include the following:

Host gh-keytest
        Hostname github.com
        IdentityFile=/home/user/.ssh/key-test

Note: gh-keytest is an arbitrary alias.

Now you can push using

git push git@gh-keytest:<githubaccountname>/keytest.git

To do it using only push

git remote remove origin  # in case origin is already set
git remote add origin git@gh-keytest:<githubaccountname>/testscope.git
git push --set-upstream origin main

Note: Replace main with the correct intended branch name.

Thereafter

git push 

is sufficient.

Craig Hicks
  • 2,199
  • 20
  • 35
  • This only works if your Organization in GitHub does not require SAML SSO. If they do, you have to use a Token as demonstrated in other answers. The TO did not specify whether that is the case for them, but it may be relevant to others who come here for a solution. – trs Oct 03 '22 at 22:11
3

Having struggled with this issue for pretty much a full day, hard coding in the ORG/REPO section into our build script getting the dreaded 'remote not found' error, eventually I found a working solution by using TRAVIS_REPO_SLUG.

Switching this in for the hardcoded attributes worked immediately.

git remote set-url origin https://[ORG]:${TOKEN}@github.com/${TRAVIS_REPO_SLUG}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
mdmjsh
  • 915
  • 9
  • 20
3

For Mac users:

  1. Open Keychain Access and find GitHub

  2. Right-click in GitHub

  3. Click delete

  4. Open the terminal and try to clone a private project

  5. Add the required values
    Username: $your GitHub username
    Password: $paste token here
    And hit Enter. Voilà - the token has been added.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ashique Bava
  • 2,486
  • 2
  • 9
  • 21
2

The password that you use to log in to github.com portal does not work in the Visual Studio Code CLI/shell. You should copy the PAT token from URL https://github.com/settings/tokens by generating a new token and paste that string in CLI as the password.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Kanna Reddy
  • 309
  • 4
  • 5
2

To update your remote repo with a new access token

git remote set-url origin https://{{your_username}}:{{your_new_token}}@github.com/{{repo_path}}.git
jawad
  • 775
  • 6
  • 16
1

By having struggling so many hours on applying GitHub token finally it works as below:

$ cf_export GITHUB_TOKEN=$(codefresh get context github --decrypt -o yaml | yq -y .spec.data.auth.password)

  • code follows Codefresh guidance on cloning a repo using token (freestyle}
  • test carried: sed %d%H%M on match word '-123456-whatever'
  • push back to the repo (which is private repo)
  • triggered by DockerHub webhooks

Following is the complete code:

version: '1.0'
steps:
  get_git_token:
    title: Reading Github token
    image: codefresh/cli
    commands:
      - cf_export GITHUB_TOKEN=$(codefresh get context github --decrypt -o yaml | yq -y .spec.data.auth.password)
  main_clone:
    title: Updating the repo
    image: alpine/git:latest
    commands:
      - git clone https://chetabahana:$GITHUB_TOKEN@github.com/chetabahana/compose.git
      - cd compose && git remote rm origin
      - git config --global user.name "chetabahana"
      - git config --global user.email "chetabahana@gmail.com"
      - git remote add origin https://chetabahana:$GITHUB_TOKEN@github.com/chetabahana/compose.git
      - sed -i "s/-[0-9]\{1,\}-\([a-zA-Z0-9_]*\)'/-`date +%d%H%M`-whatever'/g" cloudbuild.yaml
      - git status && git add . && git commit -m "fresh commit" && git push -u origin master

Output...

On branch master 
Changes not staged for commit: 
  (use "git add ..." to update what will be committed) 
  (use "git checkout -- ..." to discard changes in working directory) 

modified:   cloudbuild.yaml 

no changes added to commit (use "git add" and/or "git commit -a") 
[master dbab20f] fresh commit 
 1 file changed, 1 insertion(+), 1 deletion(-) 
Enumerating objects: 5, done. 
Counting objects:  20% (1/5) ...  Counting objects: 100% (5/5), done. 
Delta compression using up to 4 threads 
Compressing objects:  33% (1/3) ... Writing objects: 100% (3/3), 283 bytes | 283.00 KiB/s, done. 
Total 3 (delta 2), reused 0 (delta 0) 
remote: Resolving deltas:   0% (0/2)  ...   (2/2), completed with 2 local objects. 
To https://github.com/chetabahana/compose.git 
   bbb6d2f..dbab20f  master -> master 
Branch 'master' set up to track remote branch 'master' from 'origin'. 
Reading environment variable exporting file contents. 
Successfully ran freestyle step: Cloning the repo 
eQ19
  • 9,880
  • 3
  • 65
  • 77
1
  1. Clone your project -> git clone https://token@github.com//project.git
  2. In Project folder -> git config --global credential.helper cache

and work

1

Select vcs → push tab from Android Studio. A popup would be displayed with username and password. Enter your username and instead of a password, enter the token number. It will get pushed to the repository.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Vinay Bakle
  • 133
  • 13
0

After generating access token from Developer setting, run these commands, git push origin [branch] Username for 'https://github.com': [accessToken] Password for 'https://[accessToken]@github.com':[accessToken]

MechaCode
  • 195
  • 1
  • 11