Git authentication fails after enabling 2FA

You need to generate an access token. You can create one by going to your settings page.

enter image description here

Use this access token as your password in the command line.


An end-to-end solution takes 3 steps.

  1. Kudos to Gergo Erdosi. His answer is largely right, it is just that Github changes that setting page. As of late 2016, you need to generate an access token from your Personal access tokens page.

    enter image description here

    Use this access token as your password in the command line.

  2. You can persist your user name by including it into your project remote url. One of the way to do it is to edit your .git/config to modify the url line into the following format:

    url = https://[email protected]/owner/repo.git

  3. You can persist your password by run this for one time only:

    $ git config credential.helper store

    and then your future git password(s) will be stored in ~/.git-credentials, in plaintext, using the format https://user:[email protected].

    Storing password(s) in plaintext would normally be considered as a security risk. But in this 2FA case, the credential is NOT your real password, it is a randomly generated string. So it is as secure as using a ssh private key a passphrase-less ssh private key. CAVEAT: keep in mind that, if you happen to also use another git account(s) without 2FA on this machine, those real password(s) will also be stored in plaintext.

PS: Alternatively, you could choose to use ssh-based login, using a passphrase-protected ssh private key, which would be more secure and less convenient, but it is outside the scope of this answer.


You can set an SSH key (on both Linux and Windows)

💡 Note for Windows users
Make sure HOME environment variable is defined and set on your user's directory
e.g. C:\Users\jossef (learn more)


1) Generating a new SSH key (source)

Open terminal / cmd and paste the text below, (replace with your GitHub email address)

ssh-keygen -t rsa -b 4096 -C "[email protected]"

2) Link the public key to your GitHub account

  • On Linux / macOS, run in terminal:

    cat ~/.ssh/id_rsa.pub
    
  • On Windows, run in cmd:

    type %HOME%\.ssh\id_rsa.pub
    

This will output the public key:

ssh-rsa AAAAB3NzaC1y ... mKAKw== [email protected]

Navigate to https://github.com/settings/keys

  • Click New SSH Key
  • Give it a title
  • Copy-paste the public key from the previous command output

enter image description here


3) Change git origin from https:// to ssh

Open terminal / cmd and cd to your cloned repository directory and run:

git remote set-url origin [email protected]:<github username>/<repository name>

I had a similar problem. I had to alter the url used in the git command to include my username.

git push https://[email protected]/mlbileschi/scala.git

Then when it asks for PW use the access token you created from following the instructions in Gergo Erdosi's answer.