[git] How to save username and password in Git?

I want to use a push and pull automatically in GitExtension, without entering my user and password in a prompt, every time.

So how can I save my credentials in git?

This question is related to git credentials git-config git-extensions

The answer is


After reading the thread in full and experimenting with most of the answers to this question, I eventually found the procedure that works for me. I want to share it in case someone has to deal with a complex use case but still do not want to go through the full thread and the gitcredentials, gitcredentials-store etc. man pages, as I did.

Find below the procedure I suggest IF you (like me) have to deal with several repositories from several providers (GitLab, GitHub, Bitbucket, etc.) using several different username / password combinations. If you instead have only a single account to work with, then you might be better off employing the git config --global credential.helper store or git config --global user.name "your username" etc. solutions that have been very well explained in previous answers.

My solution:

  1. unset global credentials helper, in case some former experimentation gets in the way :)

> git config --global --unset credentials.helper

  1. move to the root directory of your repo and disable the local credential helper (if needed)

> cd /path/to/my/repo

> git config --unset credential.helper

  1. create a file to store your repo's credentials into

> git config credential.helper 'store --file ~/.git_repo_credentials'

Note: this command creates a new file named ".git_repo_credentials" into your home directory, to which Git stores your credentials. If you do not specify a file name, Git uses the default ".git_credentials". In this case simply issuing the following command will do:

> git config credential.helper store

  1. set your username

git config credential.*.username my_user_name

Note: using "*" is usually ok if your repositories are from the same provider (e.g. GitLab). If instead your repositories are hosted by different providers then I suggest to explicitly set the link to the provider for every repository, like in the following example (for GitLab):

git config credential.https://gitlab.com.username my_user_name

At this point if you issue a command requiring your credentials (e.g. git pull) you will be asked for the password corresponding to "my_user_name". This is only required once because git stores the credentials to ".git_repo_credentials" and automatically uses the same data at subsequent accesses.


For global setting, open the terminal (from any where) run the following:

  git config --global user.name "your username"
  git config --global user.password "your password"

By that, any local git repo that you have on your machine will use that information.

You can individually config for each repo by doing:

  • open terminal at the repo folder.
  • run the following:

    git config user.name "your username"
    git config user.password "your password"
    

It affects only that folder (because your configuration is local).


Store username and password in .git-credentials

.git-credentials is where your username and password(access token) is stored when you run git config --global credential.helper store, which is what other answers suggest, and then type in your username and password or access token:

https://${username_or_access_token}:${password_or_access_token}@github.com

So, in order to save the username and password(access token):

git config —-global credential.helper store
echo “https://${username}:${password_or_access_token}@github.com“ > ~/.git-credentials

This is very useful for github robot, e.g. to solve Chain automated builds in the same docker repository by having rules for different branch and then trigger it by pushing to it in post_push hooker in docker hub.

An example of this can be seen here in stackoverflow.


Check official git documentation:

If you use the SSH transport for connecting to remotes, it’s possible for you to have a key without a passphrase, which allows you to securely transfer data without typing in your username and password. However, this isn’t possible with the HTTP protocols – every connection needs a username and password. This gets even harder for systems with two-factor authentication, where the token you use for a password is randomly generated and unpronounceable.

Fortunately, Git has a credentials system that can help with this. Git has a few options provided in the box:

  • The default is not to cache at all. Every connection will prompt you for your username and password.

  • The “cache” mode keeps credentials in memory for a certain period of time. None of the passwords are ever stored on disk, and they are purged from the cache after 15 minutes.

  • The “store” mode saves the credentials to a plain-text file on disk, and they never expire. This means that until you change your password for the Git host, you won’t ever have to type in your credentials again. The downside of this approach is that your passwords are stored in cleartext in a plain file in your home directory.

  • If you’re using a Mac, Git comes with an “osxkeychain” mode, which caches credentials in the secure keychain that’s attached to your system account. This method stores the credentials on disk, and they never expire, but they’re encrypted with the same system that stores HTTPS certificates and Safari auto-fills.

  • If you’re using Windows, you can install a helper called “Git Credential Manager for Windows.” This is similar to the “osxkeychain” helper described above, but uses the Windows Credential Store to control sensitive information. It can be found at https://github.com/Microsoft/Git-Credential-Manager-for-Windows.

You can choose one of these methods by setting a Git configuration value:

$ git config --global credential.helper cache

$ git config --global credential.helper store

https://git-scm.com/book/en/v2/Git-Tools-Credential-Storage


I think it's safer to cache credentials, instead of store forever:

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

now you can enter your username and password(git pull or ...), and keep using git for next 3 hours.

nice and safe.

Timeout is in seconds(3 hours in the example).


Recommended and Secure Method: SSH

Create an ssh Github key. Go to github.com -> Settings -> SSH and GPG keys -> New SSH Key. Now save your private key to your computer.

Then, if the private key is saved as id_rsa in the ~/.ssh/ directory, we add it for authentication as such:

ssh-add -K ~/.ssh/id_rsa


A More Secure Method: Caching

We can use git-credential-store to cache our username and password for a time period. Simply enter the following in your CLI (terminal or command prompt):

git config --global credential.helper cache

You can also set the timeout period (in seconds) as such:

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


An Even Less Secure Method

Git-credential-store may also be used, but saves passwords in plain text file on your disk as such:

git config credential.helper store


Outdated Answer - Quick and Insecure

This is an insecure method of storing your password in plain text. If someone gains control of your computer, your password will be exposed!

You can set your username and password like this:

git config --global user.name "your username"

git config --global user.password "your password"

In that case you need git credential helper to tell git to remember your GitHub password and username by using following command line :

git config --global credential.helper wincred 

and if you are using repo using SSH key then you need SSH key to authenticate.


You can use the git config to enable credentials storage in git.

git config --global credential.helper store

When running this command, the first time you pull or push from the remote repository, you'll get asked about the username and password.

Afterwards, for consequent communications with the remote repository you don't have to provide the username and password.

The storage format is a .git-credentials file, stored in plaintext.

Also, you can use other helpers for the git config credential.helper, namely memory cache:

git config credential.helper cache <timeout>

which takes an optional timeout parameter, determining for how long the credentials will be kept in memory. Using the helper, the credentials will never touch the disk and will be erased after the specified timeout. The default value is 900 seconds (15 minutes).


WARNING : If you use this method, your git account passwords will be saved in plaintext format, in the global .gitconfig file, e.g in linux it will be /home/[username]/.gitconfig

If this is undesirable to you, use an ssh key for your accounts instead.


Just put your credentials in the Url like this:

https://Username:Password@github.com/myRepoDir/myRepo.git

You may store it like this:

git remote add myrepo https://Userna...

...example to use it:

git push myrepo master


Now that is to List the url aliases:

git remote -v

...and that the command to delete one of them:

git remote rm myrepo


For windows users look at the .gitconfig file and check what has been configured for the credential helper if you have the following...

[credential "helperselector"] selected = wincred

you'll find the credentials in the Windows Credential Manager.

enter image description here

There you can edit the credential.

EDIT: Wincred has been deprecated, see...

https://github.com/git-for-windows/git-sdk-64/tree/main/mingw64/doc/git-credential-manager

So alternatively you may want to reconfigure git to use the built-in GIT credential manager...

git config --global credential.helper manager

Turn on the credential helper so that Git will save your password in memory for some time:

In Terminal, enter the following:

# Set git to use the credential memory cache
git config --global credential.helper cache

By default, Git will cache your password for 15 minutes.

To change the default password cache timeout, enter the following:

# Set the cache to timeout after 1 hour (setting is in seconds)
git config --global credential.helper 'cache --timeout=3600'

From GitHub Help


You can use git-credential-store to store your passwords unencrypted on the disk, protected only by the permissions of the file system.

Example

$ git config credential.helper store
$ git push http://example.com/repo.git
Username: <type your username>
Password: <type your password>

[several days later]
$ git push http://example.com/repo.git
[your credentials are used automatically]

You can check the credentials stored in the file ~/.git-credentials

For more info visit git-credential-store - Helper to store credentials on disk


If you are using the Git Credential Manager on Windows...

git config -l should show:

credential.helper=manager

However, if you are not getting prompted for a credential then follow these steps:

  1. Open Control Panel from the Start menu
  2. Select User Accounts
  3. Select Manage your credentials in the left hand menu
  4. Delete any credentials related to Git or GitHub

Also ensure you have not set HTTP_PROXY, HTTPS_PROXY, NO_PROXY environmental variables if you have proxy and your Git server is on the internal network.

You can also test Git fetch/push/pull using git-gui which links to credential manager binaries in C:\Users\<username>\AppData\Local\Programs\Git\mingw64\libexec\git-core


Apart from editing the ~/.gitconfig file, that you can do if you ask:

git config --local --edit

or

git config --global --edit

Note to always use single quotes:

git config --local user.name 'your username'
git config --local user.password 'your password'

or

git config --global user.name 'your username'
git config --global user.password 'your password'

Your username and password may use some characters that would break your password if you use double quotes.

--local or --global means configuration params are saved for the project or for the os user.


You will be more secure if you use SSH authentication than username/password authentication.

If you are using a Mac, SSH client authentication is integrated into the MacOS keychain. Once you have created an SSH key, type into your terminal:

ssh-add -K ~/.ssh/id_rsa

This will add the SSH private key to the MacOS keychain. The git client will use ssh when it connects to the remote server. As long as you have registered your ssh public key with the server, you will be fine.


None of the answers above worked for me. I kept getting the following every time I wanted to fetch or pull:

Enter passphrase for key '/Users/myusername/.ssh/id_rsa':


For Macs

I was able to stop it from asking my passphrase by:

  1. Open config by running: vi ~/.ssh/config
  2. Added the following: UseKeychain yes
  3. Saved and quit: Press Esc, then enter :wq!

For Windows

I was able to get it to work using the info in this stackexchange: https://unix.stackexchange.com/a/12201/348665


just use

git config --global credential.helper store

and do the git pull, it will ask for username and password, from now on it will not provide any prompt for username and password it will store the details


After going over dozens of SO posts, blogs, etc, I tried out every method, and this is what I came up with. It covers EVERYTHING.

The Vanilla DevOps Git Credentials & Private Packages Cheatsheet

These are all the ways and tools by which you can securely authenticate git to clone a repository without an interactive password prompt.

  • SSH Public Keys
    • SSH_ASKPASS
  • API Access Tokens
    • GIT_ASKPASS
    • .gitconfig insteadOf
    • .gitconfig [credential]
    • .git-credentials
    • .netrc
  • Private Packages (for Free)
    • node / npm package.json
    • python / pip / eggs requirements.txt
    • ruby gems Gemfile
    • golang go.mod

The Silver Bullet

Want Just Works™? This is the magic silver bullet.

Get your Access Token (see the section in the cheatsheet if you need the Github or Gitea instructions for that) and set it in an environment variable (both for local dev and deployment):

MY_GIT_TOKEN=xxxxxxxxxxxxxxxx

For Github, copy and run these lines verbatim:

git config --global url."https://api:[email protected]/".insteadOf "https://github.com/"
git config --global url."https://ssh:[email protected]/".insteadOf "ssh://[email protected]/"
git config --global url."https://git:[email protected]/".insteadOf "[email protected]:"

Congrats, now any automated tool cloning git repositories won't be obstructed by a password prompt, whether using https or either style of ssh url.

Not using Github?

For other platforms (Gitea, Github, Bitbucket), just change the URL. Don't change the usernames (although arbitrary, they're needed for distinct config entries).

Compatibility

This works locally in MacOS, Linux, Windows (in Bash), Docker, CircleCI, Heroku, Akkeris, etc.

More Info

See the ".gitconfig insteadOf" section of the cheatsheet.

Security

See the "Security" section of the cheatsheet.


You can edit the ~/.gitconfig file to store your credentials

sudo nano ~/.gitconfig

Which should already have

[user]
        email = [email protected]
        user = gitUSER

You should add at the bottom of this file.

[credential]
        helper = store

The reason I recommend this option is cause it is global and if at any point you need to remove the option you know where to go and change it.

ONLY USE THIS OPTION IN YOU PERSONAL COMPUTER.

Then when you pull | clone| enter you git password, in general, the password will be saved in ~/.git-credentials in the format

https://GITUSER:[email protected]

WHERE DOMAIN.XXX COULD BE GITHUB.COM | BITBUCKET.ORG | OTHER

See Docs

Restart your terminal.


From the comment by rifrol, on Linux Ubuntu, from this answer, here's how in 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

Some other distro's provide the binary so you don't have to build it.

In OS X it typically comes "built" with a default module of "osxkeychain" so you get it for free.


Examples related to git

Does the target directory for a git clone have to match the repo name? Git fatal: protocol 'https' is not supported Git is not working after macOS Update (xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools) git clone: Authentication failed for <URL> destination path already exists and is not an empty directory SSL_connect: SSL_ERROR_SYSCALL in connection to github.com:443 GitLab remote: HTTP Basic: Access denied and fatal Authentication How can I switch to another branch in git? VS 2017 Git Local Commit DB.lock error on every commit How to remove an unpushed outgoing commit in Visual Studio?

Examples related to credentials

git clone: Authentication failed for <URL> How to save username and password in Git? AWS : The config profile (MyName) could not be found Remove credentials from Git Configuring user and password with Git Bash SVN change username HttpWebRequest using Basic authentication Using cURL with a username and password? How do I find my host and username on mysql? How to Specify Eclipse Proxy Authentication Credentials?

Examples related to git-config

How to know the git username and email saved during configuration? How to save username and password in Git? git: fatal unable to auto-detect email address How to change my Git username in terminal? How do I commit case-sensitive only filename changes in Git? Unable to auto-detect email address git: 'credential-cache' is not a git command Is it possible to have different Git configuration for different projects? How to tell git to use the correct identity (name and email) for a given project? Is there a way to cache GitHub credentials for pushing commits?

Examples related to git-extensions

How to save username and password in Git? Git Extensions: Win32 error 487: Couldn't reserve space for cygwin's heap, Win32 error 0