gitvisual-studio-codevisual-studio-2019

"Permission denied" error from Visual Studio Code and Visual Studio (but not Git Bash)


With a new work laptop running Windows 10, I have installed git, Visual Studio Code and Visual Studio 2019. After making some test changes to code in from my personal git repo (hosted on github), I am trying to commit and push those changes to the remote repo.

I can perform all of the Stage, Commit and Push actions from Git Bash. But in Git Gui, VS Code and VS 2019, Stage and Commit both work fine, but Push fails with an error message.

For VS Code the error is:

git@github.com: Permission denied (publickey).
fatal: Could not read from remote repository.

And for VS 2019 the error is similar:

git@github.com: Permission denied (publickey).
Error encountered while pushing to the remote repository: Git failed with a fatal error.
Could not read from remote repository.

How do I resolve this?

Update

The comment from @DaemonPainter helped lead to the answer. My private SSH key files were named id_rsa_github and id_rsa_github.pub. Visual Studio 2019, Code and Git Gui all expect these to be named id_rsa and id_rsa.pub.

The solution is to add a config file to %HOMEPATH%\.ssh with contents similar to this:

host github.com
 HostName github.com
 IdentityFile ~/.ssh/id_rsa_github

After making that change, git push works in Git Bash, Gut Gui, VS Code and Visual Studio.


Solution

  • As @DaemonPainter points out, one possibility is that the SSH identity and keys are missing. For that problem, this answer describing how to add your SSH keys may be of interest.

    My issue turned out to be the naming of the SSH key files. By default, these are in the %HOMEPATH%\.ssh folder with filenames id_rsa and id_rsa.pub. Developer tools such as Visual Studio 2019, and Git Gui expect that naming convention.

    Since my files are for a personal git repo on Github, I had named the SSH key files id_rsa_github/.pub. In %HOMEPATH%\.bashrc, the following lines were added (originally configured on another PC and copied over):

    # Start ssh-agent to allow git to be used
    eval `ssh-agent -s`
    ssh-add ~/.ssh/id_rsa_github
    

    That explains why it worked for Git Bash.

    To configure non-standard named SSH keys, follow these steps:

    1. Add a file called %HOMEPATH%\.ssh\config

    2. Edit config with contents similar to the following (use # to add comments):

      host github.com
       # My personal git repo for (something-cool)
       HostName github.com
       IdentityFile ~/.ssh/id_rsa_github
      
    3. Restart your development tools, such Visual Studio Code