git pushをした時のremote: Invalid username or tokenを解消した

はじめに

macbook airでgit pushをして、ユーザ名とパスワードを入力すると、以下のエラーが出た。

hiroki@shibatahiroshitakanoMacBook-Air ki-hi-ro.com % git push origin main
Username for 'https://github.com': ki-hi-ro
Password for 'https://ki-hi-ro@github.com': 
remote: Invalid username or token. Password authentication is not supported for Git operations.
fatal: Authentication failed for 'https://github.com/ki-hi-ro/ki-hi-ro.com-2022.git/'

これを解決していこう。

エラーの原因

GitHubで2021年以降、パスワードによるpushは廃止され、個人アクセストークン(PAT)を使う必要がある。

PATとは、Personal Access Tokenの略称。

解決手順1 : GitHubでトークンを発行

自分のアカウントにログインした後、プロフィールをクリックして、settingをクリックする。

左サイドバーのDeveloper settingsをクリック。

Personal access tokens > Tokens (classic)をクリック。

Generate new token (classic)をクリック。

名前を入力、有効期限を選択。

repo(リポジトリ操作用)、workflow(GitHub Actionsも使うため)にチェックを入れる。

「Generate token」のボタンをクリックして、生成されたトークンをコピー。

コピーしたトークンはメモに貼り付けておいた。

解決手順2 : Gitにトークンを登録

ターミナルに以下を入力する。

git remote set-url origin <以下で取得したweb URL>

pushするときに、先ほどのトークンを貼り付ける。

hiroki@shibatahiroshitakanoMacBook-Air ki-hi-ro.com % git push origin main
Username for 'https://github.com': ki-hi-ro
Password for 'https://ki-hi-ro@github.com': 
Enumerating objects: 7, done.
Counting objects: 100% (7/7), done.
Delta compression using up to 10 threads
Compressing objects: 100% (4/4), done.
Writing objects: 100% (4/4), 472 bytes | 472.00 KiB/s, done.
Total 4 (delta 3), reused 0 (delta 0), pack-reused 0
remote: Resolving deltas: 100% (3/3), completed with 3 local objects.
remote: 
remote: Create a pull request for 'main' on GitHub by visiting:
remote:      https://github.com/ki-hi-ro/ki-hi-ro.com-2022/pull/new/main
remote: 
To https://github.com/ki-hi-ro/ki-hi-ro.com-2022.git
 * [new branch]      main -> main

これで上手く行った。

同じリポジトリであれば、次回以降にpushする時に、ユーザー名とパスワードを入力しなくて済んだ。

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です