2086

I recently switched to synchronizing my repositories to https:// on GitHub (due to firewall issues), and it asks for a password every time.

Is there a way to cache the credentials, instead of authenticating every time that git push?

VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
Zepplock
  • 28,655
  • 4
  • 35
  • 50
  • 2
    You now can use a credential helper to encrypt the `_netrc` file containing your credentials. See [my answer below](http://stackoverflow.com/a/18362082/6309). I found that safer that the `git-credential-winstore.exe` (memory cache) which is a bit buggy on Windows. – VonC Aug 21 '13 at 15:50
  • 4
    See also [Git push requires username and password](http://stackoverflow.com/questions/6565357/git-push-requires-username-and-password) and [Git keeps prompting me for password](http://stackoverflow.com/questions/7773181/git-keeps-prompting-me-for-password). –  Aug 22 '13 at 13:08
  • A secure user-friendly alternative to SSH or personal access tokens is OAuth via Git Credential Manager, see my answer https://stackoverflow.com/a/71286601/284795 – Colonel Panic Apr 07 '22 at 18:33

28 Answers28

2618

Since Git 1.7.9 (released 2012), there is a neat mechanism in Git to avoid having to type your password all the time for HTTP / HTTPS, called credential helpers.

You can just use one of the following credential helpers:

git config --global credential.helper cache

The credential.helper cache value tells Git to keep your password cached in memory for a particular amount of minutes. The default is 15 minutes, you can set a longer timeout with:

# Cache for 1 hour
git config --global credential.helper "cache --timeout=3600"

# Cache for 1 day
git config --global credential.helper "cache --timeout=86400"

# Cache for 1 week
git config --global credential.helper "cache --timeout=604800"

You can also store your credentials permanently if so desired, see the other answers below.

GitHub's help also suggests that if you're on Mac OS X and used Homebrew to install Git, you can use the native Mac OS X keystore with:

git config --global credential.helper osxkeychain

For Windows, there is a helper called Git Credential Manager for Windows or wincred in msysgit.

git config --global credential.helper wincred # obsolete

With Git for Windows 2.7.3+ (March 2016):

git config --global credential.helper manager

For Linux, you would use (in 2011) gnome-keyring(or other keyring implementation such as KWallet).

Nowadays (2020), that would be (on Linux)

Fedora

sudo dnf install git-credential-libsecret
git config --global credential.helper /usr/libexec/git-core/git-credential-libsecret

Ubuntu

sudo apt-get install libsecret-1-0 libsecret-1-dev
cd /usr/share/doc/git/contrib/credential/libsecret
sudo make
git config --global credential.helper /usr/share/doc/git/contrib/credential/libsecret/git-credential-libsecret
Louis Go
  • 2,213
  • 2
  • 16
  • 29
Mark Longair
  • 446,582
  • 72
  • 411
  • 327
  • 81
    Don't store your password in plain text. As of Git 1.7.9 you can use credential helpers. `git config --global credential.helper osxkeychain` on OS X. For other OS see https://help.github.com/articles/set-up-git – dazonic Jun 22 '12 at 07:29
  • 6
    FWIW, the osx keychain stuff is part of base GIT source code, it's not an exclusive component of Brew or MacPorts or whatever the flavor of the month is. And you don't even need to build git from scratch - just cd contrib/credential/osxkeychain/ and run make. – synthesizerpatel Apr 09 '13 at 14:04
  • is the osxkeychain only for `https` repos urls? or does it work also when using `ssh` repos urls + keys? – chovy Oct 29 '13 at 22:52
  • 3
    With two factor authentication you have to use what github calls a [Person Access Token](https://help.github.com/articles/creating-an-access-token-for-command-line-use). In fact you should always use one, as unlike a password you can control what access it gives. Just replace the password in the url so you end up with `https://username:PERSONAL_ACCESS_TOKEN@github.com/username/project.git`. It makes plain text passwords stored on disk almost safe enough to use. – Russell Stuart Apr 10 '14 at 10:18
  • @chovy The osxkeychain credential helper is unnecessary if you're using ssh. Instead, you can use [ssh-agent](https://help.github.com/articles/working-with-ssh-key-passphrases). If you're using a Linux desktop or OS X, the keyring should automatically pick up the ssh key passphrase for you (you may need to run `ssh-add`). Windows can use Pageant if you have PuTTY. If you're using Linux in a headless environment, there's a little more set up required, but you can easily find a guide on Google. – Dan Albert Apr 26 '14 at 08:48
  • @dazonic Would the password that is stored in my local .git directory be accessible by anyone else who clones from my github? In other words, would the password stored in plain text ever leave my machine? – laggingreflex Jun 30 '14 at 12:27
  • @laggingreflex if you're using credential helper, it's not stored in plain text in .git, it's stored in the OS's password keychain which is encrypted. It won't even leave your machine, no. – dazonic Jul 10 '14 at 06:05
  • @dazonic No I meant in plain text file (using `you:password@` URL)? When it's stored in my .git directory, and I push updates, and then someone else pulls it from remote, do they have the text file that has my password (`you:password@` URL)? – laggingreflex Jul 10 '14 at 08:36
  • 1
    @laggingreflex no. `.git/config` isn't pushed up. But it's still bad practice to store plain text passwords locally. – dazonic Jul 11 '14 at 06:50
  • 13
    `git config --global credential.helper cache` doesn't work on windows: http://stackoverflow.com/questions/11693074/git-credential-cache-is-not-a-git-command use [gitcredentialstore](http://gitcredentialstore.codeplex.com/) on Windows an be happy – Sebastian J. Jan 02 '15 at 15:35
  • 8
    Any way to set this timeout to infinity? – sudo Aug 10 '15 at 18:25
  • 2
    Maybe you can try a very big number, like 999999999 – Asped Sep 04 '15 at 09:03
  • 1
    'git config --global credential.helper store' does store the password. https://git-scm.com/docs/git-credential-store/1.7.12.1 – quadroid Oct 20 '15 at 12:19
  • Ubuntu users can try this [gnome-keyring-helper](http://stackoverflow.com/a/14528360/2636873) – crisron Dec 28 '15 at 01:41
  • 1
    "git config --global credential.helper wincred" worked fine for me under Windows 10. At the first time you have to enter the credentials, but 2nd, 3rd etc. it works as expected. – hfrmobile Aug 04 '16 at 09:00
  • Well... I just use the git cache (with timeout 999999999999) because it's just one command I can enter once without any moving parts. I've had a bad time trying to make SSH keys work in the past. – sudo Aug 11 '16 at 01:59
  • 1
    `git config --global credential.helper cache` didn't work for me on Ubuntu either. – Sergiy Ostrovsky Mar 03 '17 at 09:58
  • the level of complexity involved in these tools in 2017 is insane. This command-line stuff should have went out with the 1980's. Git config credential-manager=wincred??? wtf. and this .bash_history file in your user folder stores all the passwords you ever typed in bash in plaintext. insane. – Triynko Dec 15 '17 at 18:55
  • 1
    __Security Issue:__ the Windows credential manager stores your password in plaintext accessible to anybody logged in to your Windows account. All they need to do is send a request to the credential manager such as `printf "protocol=https\nhost=git.mycompany.com\n" | git credential-manager get` ([more details here](https://github.com/0cjs/sedoc/blob/master/git/win.md#credential-management)). You should always use a [personal access token](https://help.github.com/articles/creating-a-personal-access-token-for-the-command-line/) with this, and of course use 2FA on your GitHub account. – cjs Feb 20 '18 at 22:54
  • My version of git on macOS seems to support osxkeychain `git version 2.14.3 (Apple Git-98)` –  Mar 08 '18 at 04:50
  • 3
    @Triynko That's why you **don't** type passwords on the command line. Any decent command-line tool which handles passwords either _doesn't_ take them on the command line, or **strongly** discourages it. It's always recommended to provide credentials interactively. You run the command, it prompts `Password: `, and no other process sees what you enter. Anyone who uses passwords in shell commandlines deserves what they get. (Shows up in `ps` while the command is running, too.) But, those of us who don't freak out at the mere sight of a command prompt learned that way back in the 1990s. – FeRD Jul 10 '18 at 12:26
  • @sudo, to set the timeout to ~(Infinity) you should mess up with the Integer, set it to `-1` it should be in the *maximum value*. – tripulse Oct 13 '19 at 02:20
  • @nullptr I wouldn't rely on that unless it's documented behavior. Maybe your version of git does that, dunno if all of them do. – sudo Oct 13 '19 at 22:49
  • Well, time is always positive and never negative. So, `git` should be using a *Unsigned Integer* to store the timeout. For understanding purposes see this [example](http://ideone.com/Aj0r4R), it explains the trick. – tripulse Oct 14 '19 at 09:25
  • If timeout is set to the maximum positive value then it would last about `~138` years. Which might be a bit unrealistic. – tripulse Oct 19 '19 at 14:15
783

You can also have Git store your credentials permanently using git-credential-store as following:

git config credential.helper store

Note: While this is convenient, Git will store your credentials in clear text in a local file (.git-credentials) under your project directory (see below for the "home" directory). If you don't like this, delete this file and switch to using the cache option.

If you want Git to resume to asking you for credentials every time it needs to connect to the remote repository, you can run this command:

git config --unset credential.helper

To store the passwords in .git-credentials in your %HOME% directory as opposed to the project directory: use the --global flag

git config --global credential.helper store
Colonel Panic
  • 132,665
  • 89
  • 401
  • 465
Giri Alwar
  • 7,855
  • 1
  • 13
  • 2
  • 7
    On Windows, you can download a helper utility configures things to store an encrypted version of your GIT password in the Windows Creditial Store, see https://confluence.atlassian.com/display/STASH/Permanently+authenticating+with+Git+repositories – Contango Jan 22 '13 at 18:39
  • 80
    I found that I had to specify --global or it would try to store the settings in the current repository: `git config --global credential.helper store` – Rag May 15 '13 at 03:25
  • 6
    Why would do the cache instead of storing permanently? Sharing computers or something? – Michael J. Calkins Aug 24 '13 at 15:42
  • Hm "store permanently using the following" after what? I'm getting an error that it can't lock ".git/config". Who creates that file? – Victor Eijkhout May 16 '14 at 23:23
  • @VictorEijkhout - use the command from within the repository directory or use the global option as Brian Gordon suggested a couple of comments above. – StarNix May 19 '14 at 04:59
  • 1
    instead of storing maybe it would be better to just cache it at some long value for like a week or two, to figure out the maximum that it will allow use the largest values first, if you dont then you wont know if that value was accepted. I've successfully set the timeout to 99999 which is about 11 days, I'm not sure what the max is, but most programmers elect to align values on the byte (powers of 256) or metric boundary (powers of 10), metric is more likely for text-stored values. Use git config --global --get-all credential.helper to find out your current value(s). – osirisgothra Jun 20 '14 at 11:58
  • 3
    @BrianGordon I'm using GIT 1.9.5 on Windows, and `--global` flag was redundant. Even without this flag, the credentials file was created in `%USER_HOME%` directory. – jFrenetic Aug 18 '15 at 16:24
  • Fast forward to 2015, this should no longer recommended because the password is not encrypted. Please refer to this answer instead: http://stackoverflow.com/a/32470658/193634 – Rosdi Kasim Dec 23 '15 at 05:53
  • 2
    if not storing in plain text, what is it protected with? Your password? Wouldn't it then have to ask you for your admin password when you connect to git? Isn't having to enter a password to get another password a little strange? – Cruncher Mar 10 '16 at 15:35
  • 2
    Follow-up on @osirisgothra answer: Just set a very long timeout. `git config --global credential.helper "cache --timeout=9999999999"`. That worked for me and is 317 years. – socom1880 Apr 01 '16 at 22:52
117

TLDR; Use an encrypted netrc file with Git 1.8.3+.

Saving a password for a Git repository HTTPS URL is possible with a ~/.netrc (Unix) or %HOME%/_netrc (note the _) on Windows.

But: That file would store your password in plain text.

Solution: Encrypt that file with GPG (GNU Privacy Guard), and make Git decrypt it each time it needs a password (for push/pull/fetch/clone operation).


Note: with Git 2.18 (Q2 2018), you now can customize the GPG used to decrypt the encrypted .netrc file.

See commit 786ef50, commit f07eeed (12 May 2018) by Luis Marsano (``).
(Merged by Junio C Hamano -- gitster -- in commit 017b7c5, 30 May 2018)

git-credential-netrc: accept gpg option

git-credential-netrc was hardcoded to decrypt with 'gpg' regardless of the gpg.program option.
This is a problem on distributions like Debian that call modern GnuPG something else, like 'gpg2'


Step-by-Step instructions for Windows

With Windows:

(Git has a gpg.exe in its distribution, but using a full GPG installation includes a gpg-agent.exe, which will memorize your passphrase associated to your GPG key.)

  • Install gpg4Win Lite, the minimum gnupg command-line interface (take the most recent gpg4win-vanilla-2.X.Y-betaZZ.exe), and complete your PATH with the GPG installation directory:

      set PATH=%PATH%:C:\path\to\gpg
      copy C:\path\to\gpg\gpg2.exe C:\path\to\gpg\gpg.exe
    

(Note the 'copy' command: Git will need a Bash script to execute the command 'gpg'. Since gpg4win-vanilla-2 comes with gpg2.exe, you need to duplicate it.)

  • Create or import a GPG key, and trust it:

      gpgp --import aKey
      # or
      gpg --gen-key
    

(Make sure to put a passphrase to that key.)

  • Trust that key

  • Install the credential helper script in a directory within your %PATH%:

      cd c:\a\fodler\in\your\path
      curl -o c:\prgs\bin\git-credential-netrc https://raw.githubusercontent.com/git/git/master/contrib/credential/netrc/git-credential-netrc.perl
    

(Beware: the script is renamed in Git 2.25.x/2.26, see below)

(Yes, this is a Bash script, but it will work on Windows since it will be called by Git.)

  • Make a _netrc file in clear text

      machine a_server.corp.com
      login a_login
      password a_password
      protocol https
    
      machine a_server2.corp.com
      login a_login2
      password a_password2
      protocol https
    

(Don't forget the 'protocol' part: 'http' or 'https' depending on the URL you will use.)

  • Encrypt that file:

      gpg -e -r a_recipient _netrc
    

(You now can delete the _netrc file, keeping only the _netrc.gpg encrypted one.)

  • Use that encrypted file:

      git config --local credential.helper "netrc -f C:/path/to/_netrc.gpg -v"
    

(Note the '/': C:\path\to... wouldn't work at all.) (You can use at first -v -d to see what is going on.)

From now on, any Git command using an HTTP(S) URL which requires authentication will decrypt that _netrc.gpg file and use the login/password associated to the server you are contacting. The first time, GPG will ask you for the passphrase of your GPG key, to decrypt the file. The other times, the gpg-agent launched automatically by the first GPG call will provide that passphrase for you.

That way, you can memorize several URLs/logins/passwords in one file, and have it stored on your disk encrypted.
I find it more convenient than a "cache" helper", where you need to remember and type (once per session) a different password for each of your remote services, for said password to be cached in memory.


With Git 2.26 (Q1 2020), the sample credential helper for using .netrc has been updated to work out of the box. See patch/discussion.

See commit 6579d93, commit 1c78c78 (20 Dec 2019) by Denton Liu (Denton-L).
(Merged by Junio C Hamano -- gitster -- in commit 1fd27f8, 25 Dec 2019)

contrib/credential/netrc: make PERL_PATH configurable

Signed-off-by: Denton Liu

The shebang path for the Perl interpreter in git-credential-netrc was hardcoded.
However, some users may have it located at a different location and thus, would have had to manually edit the script.

Add a .perl prefix to the script to denote it as a template and ignore the generated version.
Augment the Makefile so that it generates git-credential-netrc from git-credential-netrc.perl, just like other Perl scripts.

The Makefile recipes were shamelessly stolen from contrib/mw-to-git/Makefile.

And:

With 2.26 (Q1 2020), Sample credential helper for using .netrc has been updated to work out of the box.

See commit 6579d93, commit 1c78c78 (20 Dec 2019) by Denton Liu (Denton-L).
(Merged by Junio C Hamano -- gitster -- in commit 1fd27f8, 25 Dec 2019)

contrib/credential/netrc: work outside a repo

Signed-off-by: Denton Liu

Currently, git-credential-netrc does not work outside of a git repository. It fails with the following error:

fatal: Not a git repository: . at /usr/share/perl5/Git.pm line 214.

There is no real reason why need to be within a repository, though. Credential helpers should be able to work just fine outside the repository as well.

Call the non-self version of config() so that git-credential-netrc no longer needs to be run within a repository.

Jeff King (peff) adds:

I assume you're using a gpg-encrypted netrc (if not, you should probably just use credential-store).
For "read-only" password access, I find the combination of pass with config like this is a bit nicer:

[credential "https://github.com"]
username = peff
helper = "!f() { test $1 = get && echo password=`pass github/oauth`; }; f"

The 2013 "fatal: Not a git repository" error message with Git.pm is... fixed with Git 2.39 (Q4 2022):

See commit 20da61f (22 Oct 2022) by Jeff King (peff).
See commit 77a1310 (16 Oct 2022) by Michael McClimon (mmcclimon).
(Merged by Junio C Hamano -- gitster -- in commit 330135a, 28 Oct 2022)

Git.pm: trust rev-parse to find bare repositories

Signed-off-by: Jeff King

When initializing a repository object, we run "git rev-parse --git-dir"(man) to let the C version of Git find the correct directory.
But curiously, if this fails we don't automatically say "not a git repository".
Instead, we do our own pure-Perl check to see if we're in a bare repository.

This makes little sense, as rev-parse will report both bare and non-bare directories.
This logic comes from d5c7721 ("Git.pm: Add support for subdirectories inside of working copies", 2006-06-24, Git v1.4.3-rc1 -- merge), but I don't see any reason given why we can't just rely on rev-parse.
Worse, because we treat any non-error response from rev-parse as a non-bare repository, we'll erroneously set the object's WorkingCopy, even in a bare repository.

But it gets worse.
Since 8959555 (setup_git_directory(): add an owner check for the top-level directory, 2022-03-02, Git v2.36.0-rc2 -- merge) (setup_git_directory(): add an owner check for the top-level directory, 2022-03-02), it's actively wrong (and dangerous).
The Perl code doesn't implement the same ownership checks.
And worse, after "finding" the bare repository, it sets GIT_DIR in the environment, which tells any subsequent Git commands that we've confirmed the directory is OK, and to trust us.
I.e., it re-opens the vulnerability plugged by 8959555 when using Git.pm's repository discovery code.

We can fix this by just relying on rev-parse to tell us when we're not in a repository, which fixes the vulnerability.
Furthermore, we'll ask its --is-bare-repository function to tell us if we're bare or not, and rely on that.

VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
  • 1
    trying the same thing on linux .. git config --local credential.helper "netrc -f /home/me/.netrc.gpg -v -d" ..and i get "git : 'credential-netrc' is not a git command. see 'git --help'" – sunny Dec 21 '13 at 03:26
  • 4
    @sunny That is what the `curl -o c:\prgs\bin\git-credential-netrc https://raw.github.com/git/git/master/contrib/credential/netrc/git-credential-netrc` is for: you need to copy the `git-credential-netrc` anywhere in your path (`$PATH`), in order for git to be able to call '`credential-netrc`'. – VonC Dec 22 '13 at 00:14
  • Well, the `_netrc` didn't work for me on a `Windows 7` PC, but the `.netrc` worked for [youtube-dl](https://github.com/rg3/youtube-dl) with the `--netrc` argument passed to it. – Iulian Onofrei Apr 12 '15 at 23:02
  • @VonC the current URL seems to be `https://raw.githubusercontent.com/git/git/master/contrib/credential/netrc/git-credential-netrc.perl` (piping in seven years later ) – Gwyneth Llewelyn Mar 25 '20 at 22:50
  • 1
    @GwynethLlewelyn Thank you. I have edited the answer accordingly. Don't hesitate to edit it yourself if you see any other obsolete information. – VonC Mar 26 '20 at 05:06
  • @VonC all looks great to me — awesome update on the original answer, BTW! Well done :-) – Gwyneth Llewelyn May 02 '20 at 20:29
  • Can you add how to do it on linux? Beacuse it not clear at all what you are doing here. – aldokkani Sep 30 '20 at 16:43
  • @aldokkani Sorry for the delay, I was at work. This old (2013) answer was for Windows, at a time it did not benefit from a good credential helper (like the ones for Linux). I would not use it today, where GCM4W exists: https://github.com/microsoft/Git-Credential-Manager-for-Windows. I have edited Mark Longair's answer to add Linux updated credential helpers: https://stackoverflow.com/posts/5343146/revisions – VonC Sep 30 '20 at 20:08
52

Use a credential store.

For Git 2.11+ on OS X and Linux, use Git's built in credential store:

git config --global credential.helper libsecret

For msysgit 1.7.9+ on Windows:

git config --global credential.helper wincred

For Git 1.7.9+ on OS X use:

git config --global credential.helper osxkeychain
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
actual_kangaroo
  • 5,971
  • 2
  • 31
  • 45
  • 3
    I'm sure that this is the way to go, but I get an error sadly: `git: 'credential-gnome-keyring' is not a git command. See 'git --help'.` – codepleb Feb 12 '17 at 10:43
  • 1
    @TrudleR I updated my answer to recomend upgrading git to `2.11` and then using `git config --global credential.helper libsecret` it appears that gnome-keyring is deprecated https://stackoverflow.com/questions/13385690/how-to-use-git-with-gnome-keyring-integration – actual_kangaroo Feb 13 '17 at 12:13
  • 1
    Thanks, but I get the same error somehow. Am I doing something wrong? I type the command and nothing happens. As soon as I push, I'm asked for the credentials, which I successfully insert, but I get the error, that it is not a git command after doing that. – codepleb Feb 14 '17 at 21:56
  • 3
    Before libsecret will work on Linux, you need to do these steps: http://stackoverflow.com/a/40312117/775800 – Lavamantis May 02 '17 at 21:52
  • 1
    One other thing - if you have 2FA enabled on Github, your password won't work. But you can create a personal access token on your Github "Settings" page and that token works as your password. https://github.com/github/hub/issues/822 – Lavamantis May 02 '17 at 22:05
  • 3
    __Security Issue:__ the Windows credential manager makes your plaintext password accessible to anybody logged in to your Windows account. All they need to do is send a request to the credential manager such as `printf "protocol=https\nhost=git.mycompany.com\n" | git credential-manager get` ([more details here](https://github.com/0cjs/sedoc/blob/master/git/win.md#credential-management)). You should always use a [personal access token](https://help.github.com/articles/creating-a-personal-access-token-for-the-command-line/) with this, and of course use 2FA on your GitHub account. – cjs Feb 20 '18 at 22:58
  • 1
    Simple but great answer! This worked for me out of the box on openSUSE 13.2, even though it seems to be a fairly old installation. – cchwala Nov 23 '20 at 19:29
  • If somebody is curious about the difference between the different **credential stores** here, consider [this answer](https://stackoverflow.com/a/62184716/4575793). It also explained that "You can also use `store` to store in a file on your local disk, which is available on all platforms, but less secure." Also, the [CredentialManager](https://github.com/GitCredentialManager/git-credential-manager#macos-homebrew) is available for both MacOS and Linux now. – Cadoiz Oct 10 '22 at 07:51
45

There's an easy, old-fashioned way to store user credentials in an HTTPS URL:

https://user:password@github.com/...

You can change the URL with git remote set-url <remote-repo> <URL>

The obvious downside to that approach is that you have to store the password in plain text. You can still just enter the user name (https://user@github.com/...) which will at least save you half the hassle.

You might prefer to switch to SSH or to use the GitHub client software.

wortwart
  • 3,139
  • 27
  • 31
  • 2
    The username/password might need to be encoded, see https://stackoverflow.com/a/34611311/3906760 – MrTux Jan 05 '16 at 12:26
43

You can just use

git config credential.helper store

When you enter password next time with pull or push, it will be stored in file .git-credentials as plain text (a bit unsecure, but just put it into a protected folder).

And that's it, as stated on this page:

git-credential-store

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
sgoran
  • 826
  • 8
  • 13
  • 3
    For Git for Windows 2.7.3 (March 2016): https://github.com/git-for-windows/git/releases?after=v2.8.4.windows.1, that would be `git config credential.helper manager` instead – VonC Sep 21 '16 at 14:46
23

It wasn't immediately obvious to me that I needed to download the helper first! I found the credential.helper download at Atlassian's Permanently authenticating with Git repositories.

Quote:

Follow these steps if you want to use Git with credential caching on OS X:

Download the binary git-credential-osxkeychain.

Run the command below to ensure the binary is executable:

chmod a+x git-credential-osxkeychain

Put it in the directory /usr/local/bin.

Run the command below:

git config --global credential.helper osxkeychain
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ben
  • 1,292
  • 1
  • 13
  • 21
23

Simply include the login credentials as part of the URL:

git remote rm origin
git remote add origin https://username:mypassword@github.com/path/to/repo.git

Note: I do not recommend this method, but if you are in rush and nothing else works, you can use this method.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Tarun Gupta
  • 6,305
  • 2
  • 42
  • 39
22

On a GNU/Linux setup, a ~/.netrc works quite well too:

$ cat ~/.netrc
machine github.com login lot105 password howsyafather

It might depend on which network libraries Git is using for HTTPS transport.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
helloPiers
  • 658
  • 7
  • 13
  • 4
    Make sure to also `chmod 0600 ~/.netrc`. – poolie May 31 '13 at 03:58
  • Just want to leave a link here to the [Ubuntu netrc manpage](http://manpages.ubuntu.com/manpages/jaunty/man5/netrc.5.html). I needed to create it for another user (/home/git/.netrc) then change ownership to that user. – zacharydl Jan 14 '15 at 07:28
16

You can use the Git Credential Manager (GCM) plugin. It is currently maintained by GitHub. The nice thing is that it saves the password in the Windows Credential Store, not as plain text.

There is an installer on the releases page of the project. This will also install the official version of Git for Windows with the credential manager built-in. It allows two-factor authentication for GitHub (and other servers). And has a graphical interface for initially logging in.

For Cygwin users (or users already using the official Git for Windows), you might prefer the manual install. Download the zip package from the releases page. Extract the package, and then run the install.cmd file. This will install to your ~/bin folder. (Be sure your ~/bin directory is in your PATH.) You then configure it using this command:

git config --global credential.helper manager

Git will then run the git-credential-manager.exe when authenticating to any server.

Colonel Panic
  • 132,665
  • 89
  • 401
  • 465
Nadeem Khedr
  • 5,273
  • 3
  • 30
  • 37
  • 3
    Anybody logged into your account does have easy access to the plaintext of the password. All they need to do is send a request to the credential manager such as `printf "protocol=https\nhost=git.mycompany.com\n" | git credential-manager get` ([more details here](https://github.com/0cjs/sedoc/blob/master/git/win.md#credential-management)). You should always use a [personal access token](https://help.github.com/articles/creating-a-personal-access-token-for-the-command-line/) with this, and of course use 2FA on your GitHub account. – cjs Feb 20 '18 at 22:59
14

OAuth

You can create your own personal API token (OAuth) and use it the same way as you would use your normal credentials (at: /settings/tokens). For example:

git remote add fork https://4UTHT0KEN@github.com/foo/bar
git push fork

.netrc

Another method is to configure your user/password in ~/.netrc (_netrc on Windows), e.g.

machine github.com
login USERNAME
password PASSWORD

For HTTPS, add the extra line:

protocol https

A credential helper

To cache your GitHub password in Git when using HTTPS, you can use a credential helper to tell Git to remember your GitHub username and password every time it talks to GitHub.

  • Mac: git config --global credential.helper osxkeychain (osxkeychain helper is required),
  • Windows: git config --global credential.helper wincred
  • Linux and other: git config --global credential.helper cache

Related:

kenorb
  • 155,785
  • 88
  • 678
  • 743
14

If you don't want to store your password in plaintext like Mark said, you can use a different GitHub URL for fetching than you do for pushing. In your configuration file, under [remote "origin"]:

url = git://github.com/you/projectName.git
pushurl = git@github.com:you/projectName.git

It will still ask for a password when you push, but not when you fetch, at least for open source projects.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Tyler
  • 21,762
  • 11
  • 61
  • 90
11

You can use credential helpers.

git config --global credential.helper 'cache --timeout=x'

where x is the number of seconds.

Charan
  • 479
  • 4
  • 5
  • 9
    It is number of seconds ... Some genius updated it as milliseconds and everyone approved it without checking. Please don't mislead people if you don't know the answer. Thanks! – Charan Sep 09 '14 at 15:59
  • Can you give a link to a place where `store`, `cache` and other common things are listed and explained? – Notinlist Nov 20 '14 at 10:10
  • 5
    Care to mention the fact that this does jack shit unless you call another specific command to use the 'cache' as the manager first? This stuff is so cryptic, all of these answers are incomplete, and none of them work. Incredibly frustrating. See this instead: https://stackoverflow.com/a/24800870/88409 – Triynko Nov 21 '17 at 19:45
11

After you clone repository repo, you can edit repo/.git/config and add some configuration like below:

[user]
    name = you_name
    password = you_password
[credential]
    helper = store

Then you won't be asked for username and password again.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Xiaorong Liao
  • 1,201
  • 14
  • 14
8

I know this is not a secure solution, but sometimes you need just a simple solution - without installing anything else. And since helper = store did not work for me, I created a dummy helper:

Create a script and put it in your users bin folder, here named credfake, this script will provide your username and your password:

#!/bin/bash
while read line
do
  echo "$line"
done < "/dev/stdin"
echo username=mahuser
echo password=MahSecret12345

make it executable:

chmod u+x /home/mahuser/bin/credfake

then configure it in git:

git config --global credential.helper /home/mahuser/bin/credfake

(or use it without --global for the one repo only)

and - voilá - git will use this user + password.

bebbo
  • 2,830
  • 1
  • 32
  • 37
  • I agree. Simple (if unsecure) solution indeed. +1, as long as you know what you are doing. – VonC May 27 '17 at 16:56
6

An authentication token should be used instead of the account password. Go to GitHub settings/applications and then create a personal access token. The token can be used the same way a password is used.

The token is intended to allow users not use the account password for project work. Only use the password when doing administration work, like creating new tokens or revoke old tokens.


Instead of a token or password that grants a user whole access to a GitHub account, a project specific deployment key can be used to grant access to a single project repository. A Git project can be configured to use this different key in the following steps when you still can access other Git accounts or projects with your normal credential:

  1. Write an SSH configuration file that contains the Host, IdentityFile for the deployment key, maybe the UserKnownHostsFile, and maybe the User (though I think you don't need it).
  2. Write an SSH wrapper shell script that virtually is ssh -F /path/to/your/config $*
  3. Prepend GIT_SSH=/path/to/your/wrapper in front of your normal Git command. Here the git remote (origin) must use the git@github.com:user/project.git format.
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
minghua
  • 5,981
  • 6
  • 45
  • 71
6

It is better to use credentials for security, but you can keep it for some time using the cache:

git config --global credential.helper cache
git config credential.helper 'cache --timeout=3600'

Your credentials will be saved for 3600 seconds.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Sarvar Nishonboyev
  • 12,262
  • 10
  • 69
  • 70
  • 1
    It means after 3600 seconds , we have to input password again ??? How to save them permanently ? – Bulma Aug 27 '15 at 09:00
  • $ git config credential.helper 'cache --timeout=3600' error: could not lock config file .git/config: No such file or directory – PlantationGator Oct 21 '15 at 17:41
  • This worked: git config --global credential.helper 'cache --timeout=3600' – PlantationGator Oct 21 '15 at 17:43
  • Will this work inside a Docker container (based on `windowsservercore`)? – Peter Mortensen Sep 30 '18 at 09:19
  • 1
    @NeilChowdhury that is not true. According to the official [doc](https://docs.github.com/en/github/using-git/caching-your-github-credentials-in-git#platform-linux), by default, the password will be kept for 15 min. Do not spread ungrounded words like this! – jdhao Sep 25 '20 at 13:16
6

Usually you have a remote URL, something like this,

git remote -v

origin    https://gitlab.com/username/Repo.git (fetch)
origin    https://gitlab.com/username/Repo.git (push)

If you want to skip username and password while using git push, try this:

 git remote set-url origin https://username:password@gitlab.com/username/Repo.git

I've just added the same URL (with user details including password) to origin.

NOTE: It doesn't work if username is an email Id.

git remote -v

origin    https://username:password@gitlab.com/username/Repo.git (fetch)
origin    https://username:password@gitlab.com/username/Repo.git (push)
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Nayagam
  • 1,767
  • 18
  • 12
4

Things are a little different if you're using two-factor authentication as I am. Since I didn't find a good answer elsewhere, I'll stick one here so that maybe I can find it later.

If you're using two-factor authentication, then specifying username/password won't even work - you get access denied. But you can use an application access token and use Git's credential helper to cache that for you. Here are the pertinent links:

And I don't remember where I saw this, but when you're asked for your username - that's where you stick the application access token. Then leave the password blank. It worked on my Mac.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
JnBrymn
  • 24,245
  • 28
  • 105
  • 147
4

As of 2021, there is a secure user-friendly cross-platform solution for HTTPS remotes. No more typing passwords! No more SSH keys! No more personal access tokens!

Install Git Credential Manager developed by GitHub (downloads). It supports passwordless OAuth authentication to GitHub, BitBucket, Azure and GitLab. This means you can enable two-factor authentication on GitHub and the other platforms, greatly improving the security of your accounts.

When you push, you are offered a choice of authentication methods:

> git push
Select an authentication method for 'https://github.com/':
  1. Web browser (default)
  2. Device code
  3. Personal access token
option (enter for default): 1
info: please complete authentication in your browser...

On Linux, a tiny bit of setup is required. The following caches credentials in memory for 20 hours, so you have to authenticate at most once per day.

git-credential-manager-core configure
git config --global credential.credentialStore cache
git config --global credential.cacheoptions=--timeout 72000

Power users familiar with gnome-keyring or KWallet may prefer to change the credential store to libsecret.

Cosmetic configuration: Since I always choose 'web browser' at the prompt above, I set a gitHubAuthModes preference to skip the choice. Recent versions of GCM include a GUI that adds an extra click to the authtentication flow, I disable that.

git config --global credential.gitHubAuthModes browser
git config --global credential.guiPrompt false
Colonel Panic
  • 132,665
  • 89
  • 401
  • 465
3

This works for me I'm using Windows 10

git config --global credential.helper wincred
Mostafa Nawara
  • 782
  • 9
  • 21
3

You also edit the bashrc file and add a script in it.

This would ask for your password once when you start Git and then remembers it until you log off.

SSH_ENV=$HOME/.ssh/environment
  
# Start the ssh-agent
function start_agent {
    echo "Initializing new SSH agent..."

    # Spawn ssh-agent
    /usr/bin/ssh-agent | sed 's/^echo/#echo/' > "${SSH_ENV}"
    echo succeeded
    chmod 600 "${SSH_ENV}"
    . "${SSH_ENV}" > /dev/null
    /usr/bin/ssh-add
}
  
if [ -f "${SSH_ENV}" ]; then
     . "${SSH_ENV}" > /dev/null
   ps -ef | grep ${SSH_AGENT_PID} | grep ssh-agent$ > /dev/null || {
      start_agent;
  }
else
    start_agent;
fi
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ThePatelGuy
  • 1,844
  • 1
  • 19
  • 18
2

I got my answer from gitcredentials(7) Manual Page. For my case, I don't have credential-cache in my Windows installation; I use credential-store.

After I use credential-store, the username/password are stored in [user folder]/.git-credentials file. To remove the username/password, just delete the content of the file.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mike
  • 57
  • 1
  • 5
  • 2
    When you don't have credential-cache in your windows, I would suggest to use `git config --global credential.helper wincred` this store the password permanently. – eQ19 Apr 03 '16 at 09:45
1

The composer documentation mentions that you can prevent it from using the GitHub API, so that it acts like git clone:

If you set the no-api key to true on a GitHub repository it will clone the repository as it would with any other Git repository instead of using the GitHub API. But unlike using the git driver directly, composer will still attempt to use GitHub's zip files.

So the section would look like this:

"repositories": [
    {
        "type": "vcs",
        "no-api": true,
        "url": "https://github.com/your/repo"
    }
],

Keep in mind that the API is there for a reason. So it this should be a method of last resort regarding the increased load on github.com.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
sebastianwagner
  • 399
  • 2
  • 9
1

Caching credentials locally using Git Credential Manager (GCM) on Ubuntu, tested on Ubuntu 20.04 and 18.04, but should work on other Linux distros.

  1. Set up git credential manager:
curl -LO https://raw.githubusercontent.com/GitCredentialManager/git-credential-manager/main/src/linux/Packaging.Linux/install-from-source.sh
sh ./install-from-source.sh
git-credential-manager-core configure
git config --global credential.credentialStore cache
git config --global credential.cacheoptions "--timeout 72000"
sudo rm -rf git-credential-manager/
sudo rm install-from-source.sh
  1. Go to a repo and run git fetch
  2. Select Device code
  3. Visit the link and enter the code provided in the output
aleksk
  • 661
  • 7
  • 15
0

I also had that problem on MacOS, and the following command worked for me:

rm -rf  ~/.git-credentials 

That is a forced method to really remove all git credentials. And next time I used the push command, voilà: I am prompted for a username and password (or token).

Alex
  • 41,580
  • 88
  • 260
  • 469
0

Two-factor authentication has changed how users authenticate to websites, but Git still assumes users can type a password from memory.

Introducing git-credential-oauth: a Git credential helper that securely authenticates to GitHub, GitLab, BitBucket and other forges using OAuth.

No more passwords! No more personal access tokens! No more SSH keys!

The first time you push, the helper will open a browser window to authenticate. Subsequent pushes within the cache timeout require no interaction.

Install from https://github.com/hickford/git-credential-oauth/releases/

Configure with:

git config --global --unset-all credential.helper
git config --global --add credential.helper "cache --timeout 7200" # two hours
git config --global --add credential.helper oauth
Colonel Panic
  • 132,665
  • 89
  • 401
  • 465
-1

If you are using osxkeychain and had a token expire and want to update it, follow these steps:

Run in terminal, then press enter twice.

git credential-osxkeychain erase
 host=github.com
 protocol=https

Now you should be prompted for a username/password. However sometimes it seems this does not 'take' and you have to keep re-entering.

If so, restart your computer. Now the next time you run a git command and enter your username/password, it will be saved.

Andrew Schreiber
  • 14,344
  • 6
  • 46
  • 53