Edson Cezar
Edson Cezar

Reputation: 28084

How can I save username and password in Git?

I want to use a push and pull automatically in Git Extensions, Sourcetree or any other Git GUI without entering my username and password in a prompt, every time.

So how can I save my credentials in Git?

Upvotes: 2769

Views: 4434489

Answers (30)

Atul
Atul

Reputation: 4320

git config --global credential.helper store is the way to do it!

Here are correct steps:

On Azure click on clone repo -> Generate Git Credentials: enter image description here

It will generate password that you just copy to your clipboard

Then follow these steps:

$ git config --global credential.helper store

$ git clone https://[email protected]/myorg/my_project/_git/my_repo
Cloning into 'my_repo'...
Password for 'https://[email protected]': <Paste here password you've copied on your clipboard>
remote: Azure Repos
remote: Found 152 objects to send. (108 ms)
Receiving objects: 100% (152/152), 60.89 KiB | 432.00 KiB/s, done.
Resolving deltas: 100% (35/35), done.

$ cd my_repo/

$ git pull
Already up to date.

Notice that for last git command (i.e. git pull) it didn't ask password.

Upvotes: 0

Dean
Dean

Reputation: 649

On macOS, you can use the system keychain for security. I believe this is the most secure method for websites like Overleaf, which only offers HTTPS access (unless you link a GitHub repository of yours).

The following Git command activates this functionality.

git config --global credential.helper osxkeychain

(Additionally, as I write below, make sure you disable other credential helpers so that Git won't save your password, e.g., in plain text.) Then, you clone the Git repository:

git clone https://git.overleaf.com/blahblah

This asks for the password. Enter it, and you can see it in macOS' built-in KeyChain Access application.

In this case, you can find the entry for the URL with the name git.overleaf.com, which matches the Git URL.

For better security, you can require all applications to ask for your permission. You can remove Git from the "Always allow access by these applications", so that even Git will not be able to get the password without your permission.

Keychain Access configuration

Note: However, I noticed that some applications can still somehow Git pull without my permission. This is weird because, in this case, Overleaf's Git repository only offers https access. (I.e., there aren't any loophole through SSH.) If I change my password, I can temporarily block these applications from doing pull, but after I reregister my new password, these applications can do the pull again... Even if I check "Ask for Keychain password". Might be a misconfiguration or even a bug in macOS v13 (Ventura).

I found the problem. Git still had the configuration to store the credential written down in the global settings (~/.git-config). So you need to make sure you have the settings correct for different resolutions. This includes per-project, global (git config edit --system) and system (git config edit --system) should have the [credential] set to helper = osxkeychain only.

After you edit the settings, check ~/.git-credentials and see there isn't any password stored unintentionally (in plain text).

Upvotes: 3

edestrero
edestrero

Reputation: 516

In my case I just changed my domain access password due to normal expiration.

after this, VS2022 was unable to connect again to our devops/git server.

I literally tested any suggested solution, but the one that worked for me was to change the ./git/config file in a visual studio project that previously was working by adding explicit credentials in url.

ie:

before https://github.com/myRepoDir/myRepo.git

after https://Username:[email protected]/myRepoDir/myRepo.git

then I just did a pull, that this time worked as expected.

after this, I removed the clear text credentials from that url.

and this also did the trick for all other visual studio projects.

Upvotes: 0

Colonel Panic
Colonel Panic

Reputation: 137524

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 in-browser 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 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 (docs):

  1. Prefer choosing authentication method at terminal rather than in GUI (fewer clicks)
  2. Always use browser method rather than be asked every time (even fewer keypresses)
git config --global credential.guiPrompt false
git config --global credential.gitHubAuthModes browser

Upvotes: 32

Nadu
Nadu

Reputation: 2501

Just put your credentials in the URL like this:

https://Username:[email protected]/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

Upvotes: 68

user3342981
user3342981

Reputation: 145

Sudheer Singh's answer did not work for me completely. I figured I had to complete the "Testing your SSH connection". After the usual

git config --global user.name "userName"
git config --global user.email "[email protected]"
git config --global user.password "userPassword"
git config --global credential.helper store
git config --list --show-origin

I copied my public key to github account. Obtain your public key like this on your PC:

ssh-keygen -t rsa -b 4096 -C "[email protected]"
clip < ~/.ssh/id_rsa.pub

There is where you copy it on github.com → SettingsSSH and GPG keysNew SSH Key.

Then I ran ssh -T [email protected]. Finally, it works then.

I copied few commands from this answer as they are standard commands.

Upvotes: 4

eQ19
eQ19

Reputation: 10691

Your question:

I want to use a push and pull automatically in Git Extensions, Sourcetree or any other Git GUI without entering my username and password in a prompt, every time.
So how can I save my credentials in Git?

If you are in github or other providers I would recommend not to save them in the Git such as ~/.git-credentials but treat them as Encrypted secrets as they should.

Put the credential to the following format:

https://your_user_name:[email protected]/your_user_name/your_repo_name.git

Put it as encrypted secrets like secrets.REPOSITORY:

Actionsecrets

Then you can use it to clone either public of private repos along with its submodules as well as to do a push and pull automatically

# put the credentials in a variable
export REPOSITORY=${{ secrets.REPOSITORY }}

# git clone public or private repos
git clone --recurse-submodules -j8 ${REPOSITORY}

# git pull will do automatic
cd /path/to/the/repo
git pull

# git push to a branch in the repo
git add . && \
  git commit -m "Action from ${GITHUB_SHA}" && \
  git push --force $REPOSITORY master:$BRANCH

Upvotes: 2

mrigendra
mrigendra

Reputation: 1556

Save the username and password globally:

git config --global user.name "fname lname"
git config --global user.email "[email protected]"
git config --global user.password "secret"

Get a specific setting,

git config --global --get user.name
git config --global --get user.email
git config --global --get user.password

Getting all Git settings:

git config --list --show-origin

Upvotes: 12

prosti
prosti

Reputation: 46291

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

git config --local --edit

or

git config --global --edit

enter image description here Editing git config file in default text editor

You can also use the command line to edit the git config file directly (without the editor)

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'

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

--local or --global means configuration parameters are saved for the project or for the OS user.

Upvotes: 38

JiaHao Xu
JiaHao Xu

Reputation: 2748

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}:${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

Replace ${username} with your username, ${password_or_access_token} with your password (not recommended) or your access token.

NOTE that you must provide access token if you enabled 2FA on GitHub.

Using access token is recommended.

This is very useful for a GitHub robot, e.g. to solve Chain automated builds in the same Docker Hub repository by having rules for different branch and then trigger it by pushing to it in the post_push hook in Docker Hub.

An example of this can be seen here on Stack Overflow.

Upvotes: 54

Tuananhcwrs
Tuananhcwrs

Reputation: 1119

For global settings, open the terminal (from anywhere), run the following:

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

By that, any local Git repository that you have on your machine will use that information.

You can individually configure for each repository by doing:

  • open the terminal at the repository 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).

Upvotes: 74

Amin Shojaei
Amin Shojaei

Reputation: 6508

I think it's safer to cache credentials, instead of storing it 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 the next three hours.

It is nice and safe.

The unit for timeout is seconds (three hours in this example).

Upvotes: 92

simhumileco
simhumileco

Reputation: 34515

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.

Upvotes: 192

Andreas Bigger
Andreas Bigger

Reputation: 5540

Recommended and secure method: SSH

Generate a key following these steps: more details

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

set a passphrase that protects the key and store it locally

Copy the contents of the id_rsa.pub file to your clipboard for next step

clip < ~/.ssh/id_rsa.pub

Go to github.comSettingsSSH and GPG keysNew SSH Key. Paste they key and save it

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-cache 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'

Upvotes: 495

Farhad
Farhad

Reputation: 12976

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=<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).

You can again use --global to define for the whole system.

git config --global credential.helper 'cache --timeout=<timeout>'

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.

Upvotes: 699

Neetika
Neetika

Reputation: 45006

Attention:

This method saves the credentials in plaintext on your PC's disk. Everyone on your computer can access it, e.g. malicious NPM modules.

Run:

git config --global credential.helper store

then:

git pull

provide a username and password and those details will then be remembered later. The credentials are stored in a file on the disk, with the disk permissions of "just user readable/writable" but still in plaintext.

If you want to change the password later:

git pull

Will fail, because the password is incorrect, git then removes the offending user+password from the ~/.git-credentials file, so now re-run:

git pull

to provide a new password so it works as earlier.

Upvotes: 4464

Matt Lyons-Wood
Matt Lyons-Wood

Reputation: 960

For me I kept being asked for credentials because my repo directory somehow had credential.helper set to a blank value.

If you've tried all the other answers, check your config with git config --list --show-origin to make sure you're using the Credential Manager you think you're using.

You'll see something like this:

file:/home/username/.gitconfig      credential.helper=store
...
file:.git/config      credential.helper=

If there are conflicts, the repo-local value (file:.git/config) will be used - in the above case, blank.

Upvotes: 0

Mick
Mick

Reputation: 6864

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.

Note: Windows Credential Manager (executable wincred) has been deprecated. See:

Git Credential Manager for Windows - "This project is no longer being maintained. "

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

git config --global credential.helper manager

Upvotes: 9

aGuegu
aGuegu

Reputation: 2299

If security is not a concern for the Git client, edit the URL this way:

git remote set-url origin https://${access_token}@github.com/${someone}/${somerepo}.git

The same in the git clone case:

git clone https://${access_token}@github.com/${someone}/${somerepo}.git

I personally do not favor git config with global domain, since that would be a mess in a multiple-accounts case.

access_token is what you could generate in Settings / Developer settings / Personal access tokens. Remember to grant it with repo scope.

Upvotes: 13

Colonel Panic
Colonel Panic

Reputation: 137524

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 the binaries or source at hickford, git-credential-oauth.

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

Upvotes: 4

Tamjid Rayhan
Tamjid Rayhan

Reputation: 13

For GitLab users having the same issue:

You can setup a deploy token to clone or pull from your repository (you can not push code to the repository with a deploy token).

Here you can know more about GitLab deploy tokens: Deploy tokens

Once you create the deploy token, use the following to clone a repository:

git clone https://${username}:${deploy_token}@gitlab.com/yourusername/yourreponame.git

I think this approach is better than saving the Git username and Git password globally (for instance, it can be unsafe in a remote shared machine).

Upvotes: 0

Sudheer Singh
Sudheer Singh

Reputation: 654

To save your user name and user password into a GitHub account, just run these command in sequence.

git config --global user.name "userName"
git config --global user.email "[email protected]"
git config --global user.password "userPassword"
git config --global credential.helper store
git config --list --show-origin

Then generate a key using below command:

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

Note: Copy the file location where the id_rsa file gets created. Then go to that file location → open Git Bash or command prompt → Run a command - cat id_rsa.pub

The SSH key will be displayed, copy this SSH key and paste it in your GitHub or GitLab account.

Upvotes: 23

Yann Dubois
Yann Dubois

Reputation: 1345

The GitHub recommendations have now changed, and the best method is also the simplest. Details are here.

  1. Install the GitHub official CLI. E.g., for Mac: brew install gh.
  2. type gh auth login in your terminal, and then follow the prompts.

Upvotes: 10

T04435
T04435

Reputation: 13992

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

nano ~/.gitconfig

Which should already have

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

You should add the following at the bottom of this file.

[credential]
        helper = store

The reason I recommend this option is because 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, or others

See the documentation.

Restart your terminal.

Upvotes: 133

Baft Tabaku
Baft Tabaku

Reputation: 62

You can just simply modify ~/.git-credentials

then add the following line:

git:https://<user>:<token/password>@gitlab.com

that's it

Upvotes: -1

rogerdpack
rogerdpack

Reputation: 66711

From the comment by rofrol, on Linux Ubuntu, from this answer, here's how to do it on 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 distributions provide the binary, so you don't have to build it.

In OS X, it typically comes "built" with a default module added of "osxkeychain", so you get it for free. Both the OS X built-in one and the homebrew variety have it present by default.

Upvotes: 12

coolaj86
coolaj86

Reputation: 76984

After going over dozens of Stack Overflow 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 cheat sheet

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.js / npm package.json
  • Python / pip / eggs requirements.txt
  • Ruby gems Gemfile
  • Go go.mod

The Silver Bullet

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

Get your access token (see the section in the cheat sheet if you need the GitHub or Gitea instructions for that) and set it in an environment variable (both for local development 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]:"

Congratulations. Now any automated tool cloning Git repositories won't be obstructed by a password prompt, whether using HTTPS or either style of an SSH URL.

Not using GitHub?

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

Compatibility

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

More information

See the ".gitconfig insteadOf" section of the cheat sheet.

Security

See the "Security" section of the cheat sheet.

Upvotes: 125

Niroshan Ratnayake
Niroshan Ratnayake

Reputation: 3801

For Windows users, this way will work:

Note: If you have enabled two-factor authentication for GitHub, disable it for a while

  • Step 1

    Go to Control PanelUser AccountsCredential ManagerWindows Credentials

  • Step 2

    Go to the Generic Credentials section → Add a generic credential

    Enter image description here

  • Step 3 - Fill in the fields

    Internet or network address: git.https://github.com

    User name: your GitHub username

    Password: your GitHub username

    Enter image description here

    And now click on OK. This will save the password and the username of your GitHub account to your local machine

Upvotes: 3

Keshav Gera
Keshav Gera

Reputation: 11244

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

Check

git config --list

Upvotes: 3

Sma Ma
Sma Ma

Reputation: 3685

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

From 7.14 Git Tools - Credential Storage

Upvotes: 15

Related Questions