Bash

Fix Git SSH Permission Denied When Using Multiple Accounts

A Git push over SSH suddenly fails with a permission denied error, even though ssh -T [email protected] says you authenticated successfully. The remote server identifies your key as the wrong user or drops the connection because your client offered too many irrelevant keys before reaching the right one.

text
[email protected]: Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

Or, if your local SSH agent holds more than five keys, the failure looks like this:

text
Received disconnect from 140.82.121.4 port 22:2: Too many authentication failures
Disconnected from 140.82.121.4 port 22
fatal: Could not read from remote repository.

Why SSH Picks the Wrong Key

OpenSSH does not understand Git repositories, organizations, or repository permissions. It only understands hostnames, user names, and cryptographic keys.

When you run git push origin main against an SSH remote like [email protected]:org-corp/internal-tool.git, Git invokes ssh under the hood. It tells ssh to connect to github.com using the username git.

SSH checks your running ssh-agent. If you have keys loaded, it presents them to GitHub one by one in the order they were added. GitHub checks the public key against its entire database of user accounts. The moment a matching public key is found, GitHub says yes to the key and establishes the session under the GitHub account that owns that key.

Here is the trap. If your personal key is first in your agent, GitHub authenticates you as your personal account. Then Git requests access to org-corp/internal-tool.git. GitHub looks at your personal account, sees that it has no permissions on the corporate repository, and returns Permission denied (publickey). It never asks for a second key. SSH negotiation stops on the first accepted identity.

The second failure happens when your agent holds six or more keys. Most enterprise Git hosts, including GitHub and GitLab, configure MaxAuthTries to 6. If the agent offers five wrong keys, the server cuts the connection before your sixth, valid key is ever tested.

Inspecting the Agent State

Check what your SSH client is actually offering. Run ssh in verbose mode against the host:

bash
ssh -v -T [email protected]

Look at the lines starting with debug1: Authentications that can continue and debug1: Offering public key.

text
debug1: Offering public key: /Users/username/.ssh/id_rsa RSA SHA256:abc... agent
debug1: Server accepts key: /Users/username/.ssh/id_rsa RSA SHA256:abc... agent
debug1: Authentication succeeded (publickey).
Authenticated to github.com ([140.82.121.4]:22) using "publickey".
...
Hi personal-user! You've successfully authenticated, but GitHub does not provide shell access.

Notice the last line. The server greeted personal-user. If the repository you need belongs to work-user, every push will fail with a permission error.

To see all keys currently loaded in your agent:

bash
ssh-add -l

If you see multiple keys listed, every single SSH connection attempts to use them in that order by default.

The Fix: Host Aliases and IdentitiesOnly

The fix requires two parts: configuring distinct host aliases in ~/.ssh/config, and pointing your local Git repository to that alias instead of the default host.

Open or create ~/.ssh/config. Ensure its permissions are strictly 600:

bash
chmod 600 ~/.ssh/config

Add host configurations that separate your identities. The critical directive is IdentitiesOnly yes. This flag tells SSH to ignore keys from ssh-agent unless they match the specific IdentityFile configured for that block.

text
# Default/Personal Account
Host github.com
    HostName github.com
    User git
    IdentityFile ~/.ssh/id_ed25519_personal
    IdentitiesOnly yes
    AddKeysToAgent yes

# Work Account
Host github-work
    HostName github.com
    User git
    IdentityFile ~/.ssh/id_ed25519_work
    IdentitiesOnly yes
    AddKeysToAgent yes

Notice the second block. The Host entry is an arbitrary alias (github-work), but HostName points to the real domain (github.com). The User is explicitly set to git.

Now, update your repository remote URL to use the alias instead of github.com.

Navigate to the work repository:

bash
cd ~/code/work/internal-tool

Check the existing remote:

bash
git remote -v
text
origin  [email protected]:org-corp/internal-tool.git (fetch)
origin  [email protected]:org-corp/internal-tool.git (push)

Replace github.com with your alias github-work:

bash
git remote set-url origin git@github-work:org-corp/internal-tool.git

Verify the change in Git’s configuration:

bash
git remote -v
text
origin  git@github-work:org-corp/internal-tool.git (fetch)
origin  git@github-work:org-corp/internal-tool.git (push)

Test the connection to the alias:

bash
ssh -T git@github-work

Output:

text
Hi work-user! You've successfully authenticated, but GitHub does not provide shell access.

Now git push origin main will resolve through github-work, present exclusively ~/.ssh/id_ed25519_work, and succeed.

Automating Git Config Across Directories

Having to manually change the remote URL on every repository clone is tedious and fragile. If you forget to edit the remote URL after running git clone [email protected]:..., you run into the exact same problem.

Instead, organize your repositories by directory structure and use Git’s includeIf conditional configuration.

Assume your file system looks like this:

text
~/code/
  ├── personal/
  └── work/

Open your global Git configuration file at ~/.gitconfig:

ini
[user]
    name = Jane Doe
    email = [email protected]

[includeIf "gitdir:~/code/work/"]
    path = ~/.gitconfig-work

Create the referenced file at ~/.gitconfig-work:

ini
[user]
    name = Jane Doe
    email = [email protected]

[url "git@github-work:"]
    insteadOf = [email protected]:

The url.<base>.insteadOf setting dynamically rewrites URLs inside any repository cloned under ~/code/work/.

When you run git clone [email protected]:org-corp/internal-tool.git inside ~/code/work/, Git automatically rewrites the connection to use git@github-work:org-corp/internal-tool.git. You get the correct SSH key and the correct commit author email without manual repository adjustments.

Verify this behavior inside a work project:

bash
cd ~/code/work/test-repo
git config user.email

Output:

Gotcha 1: Trailing Slashes in Git Include Paths

Conditional includes in Git are sensitive to path formatting. If you omit the trailing slash in the gitdir directive, matching fails silently.

Broken:

ini
[includeIf "gitdir:~/code/work"]
    path = ~/.gitconfig-work

Working:

ini
[includeIf "gitdir:~/code/work/"]
    path = ~/.gitconfig-work

Without the trailing slash, Git treats ~/code/work as a file pattern rather than a directory prefix. Subdirectories like ~/code/work/project-a/.git will not trigger the include.

Additionally, if your path contains symlinks, gitdir: resolves them before matching. If ~/code is actually a symlink to /Volumes/Data/code, you must match the real path:

ini
[includeIf "gitdir:/Volumes/Data/code/work/"]
    path = ~/.gitconfig-work

Alternatively, use gitdir/i: for case-insensitive matching if you work across macOS and Linux file systems:

ini
[includeIf "gitdir/i:~/code/work/"]
    path = ~/.gitconfig-work

Gotcha 2: The macOS Keychain Silent Fallback

macOS includes its own version of OpenSSH that integrates with the system Keychain. When you use the system ssh-add --apple-use-keychain ~/.ssh/id_rsa, the OS stores the passphrase in the Keychain.

On system restarts, macOS automatically loads these keys into the agent on demand. If you have older, expired, or decommissioned keys saved in your macOS Keychain, they get offered to remote servers even if they are not explicitly configured in ~/.ssh/config.

To see keys loaded in the Apple agent:

bash
ssh-add -L

If an unwanted key appears that keeps hijacking your connection before IdentitiesOnly can intervene, remove it from the running agent:

bash
ssh-add -d ~/.ssh/id_unwanted.pub

To clear all identities from memory:

bash
ssh-add -D

To stop macOS from reloading all Keychain keys into your agent session automatically, add IgnoreUnknown UseKeychain and avoid generic wildcards in your default configuration:

text
Host *
    IdentitiesOnly yes
    AddKeysToAgent no

Keep your global Host * strict. Force every host entry to define its identity explicitly with its own IdentityFile.

Verifying the Final Setup

Verify your configuration by checking the debug handshake on both accounts.

Test personal:

bash
ssh -v -T [email protected] 2>&1 | grep "Offering public key"

Output shows only your personal key being offered:

text
debug1: Offering public key: /Users/username/.ssh/id_ed25519_personal ED25519 SHA256:... explicit

Note the word explicit at the end of the debug line instead of agent. This confirms SSH is honoring IdentitiesOnly yes and selecting only the specified file.

Test work:

bash
ssh -v -T git@github-work 2>&1 | grep "Offering public key"

Output:

text
debug1: Offering public key: /Users/username/.ssh/id_ed25519_work ED25519 SHA256:... explicit

Run a test push inside your work repository:

bash
git push --dry-run origin main
text
To github-work:org-corp/internal-tool.git
   d8e4f1a..b2c3d4e  main -> main

The connection routes through the alias, authenticates as the correct user, and completes without touching unauthorized keys.

More in Bash