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 macOS, 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 enable the Git Credential Manager feature when installing Git for Windows or separately install the latest GCM as a standalone service.
This is similar to the “osxkeychain” helper described above, but uses the Windows Credential Store to control sensitive information.
It can also serve credentials to WSL1 or WSL2.
See GCM Install Instructions for more information.
You can choose one of these methods by setting a Git configuration value:
$ git config --global credential.helper cache
Some of these helpers have options.
The “store” helper can take a --file <path>
argument, which customizes where the plain-text file is saved (the default is ~/.git-credentials
).
The “cache” helper accepts the --timeout <seconds>
option, which changes the amount of time its daemon is kept running (the default is “900”, or 15 minutes).
Here’s an example of how you’d configure the “store” helper with a custom file name:
$ git config --global credential.helper 'store --file ~/.my-credentials'
Git even allows you to configure several helpers.
When looking for credentials for a particular host, Git will query them in order, and stop after the first answer is provided.
When saving credentials, Git will send the username and password to all of the helpers in the list, and they can choose what to do with them.
Here’s what a .gitconfig
would look like if you had a credentials file on a thumb drive, but wanted to use the in-memory cache to save some typing if the drive isn’t plugged in:
[credential]
helper = store --file /mnt/thumbdrive/.git-credentials
helper = cache --timeout 30000
Under the Hood
How does this all work?
Git’s root command for the credential-helper system is git credential
, which takes a command as an argument, and then more input through stdin.
This might be easier to understand with an example.
Let’s say that a credential helper has been configured, and the helper has stored credentials for mygithost
.
Here’s a session that uses the “fill” command, which is invoked when Git is trying to find credentials for a host:
$ git credential fill (1)
protocol=https (2)
host=mygithost
(3)
protocol=https (4)
host=mygithost
username=bob
password=s3cre7
$ git credential fill (5)
protocol=https
host=unknownhost
Username for 'https://unknownhost': bob
Password for 'https://bob@unknownhost':
protocol=https
host=unknownhost
username=bob
password=s3cre7
-
This is the command line that initiates the interaction.
-
Git-credential is then waiting for input on stdin.
We provide it with the things we know: the protocol and hostname. -
A blank line indicates that the input is complete, and the credential system should answer with what it knows.
-
Git-credential then takes over, and writes to stdout with the bits of information it found.
-
If credentials are not found, Git asks the user for the username and password, and provides them back to the invoking stdout (here they’re attached to the same console).
The credential system is actually invoking a program that’s separate from Git itself; which one and how depends on the credential.helper
configuration value.
There are several forms it can take:
Configuration Value | Behavior |
---|---|
|
Runs |
|
Runs |
|
Runs |
|
Code after |
So the helpers described above are actually named git-credential-cache
, git-credential-store
, and so on, and we can configure them to take command-line arguments.
The general form for this is “git-credential-foo [args] <action>.”
The stdin/stdout protocol is the same as git-credential, but they use a slightly different set of actions:
-
get
is a request for a username/password pair. -
store
is a request to save a set of credentials in this helper’s memory. -
erase
purge the credentials for the given properties from this helper’s memory.
For the store
and erase
actions, no response is required (Git ignores it anyway).
For the get
action, however, Git is very interested in what the helper has to say.
If the helper doesn’t know anything useful, it can simply exit with no output, but if it does know, it should augment the provided information with the information it has stored.
The output is treated like a series of assignment statements; anything provided will replace what Git already knows.
Here’s the same example from above, but skipping git-credential
and going straight for git-credential-store
:
$ git credential-store --file ~/git.store store (1)
protocol=https
host=mygithost
username=bob
password=s3cre7
$ git credential-store --file ~/git.store get (2)
protocol=https
host=mygithost
username=bob (3)
password=s3cre7
-
Here we tell
git-credential-store
to save some credentials: the username “bob” and the password “s3cre7” are to be used whenhttps://mygithost
is accessed. -
Now we’ll retrieve those credentials.
We provide the parts of the connection we already know (https://mygithost
), and an empty line. -
git-credential-store
replies with the username and password we stored above.
Here’s what the ~/git.store
file looks like:
https://bob:s3cre7@mygithost
It’s just a series of lines, each of which contains a credential-decorated URL.
The osxkeychain
and wincred
helpers use the native format of their backing stores, while cache
uses its own in-memory format (which no other process can read).
A Custom Credential Cache
Given that git-credential-store
and friends are separate programs from Git, it’s not much of a leap to realize that any program can be a Git credential helper.
The helpers provided by Git cover many common use cases, but not all.
For example, let’s say your team has some credentials that are shared with the entire team, perhaps for deployment.
These are stored in a shared directory, but you don’t want to copy them to your own credential store, because they change often.
None of the existing helpers cover this case; let’s see what it would take to write our own.
There are several key features this program needs to have:
-
The only action we need to pay attention to is
get
;store
anderase
are write operations, so we’ll just exit cleanly when they’re received. -
The file format of the shared-credential file is the same as that used by
git-credential-store
. -
The location of that file is fairly standard, but we should allow the user to pass a custom path just in case.
Once again, we’ll write this extension in Ruby, but any language will work so long as Git can execute the finished product.
Here’s the full source code of our new credential helper:
#!/usr/bin/env ruby
require 'optparse'
path = File.expand_path '~/.git-credentials' # (1)
OptionParser.new do |opts|
opts.banner = 'USAGE: git-credential-read-only [options] <action>'
opts.on('-f', '--file PATH', 'Specify path for backing store') do |argpath|
path = File.expand_path argpath
end
end.parse!
exit(0) unless ARGV[0].downcase == 'get' # (2)
exit(0) unless File.exist? path
known = {} # (3)
while line = STDIN.gets
break if line.strip == ''
k,v = line.strip.split '=', 2
known[k] = v
end
File.readlines(path).each do |fileline| # (4)
prot,user,pass,host = fileline.scan(/^(.*?):\/\/(.*?):(.*?)@(.*)$/).first
if prot == known['protocol'] and host == known['host'] and user == known['username'] then
puts "protocol=#{prot}"
puts "host=#{host}"
puts "username=#{user}"
puts "password=#{pass}"
exit(0)
end
end
-
Here we parse the command-line options, allowing the user to specify the input file.
The default is~/.git-credentials
. -
This program only responds if the action is
get
and the backing-store file exists. -
This loop reads from stdin until the first blank line is reached.
The inputs are stored in theknown
hash for later reference. -
This loop reads the contents of the storage file, looking for matches.
If the protocol, host, and username fromknown
match this line, the program prints the results to stdout and exits.
We’ll save our helper as git-credential-read-only
, put it somewhere in our PATH
and mark it executable.
Here’s what an interactive session looks like:
$ git credential-read-only --file=/mnt/shared/creds get
protocol=https
host=mygithost
username=bob
protocol=https
host=mygithost
username=bob
password=s3cre7
Since its name starts with “git-”, we can use the simple syntax for the configuration value:
$ git config --global credential.helper 'read-only --file /mnt/shared/creds'
As you can see, extending this system is pretty straightforward, and can solve some common problems for you and your team.
Last Updated :
11 Jun, 2024
Managing credentials efficiently is important for seamless interaction with remote Git repositories. By default, Git prompts for a username and password each time you interact with a remote repository. To simplify this process, you can configure Git to save your credentials, allowing for a smoother workflow. This article will guide you through various methods to save your username and password in Git.
Prerequisites
Before proceeding, ensure you have the following:
- Git Installed: Make sure Git is installed on your system. You can download it from Git’s official website.
- Access to a Remote Repository: Ensure you have access to a remote repository where you need to save your credentials.
Methods to Save Credentials
Method 1. Using Git Credential Helper
Git includes a credential helper that can save your credentials. There are different types of credential helpers, including:
1. cache Helper
The cache helper temporarily stores your credentials in memory for a configurable period.
- Set Up Cache Helper: Configure Git to use the cache helper with a timeout (e.g., 3600 seconds = 1 hour):
git config --global credential.helper 'cache --timeout=3600'
2. store Helper
The store helper saves your credentials in a plain-text file on disk.
- Set Up Store Helper: Configure Git to use the store helper:
git config --global credential.helper store
- First Usage: The first time you push or pull, Git will ask for your username and password and store them in ~/.git-credentials.
3. manager-core (Windows and macOS) / osxkeychain (macOS) / libsecret (Linux)
These helpers store credentials securely in the OS-specific credential storage.
For Windows
git config --global credential.helper manager-core
For macOS:
git config --global credential.helper osxkeychain
For Linux:
git config --global credential.helper libsecret
Method 2. Saving Credentials for HTTPS Repositories
If you are working with HTTPS repositories, you can directly save the username and password in the repository URL. However, this method is not recommended due to security risks.
- Clone Repository with Credentials:
git clone https://username:password@github.com/username/repository.git
- Update Remote URL with Credentials:
git remote set-url origin https://username:password@github.com/username/repository.git
Warning: Storing credentials in URLs is insecure and should be avoided whenever possible.
Method 3: Using SSH Keys
A more secure and recommended method is to use SSH keys instead of saving plain-text credentials.
- Generate SSH Key:
ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
- Add SSH Key to SSH-Agent:
eval "$(ssh-agent -s)"
ssh-add ~/.ssh/id_rsa
- Add SSH Key to GitHub/GitLab: Copy the contents of ~/.ssh/id_rsa.pub and add it to your GitHub/GitLab account under SSH keys.
- Clone Repository Using SSH:
git clone git@github.com:username/repository.git
Method 4. Using Personal Access Tokens
For increased security, especially with platforms like GitHub, you can use Personal Access Tokens (PATs).
- Generate PAT: Go to your GitHub account settings and generate a PAT with the necessary permissions.
- Use PAT Instead of Password: When prompted for a password, use the PAT instead.
git clone https://github.com/username/repository.git
Username: your_username
Password: your_token
In this article, we want to show how to save username and password for git under Windows, when we don’t want to type it each time during push
/ pull
operations.
Quick solution (run command):
git config --global credential.helper manager
In the below sections we can see described two variants:
- built-in in operating system Windows Credential Manager,
- git credential store.
1. Windows Credential Manager example
This approach uses Windows Credential Manager that stores passwords in operating system safe storage.
Simple steps:
- run Git Bash,
- run following command:
git config --global credential.helper manager
- run following command in the project directory:
git pull
or any other git command that requires authentication,
- Windows Credential Manager will ask us for username and password,
- type username and password and click Ok or other confirmation action,
- all future git authentications for this git account will go from Windows Credential Manager.
Notes:
- now our password is saved with Windows Credential Manager — not as plain text
- Available from Git for Windows 2.7.3+ — github release
2. git credential store example
This approach uses git credential store that stores passwords in a simple text file.
Simple steps:
- run Git Bash,
- run following command:
git config credential.helper store
- run following command in the project directory:
git pull
or any other git command that requires authentication,
- we will be asked to provide username and password to our git account,
- type username and password and click Ok or other confirmation action,
- all future git authentications for this git account will go from
.git-credentials
file.
Note: the password is stored as plain text in
C:\Users\my_user_name\.git-credentials
what is not safe when our account is not encrypted.
References
- Git Credential Manager for Windows
- Windows Credential Manager
- Git config — docs
- How do I save git credential under windows?
- Git — save username and password with windows
- How to safely store git credential under windows?
- Windows and git — save username and password
To connect to a Git repository with authentication over HTTP(S), every time it needs to set a username and password.
You can configure Git to remember a username and password by storing them in a remote URL or by using Git credential helper.
In this article i am showing how to clone Git repository by setting a username and password on the command line, how to save a username and password in Git credentials storage and how to configure different usernames and passwords for different repositories on the same Git server.
Cool Tip: Show Git branch name in the command prompt! Read more →
Warning: Your Git credentials will be saved in a plaintext format in the files .git/config
or ~/.git-credentials
, depending on the method you choose.
Set Username and Password in Remote URL
To save credentials you can clone Git repository by setting a username and password on the command line:
$ git clone https://<USERNAME>:<PASSWORD>@github.com/path/to/repo.git
The username and password will be stored in .git/config
file as a part of the remote repository URL.
If you have already cloned a repository without setting username and password on the command line, you can always update the remote URL by running the following command:
$ git remote set-url origin https://<USERNAME>:<PASSWORD>@github.com/path/to/repo.git
Save Username and Password in Git Credentials Storage
Run the following command to enable credentials storage in your Git repository:
$ git config credential.helper store
To enable credentials storage globally, run:
$ git config --global credential.helper store
When credentials storage is enabled, the first time you pull or push from the remote Git repository, you will be asked for a username and password, and they will be saved in ~/.git-credentials
file.
During the next communications with the remote Git repository you won’t have to provide the username and password.
Each credential in ~/.git-credentials
file is stored on its own line as a URL like:
https://<USERNAME>:<PASSWORD>@github.com
Config Username and Password for Different Repositories
Sometimes you may need to use different accounts on the same Git server, for example your company’s corporate account on github.com and your private one.
To be able to configure usernames and passwords for different Git repositories on the same Git server you can enable the useHttpPath
option.
By default, Git does not consider the “path” component of an http URL to be worth matching via external helpers. This means that a credential stored for
https://example.com/foo.git
will also be used forhttps://example.com/bar.git
. If you do want to distinguish these cases, setuseHttpPath
option to true (source)
Run the following commands to configure Git credentials storage and separate credentials for different repositories on github.com:
$ git config --global credential.helper store $ git config --global credential.github.com.useHttpPath true
The usernames and passwords for different GitHub repositories will be stored in ~/.git-credentials
file separately on their own lines:
https://<USERNAME>:<PASSWORD>@github.com/path/to/repo1.git https://<USERNAME>:<PASSWORD>@github.com/path/to/repo2.git
Cool Tip: Create a new Git branch and checkout in one command! Read More →
Was it useful? Share this post with the world!
При работе с закрытыми git репозиториями приходится каждый раз вводить логин и пароль при подключении по SSH. Это связано с тем, что Git не кеширует пользовательские данные. Решить эту проблему можно двумя способами:
- создать ssh ключ и добавить его в профиль git платформы
- сохранить логин и пароль
В это статье рассмотрим второй вариант.
Важно понимать, что логин и пароль будут сохранены в текстовом файле в открытом виде. Этот файл можно открыть текстовым редактором и увидеть все пользовательские данные, поэтому способ не самый безопасный. Тем не менее, если вы работаете один за своим компьютером, то способ вполне рабочий.
Существует два метода хранения пароля:
- cache режим хранит пароль в памяти определенное время (конечный срок)
- store режим сохраняет пароль на постоянной основе
Чтобы сохранять логин и пароль в режиме «cache», используйте команду:
git config --global credential.helper cache --timeout 3600
- git config — команда для настройки
- —global — указываем, что будет настраивать глобально, а не для репозитория
- credential.helper cache — указываем режим хранения данных «cache»
- —timeout — как долго будет хранится пароль (в секундах)
Чтобы сохранять пользовательские данные навсегда, воспользуйтесь командой:
git config --global credential.helper store
- git config — команда для настройки
- —global — указываем, что будет настраивать глобально, а не для репозитория
- credential.helper store — указываем режим хранения данных «store»
По умолчанию пользовательские данные хранятся в файле домашнего каталога пользователя ~/.git-credentials
После выполнения команды нужно ввести логин и пароль (например сделать git pull) и в следующий раз данные для входа не будут запрашиваться.