Git 接続で failed: Authentication failed for … のエラーが出たときの対処法

GitGit

git clone https://~ で clone を試みる

git clone https://github.com/~~~~~~~
Username for 'https://github.com': hoge-user
Password for 'https://hoge-user@github.com':
remote: Invalid username or password.
fatal: Authentication failed for 'https://github.com/hoge-user/repository-name.git/'

github のページで repository を開いたときに右上部にある Code ボタンを押下、ssh タブをクリックしアドレスをコピーして、clone してみる

git clone git@github.com:~~~
Warning: Permanently added 'github.com,XXX.XXX.XXX.XXX' (RSA) to the list of known hosts.
Permission denied (publickey).
fatal: Could not read from remote repository.

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

エラーが出ました。

上記のエラーはいずれもアクセス権限がないということが原因です。
以下に解決する手順を記していきます。

ssh key を作成する

ssh-keygen -t rsa

上記のコマンドを実行します。
ファイル名や鍵ファイルのパスワードを聞かれるので必要があれば設定できます。
指定しなければ ~/.ssh/ ディレクトリ下に作成されます。

確認

ls ~/.ssh
id_rsa  id_rsa.pub

id_rsa (秘密鍵) と id_rsa.pub (公開鍵) が作成されました。

GitHub に公開鍵を登録する

公開鍵を GitHub に登録します

以下のコマンドを実行して出力した公開鍵をコピーします。

cat ~/.ssh/id_rsa.pub

右上部ユーザーアイコン」>「Settings」>「SSH and GPG keys」>「New SSH key

コピーした公開鍵を Key の欄に入力しタイトルを付けて保存

再度 git clone

git clone https://github.com/~~~~~~~

これでうまくリポジトリがクローンされるはず。