ChatGPT解决这个技术问题 Extra ChatGPT

Git keeps prompting me for a password

I've been using Git for a while now, but the constant requests for a password are starting to drive me up the wall.

I'm using Mac OS X and GitHub, and I set up Git and my SSH keys as instructed by GitHub's Set Up Git page.

I've also added the github SSH key to my Mac OS X keychain, as mentioned on GitHub's SSH key passphrases page. My public key is registered with Git.

Nevertheless, every time I try to Git pull, I have to enter my username and password. Is there something other than an SSH key that I need to set up for this?

Silly question, but have you verified that the SSH key works when simply using ssh to the machine with git?
You mean something like ssh -T git@github.com ? Yeah, that works just fine (if a little slow).
For https url, you can use (with git1.8.3+) a git credential helper 'netrc'. See a full example here.
I am a Windows user, and I was also facing password request issue even after adding my public key to authorized_keys file of server. What really the problem was that I was not keeping my public/private keys under .ssh folder of c:\program files\git folder. If anyone is facing such issue, please copy your keys in this folder and try pushing/pulling.

B
Bizhan

I think you may have the wrong Git repository URL.

Open .git/config and find the [remote "origin"] section. Make sure you're using the SSH one:

ssh://git@github.com/username/repo.git

You can see the SSH URL in the main page of your repository if you click Clone or download and choose ssh.

And NOT the https or git one:

https://github.com/username/repo.git
git://github.com/username/repo.git

You can now validate with just the SSH key instead of the username and password.

If Git complains that 'origin' has already been added, open the .config file and edit the url = "..." part after [remote origin] as url = ssh://github/username/repo.git

The same goes for other services. Make sure the address looks like: protocol://something@url

E.g. .git/config for Azure DevOps:

[remote "origin"]
    url = https://mystore@dev.azure.com/mystore/myproject/
    fetch = +refs/heads/*:refs/remotes/origin/*

This may be it. When I call git remote -v I get: origin github.com/Foo/Bar.git (fetch) origin github.com/Foo/Bar.git (push) whereas to work with SSH it seems that it should be: origin git@github.com:Foo/Bar.git (fetch) origin git@github.com:Foo/Bar.git (push) This may be because I originally checked out my project using GitHub's Mac application (mac.github.com). Any idea how I can fix it?
Either fix the url in the .git/config file, use git-remote to fix it, or delete your local repo and clone it again with the correct URL.
Just to spell this out (as I needed it): open .git/config and in the [remote "origin"] section set url = ssh://git@github.com/username/Repo.git. That worked for me.
Odd, @GregK's solution didn't work for me, but url = git@github.com:organization/Repo.git did work. +1 for leading me down the right path though! Success!
I can't stress enough how important it is to CLONE using ssh://git@github/[username]/[reponame].git is you want to use an key to access GIT not have to type your username and password each time. I found the only way to fix it was to remove the local repo and clone again $ git clone ssh://git@github/[username]/[reponame].git
C
Community

Configuring credential.helper

On OS X (now macOS), run this in Terminal:

git config --global credential.helper osxkeychain

It enables Git to use file Keychain.app to store username and password and to retrieve the passphrase to your private SSH key from the keychain.

For Windows use:

git config --global credential.helper wincred

For Linux use:

git config --global credential.helper cache // If you want to cache the credentials for some time (default 15 minutes)

OR

git config --global credential.helper store // if you want to store the credentials for ever (considered unsafe)

Note: The first method will cache the credentials in memory, whereas the second will store them in ~/.git-credentials in plain text format.

Check here for more info about Linux method.
Check here for more info about all three.

Troubleshooting

If the Git credential helper is configured correctly macOS saves the passphrase in the keychain. Sometimes the connection between SSH and the passphrases stored in the keychain can break. Run ssh-add -K or ssh-add ~/.ssh/id_rsa to add the key to keychain again.

macOS v10.12 (Sierra) changes to ssh

For macOS v10.12 (Sierra), ssh-add -K needs to be run after every reboot. To avoid this, create ~/.ssh/config with this content.

Host *
    AddKeysToAgent yes
    UseKeychain yes
    IdentityFile ~/.ssh/id_rsa

From the ssh_config man page on 10.12.2:

UseKeychain

On macOS, specifies whether the system should search for passphrases in the user's keychain when attempting to use a particular key. When the passphrase is provided by the user, this option also specifies whether the passphrase should be stored into the keychain once it has been verified to be correct. The argument must be 'yes' or 'no'. The default is 'no'.

Apple has added Technote 2449 which explains what happened.

Prior to macOS Sierra, ssh would present a dialog asking for your passphrase and would offer the option to store it into the keychain. This UI was deprecated some time ago and has been removed.


This is by far the best way to do this since the Github application for OSX (maybe Windows as well) uses the https path for git repos by default. There is also a good reason for using https rather than ssh/git since many corporate networks only allow traffic on port 80 and 443 for security reasons.
You need git 1.7.10 or newer to use the credential helper.
+1 for keychain.app solution. This is GREAT for me because my employer's git server only supports http served via apache and they strongly discourage using the .netrc file method which puts your password in plaintext.
Note, I got the error 'credential-osxkeychain' is not a git command. as I didn't have the credential helper installed. I followed the instructions here to install it: help.github.com/articles/set-up-git#password-caching
Thanks for the Sierra update, I just updated and couldn't figure out why github kept asking for pw when I added the git config --global credential.helper osxkeychain The config file in my .ssh directory fixed me up.
P
Peter Mortensen

This happened to me when I upgraded to macOS v10.12 (Sierra). Looks like the SSH agent got cleared upon upgrade.

$ ssh-add -L
The agent has no identities.

Simply running ssh-add located my existing identity. I entered the password and was good to go again.


+1 broken by Sierra upgrade. Note the password is the password for your SSH key and not your Mac user password.
Doing ssh-add does work but appears to be reset by closing the Terminal window. Maybe this is a new "feature".
Heads up - this happened again with another Sierra update (10.12.2) but the same fix applies.
Does anyone know how to have this not be reset after Terminal is closed?
I had just updated my macbook pro to 10.12.2 and it broke my git. Using ssh-add totally worked for me. Thanks @amcc!
m
marteljn

Use this: Replace github.com with the appropriate hostname

git remote set-url origin git@github.com:user/repo.git

I already have that set when viewing git remote -v. Yet, I am still being prompted for password.
Same, I have set as what he suggested, but I still get prompt for password, how do I prevent that ?
@IgorGanapolsky : Did you ever found a solution for you ?
This works properly. This is weird that remote URL with git@** doesn't prompt credentials and URL with https@** does :). Thus I found this doc.
P
Peter Mortensen

As others have said, you can install a password cache helper. I mostly just wanted to post the link for other platforms, and not just Mac. I'm running a Linux server and this was helpful: Caching your GitHub password in Git

For Mac:

git credential-osxkeychain

Windows:

git config --global credential.helper wincred

Linux:

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

I had to scroll down to the third answer to see the Linux instructions, these should be in the primary answer since it is a commonly referenced issue.
P
Peter Mortensen

Also look for who is asking you for the passphrase. Is it Git or your SSH agent?

In my case, every time I did git pull it was asking me:

Enter passphrase for key '/work/username/.ssh/id_rsa':

So I assumed it was Git asking for a passphrase. So I kept hunting for solutions, only to realize later that my SSH agent had shut down. Which can be fixed using eval $(ssh-agent) and ssh-add as given here.

Also am pasting below a little snippet you can add to your ~/.bashrc file (or the equivalent) to ensure that your SSH agent is started on your login.

In any case this was a pretty silly mistake I made, but posting it here, just in case it helps someone save some time from barking up the wrong tree, like I did.

# 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


Pretty sure you are missing a line in the code above - as per stackoverflow.com/a/18915067/277023 you need to have SSH_ENV="$HOME/.ssh/environment"
L
Lokesh S
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

P
Peter Mortensen

Use the following command to increase the timeout period so that you could retype password for a while

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

I used it for Bitbucket and GitHub it works for both. The only thing you need to do is 3600 is in seconds. Increase it to whatever extent you want. I changed it to 259200 which is about 30 days. This way I re-enter my password for every 30 days or so.


Ok, I've found that this does not persist after a restart, so you still need to enter the password after a restart, regardless of timeout...
This is a nice way to make in cache :) At least saved my time. Thanks
@BenWinding because it stores credentials in memory.
C
Community

In Windows for Git 1.7.9+, run the following command on the command prompt to open the configuration file in a text editor:

git config --global --edit

Then in the file, add the following block if not present or edit it accordingly:

[credential "https://giturl.com"]
username = <user id>
helper = wincred

Save and close the file. You will need to provide the credentials only once after the above change.


this works perfect, you saved my hours, now I can concentrate on my work, Thanks a lot Brother.
This did not work for me. "error: There was a problem with the editor '"D:/Programs/GitExtensions/GitExtensions.exe" fileeditor'"
P
Peter Mortensen

Guide to Git on Windows and GitHub using SSH to push/pull: An Illustrated Guide to Git on Windows

Download and install PuTTY Set environment variable 'GIT_SSH' = 'path\to\plink.exe' (in installed putty folder) - very important!!! Restart Windows Explorer for environment variables to take effect (cannot only restart command prompt) Run puttygen.exe to generate new key, copy the public key to the GitHub site Save this new private key somewhere safe on the disk (preferable not Dropbox) Run putty.exe and connect SSH to github.co Quickly get to startup folder by running "shell:startup". Make your private key startup with Windows via pageant. Create a shortcut in Startup folder with syntax "path\to\pageant.exe" "path\to\privatekey" We do not need to set the 'puttykeyfile' setting inside .git/config of our repositories Very important is that the "SSH clone URL" of GitHub is used and not HTTPS.


Nobody should be using putty anymore. You can do everything now with built in Windows 10 utilities. Let putty, just be putty.
A
Ahmed

If you want to stop Git from always asking you for the login credentials of your GitHub repository this can be easily done.

Using SSH instead of HTTPS

You can update the origin remote using SSH instead of HTTPS"

git remote set-url origin git@github.com:username/your-repo.git

Configure Git to Store your Password and Username

Here’s how you can make Git store the username and password:

git config --global credential.helper store

Next, save the username and password for a session:

git config --global credential.helper cache

P
Peter Mortensen

I feel like the answer provided by static_rtti is hacky in some sense. I don't know if this was available earlier, but Git tools now provide credential storage.

Cache Mode

$ git config --global credential.helper cache

Use the “cache” mode to keep 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.

Store Mode

$ git config --global credential.helper 'store --file ~/.my-credentials'

Use the “store” mode to save the credentials to a plain-text file on disk, and they never expire.

I personally used the store mode. I deleted my repository, cloned it, and then had to enter my credentials once.

Reference: 7.14 Git Tools - Credential Storage


For Windows credential.helper cache does NOT work. It should be git config --global credential.helper wincred.
Storing it worked and now it allows me to commit my changes without prompting for a password all the time, you're a lifesaver!
In Linux this did the job for me git config --local credential.helper store. In my case, I'm over HTTPS, in this way I only type username/password one time and after that, my credentials are reused from ~/.git-credentials
P
Peter Mortensen

If Git prompts you for a username and password every time you try to interact with GitHub, you're probably using the HTTPS clone URL for your repository.

Using an HTTPS remote URL has some advantages: it's easier to set up than SSH, and usually works through strict firewalls and proxies. However, it also prompts you to enter your GitHub credentials every time you pull or push a repository.

You can configure Git to store your password for you. For Windows:

git config --global credential.helper wincred

M
Marko

I figure you fixed your problem, but I don't see the solution here that helped me, so here it is.

Type in terminal:

echo "" > ~/.ssh/known_hosts

That will empty your known_hosts file, and you'll have to add every host you used and have connected to, but it solved the problem.


cat /dev/null > ~/.ssh/known_hosts will do the same.
> ~/.ssh/known_hosts is even shorter :)
rm ~/.ssh/known_hosts should do the job too. I would advise against this though.
If you need to remove a host from ~/.ssh/known_hosts, there is a less impactful way than wiping out the file. ~/.ssh/known_hosts is just a text file and if you can find the offending hosts in the file, you can just delete their lines. You may want to back up the file before editing it. If you only have a few entries in the file, then wiping it out might not be a bad idea. I work on lots of servers so my ~/.ssh/known_hosts has hundreds of entries in it and I'm not quite ready to delete them all to remove a few entries.
@papan This does not prevent git from asking me for my password!
m
mbomb007

On Windows Subsystem for Linux (WSL) this was the only solution that I found to work:

eval `ssh-agent`; ssh-add ~/.ssh/id_rsa

It was a problem with the ssh-agent not being properly registered in WSL.


Been a whlie, but this is what fixed my issue.
F
FrostyDog

I had the same problem. MacOS Mojave keychain keeps asking for the passphrase. Your id_rsa should be encrypted with a passphrase for security. Then try adding it to the keychain ssh-add -K ~/.ssh/id_rsa

If your key is in another folder than ~/.ssh then substitute with the correct folder.

Keychain now knows your ssh key, hopefully, all works now.

If you are still facing the issue then try

1. brew install keychain

2. echo '/usr/local/bin/keychain $HOME/.ssh/id_rsa' >> ~/.bash_profile
   echo 'source $HOME/.keychain/$HOSTNAME-sh' ~/.bash_profile

3. ssh-add -K ~/.ssh/id_rsa

Hopefully, it should work now.

Update: The -K flag has since been deprecated. Use the following instead:

ssh-add --apple-use-keychain ~/.ssh/id_ed25519 # path to private key

Thank you! The top solution didn't work for me but using ssh-add like you said finally resolved the issue for me.
Since the "-K" flag is deprecated use "--apple-use-keychain" instead: ssh-add --apple-use-keychain ~/.ssh/id_rsa
I
ICeZer0

Running macOS Cataline 10.15, the keychain caching method was not working for me. And I wanted to use https:// not ssh

Here is what worked for me:

git remote rm origin

git remote add origin https://your_git_username:your_git_password@github.com/path_to_your_git.git

This should work on GitLab too

Make sure if the username contains an email address, to remove the @email part or you'll get an error stating URL using bad/illegal format or missing URL.

Hope this helps!


This is the ONLY solution that worked for me. your_git_username was critical. It was actually not necessary to put :your_git_password. At this point, even though it still asked for a "passphrase", it would now accept the account password.
S
Snoi Singla

Git will prompt you for a passowrd if you are using https protocol. If you use ssh, it will do the authentication using your private key instead of asking for password. (https://help.github.com/en/github/authenticating-to-github/adding-a-new-ssh-key-to-your-github-account)

Here is how to fix this:

git remote -v

This will show the url for origin. And you will notice https in this url. (Example : https://github.com/PrestaShop/PrestaShop.git)

Now, you will have to just remove this first and add the url with ssh

git remote remove origin

git remote add origin git@github.com:PrestaShop/PrestaShop.git


P
Peter Mortensen

orkoden's answer on using the keychain with Git in your terminal was incomplete and raises errors. This is what you have to do to save the username and password you enter in the the terminal in your keychain:

curl http://github-media-downloads.s3.amazonaws.com/osx/git-credential-osxkeychain -o git-credential-osxkeychain
sudo mv git-credential-osxkeychain /usr/local/bin
sudo chmod u+x /usr/local/bin/git-credential-osxkeychain

Then enter

git config --global credential.helper osxkeychain

If you have already done the part with Git configuration before the curl stuff, it's no problem; it'll work.


What if I'm on linux.
P
Peter Mortensen

As static_rtti said above, change

https://github.com/username/repo.git
git://github.com/username/repo.git

to

ssh://git@github.com/username/repo.git

I myself changed the https in the .git/config file to ssh, but it still wasn't working. Then I saw that you must change github.com to git@github.com. A good way to get the actual correct URL is to go to your project page and click this:

Change HTTPS to SSH to get the right URL

Then add this URL to the configuration file.


I have that in my config config file already what else should I check ?
Did you change it on github.com as well?
P
Peter Mortensen

I agree with "codehugger" and using the instruction of "orkoden" it worked for me - on NetBeans 7.3 - when you right-click on the file and select context menu - push - a 'push to remote' window opened - there are two options here:

origin:https://github.com/myaccount/myproject.git/ https://github.com/myaccount/myproject.git/

As you can see, the difference is the origin parameter in the URL - you do not want to choose this option (1) you want to check option (2), and that works just fine for me.


P
Peter Mortensen

Step 1: check your current configuration

cat .git/config

You will get:

[core]
    repositoryformatversion = 0
    filemode = true
    bare = false
    logallrefupdates = true
    ignorecase = true
    precomposeunicode = true
[remote "origin"]
    url = https://github.com/path_to_your_git.git
    fetch = +refs/heads/*:refs/remotes/origin/*
[user]
    name = your_username
    email = your_email
[branch "master-staging"]
    remote = origin
    merge = refs/heads/master-staging

Step 2: remove your remote origin

git remote rm origin

Step 3: add remote origin back with your username and password

git remote add origin https://your_git_username:your_git_password@github.com/path_to_your_git.git

After you've added the remote origin again you also need to align your branches remote and local - something like this: git branch --set-upstream master origin/master
P
Peter Mortensen

There are different kind of authentications depending on your configuration. Here are a few:

git credential-osxkeychain. If your credential is invalid, remove it by: git credential-osxkeychain erase or: printf "protocol=https\nhost=github.com\n" | git credential-osxkeychain erase So Git won't ask you for the keychain permission again. Then configure it again. See: Updating credentials from the OS X Keychain at GitHub Your SSH RSA key. For this, you need to compare your SSH key with what you've added, check by ssh-add -L/ssh-add -l if you're using the right identity. Your HTTPS authentication (if you're using https instead of ssh protocol). Use ~/.netrc (%HOME%/_netrc on Windows), to provide your credentials, e.g. machine stash1.mycompany.com login myusername password mypassword

Learn more: Syncing with GitHub at Stack Overflow.


P
Peter Mortensen

Before you can use your key with GitHub, follow this step in the tutorial, Testing your SSH connection:

$ ssh -T git@github.com
# Attempts to ssh to GitHub

P
Peter Mortensen

If you're using Windows and this has suddenly started happening on out of the blue on GitHub, it's probably due to GitHub's recent disabling support for deprecated cryptographic algorithms on 2018-02-22, in which case the solution is simply to download and install the latest version of either the full Git for Windows or just the Git Credential Manager for Windows.


n
nyuszika7h

If you have SSH agent set up, you can also add this to your ~/.gitconfig to force git to use SSH for all GitHub repos rather than HTTPS:

[url "ssh://git@github.com/"]
    insteadOf = git://github.com/
    insteadOf = https://github.com/

(If you're mostly working with public repos, you can also use pushInsteadOf rather than insteadOf, as reading from a public repo can be done without authentication).


B
Bizhan

Microsoft Stack solution (Windows and Azure DevOps)

First open the .git/config file to make sure the address looks like:

protocol://something@url

E.g. .git/config for Azure DevOps:

[remote "origin"]
    url = https://mystore@dev.azure.com/mystore/myproject/
    fetch = +refs/heads/*:refs/remotes/origin/*

If the problem still persists, open Windows Credential Manager, click on the safebox named Windows Credentials and remove all the git related credentials.

Now the next time you log into git, it won't go away anymore.


J
Jonathan Hale

I had this issue. A repo was requiring me to input credentials every time. All my other repos were not asking for my credentials. They were even set up to track GitLab using HTTPS under the same account credentials, so it was weird that they all worked fine except one.

Comparing the .git/config files, I found that there were 2 key differences in the URLs which was causing the issue:

Does ask for credentials:

https://gitlab.com/myaccount/myproject

Does not ask for credentials:

https://myaccount@gitlab.com/myaccount/myproject.git 

So adding the "myaccount@" and ".git" resolved the issue in my case.


R
Rohit Gaikwad

In my case, I was always getting a password prompt when I tried to cherrypick a URL like below:

git fetch http://username@gerrit-domainname/repositoryname refs/changes/1/12345/1 && git cherry-pick FETCH_HEAD

This URL worked well when cherrypicked on a different machine. However, At my end when I try to cherrypick with correct password abc@12345 I used to get below error:

remote: Unauthorized
remote: Authentication failed for http://username@gerrit-domainname  

In my git config file the remote URL was like below:

url = ssh://gerrit-domainname:8080/wnc

Solution: I resolved the authentication failure issue by providing the HTTP Password which I found at My gerrit account -> Settings -> HTTP Password.

The HTTP Password was something like Th+IsAduMMy+PaSS+WordT+RY+Your+OwNPaSs which was way different than my actual password abc@12345

Note: My URL to cherrpick starts with git fetch ... So, this solution might work on git checkout/download where the URL starts with git fetch ...


S
Salahuddin Ahmed

Faced same kind of issue.

Please make sure you have properly set the remote origin:

$git remote add origin master "https://...git "