Git authentication failed for как исправить

I started experiencing this issue on Visual Studio Code in Ubuntu 20.04 yesterday.

I did not make any changes to my GitHub credentials, neither did I change anything in the project, but I run any git command to communicate with my remote branch like:

git pull origin dev

I get the error below:

remote: Repository not found.
fatal: Authentication failed for ‘https://github.com/MyUsername/my-project.git/’

Here’s what worked for me:

I tried recloning the project and then running the git pull command but it did not work.

git clone https://my-git-url

I tried setting my credentials again using the below commands but still no luck:

git config --global user.email "email@example.com"
git config --global user.name "John King"

I tried removing the remote repository and re-adding it using the below commands, but still no luck:

git remote remove origin
git remote add origin https://my-git-url

Finally, I decided to try using my default Ubuntu terminal and it worked fine. My big guess is that it’s a bug from Visual Studio Code from the last update that was made some few hours before then (See the screenshot that shows that a Release was done on the same day that I was having the issue). I mean I set up Visual Studio Code using snap, so probably it might have been updated in the background a few hours before then.

enter image description here

Hopefully, they will get it fixed and git remote operations will be fine again.

Git is a popular version control software that every developer should know how to use. But sometimes, it pops out strange errors that confuses even seasoned users. If you are seeing “Authentication failed” whenever you try to use git push command, this short article is going to help you solve this error message.

The “fatal: Authentication failed” error message indicates that the existing authentication method you have been using on your repository has become obsolete/outdated. The full error message may look like this

remote: Support for password authentication was removed on August 13, 2021. Please use a personal access token instead.
remote: Please see https://github.blog/2020-12-15-token-authentication-requirements-for-git-operations/ for more information.
fatal: Authentication failed for 'https://github.com/user/example-project.git/'Code language: JavaScript (javascript)

Or if you’re pushing to your remote repository via HTTPS, the error message may look like this

If you enabled two-factor authentication in your Github account you won't be able to push via HTTPS using your accounts password. Instead you need to generate a personal access token. This can be done in the application settings of your Github account. Using this token as your password should allow you to push to your remote repository via HTTPS. Use your username as usual.

Usually, the “Authentication Failed” error happens if you recently enabled 2-Factor Authentication on your GitHub account and uses HTTPS to push/pull in Git at the same time. GitHub deprecates the password authentication method from August 13, 2021 to favor more secure way of authentication. In this article, we will show you several possible ways to get around the “fatal: Authentication failed” problem.

Switch to SSH protocol in Git

As being said earlier, Github is no longer allow authenticating via HTTPS URLs once 2-Factor Authentication (2FA) enabled. Git with HTTPS uses public-key encryption-based authentication for doing every action like git push, git clone, git fetch and git pull, etc. Meanwhile, SSH protocol allows Git to securely transfer repository data over the internet.

In order to quickly fix “fatal: Authentication failed”, you can remove the existing origin (which is something like https://github.com:user/repo.git) and re-add a [email protected]:user/repo.git URL to instruct Git to use SSH instead. Run the following command to do so:

git remote -v
git remote remove origin
git remote add origin [email protected]:user/repo.git

If you didn’t set up the necessary private keys for Git, running the commands above will end up with an error message. You may need to consult access Github repositories using SSH keys and Connecting to GitHub with SSH for instructions on adding private keys.

git remote add origin with SSH

Create a PAT (Personal Access Token)

When you connect to a GitHub repository from Git, you’ll need to authenticate with GitHub using either HTTPS or SSH. Alternatively, you can use Github CLI with the command gh auth login. All of these authentication method requires a PAT (Personal Access Token) that is a more secure alternative to passwords. Follow the instructions below to create a PAT :

First, login to your account. In the upper right corner of the page, look for your avatar, click it and select Settings.

In the Settings page, choose Developer settings > Developer settings > Personal access tokens in the left sidebar.

Personal access tokens

Click Generate new token in order to create a new PAT. You will be able to name the token, set its expiration date and its scope. For a token that specifically for managing repositories, you should limit the scope to repo.

Limit PAT scope

Finally, click Generate token. You would be redirected to another page which shows you the newly created token. Remember that the token will only be shown once. If you lost the token, you have no way to recover it but to re-generate a new one.

Treat your tokens like passwords and keep them in a secure place. The token should be stored in an environment variable instead of hardcoding them into your programs/applications source code.

Once you’re done creating a token, you have to reset the old password authentication by running the following command.

git config --global --unset credential.helperCode language: PHP (php)

You may also need to update your repository to change the protocol from HTTPS to native SSH

git remote -v
git remote remove origin
git remote add origin [email protected]:user/repo.git

Disable Github 2-Factor Authentication

If you recently enabled 2-Factor Authentication(2FA) on your GitHub account right before the “Authentication Failed” error pops up, you can try disabling it to quickly fix the problem.

However, remember that disabling 2FA significantly increase the risk of your account to be compromised. Also, If you’re a member, billing manager, or outside collaborator to a public repository of an organization that requires two-factor authentication and you disable 2FA, you’ll be automatically removed from the organization, and you’ll lose your access to their repositories. In order to regain access to the organization, you have to re-enable 2FA and re-apply to the organization.

To disable 2FA for an account, you need to log into it, then click your profile photo in the upper right corner and select Settings.

Settings icon in the user bar

Then, select Account Security in the left sidebar and click Disable in Two-factor authentication section.

Disable two-factor authentication button Github

Remove saved credentials on Windows

Windows users may beed to change your login or password of the Git service account stored in Windows Credential Manager.

First, you need to search for Windows Credential Manager from the Start menu. Usually it is placed in Control Panel if you use Windows 7 and Settings on newer Windows versions.

On the Credential Manager window, click on Windows Credentials tab and look for anything that starts with git: or ada:. In order to remove them, you would have to click each of them to open the details view and click Remove.

You may also need to remove them from Generic Credentials, too.

Remove saved credentials from Windows Credential Manager

We hope that the information above helps you solve the “fatal: Authentication failed” error message in Git. You may want to check out our other guide on fixing other popular Git issues such as Git : how to accept all current/incoming changes, How to clone a private repository in Github or How to access GitHub from inside China.



я использую Github на некоторое время, и я был в порядке с git add,git commit и git push пока без проблем. Внезапно у меня возникает ошибка, которая говорит:

fatal: аутентификация не удалась

в терминале я клонировал репозиторий, работал над файлом, а затем использовал git add чтобы добавить файл в журнал фиксации и когда я сделал git commit, он работал нормально. Наконец,git push просит имя пользователя и пароль. Я положил их правильно и каждый раз, когда я это делаю, он говорит ту же ошибку.

кто-нибудь знает, в чем причина этой проблемы и как я могу это исправить?

содержание .git/config являются:

[core]
repositoryformatversion = 0
filemode = true
bare = false
logallrefupdates = true
[remote "origin"]
url = http://www.github.com/######/Random-Python-Tests
fetch = +refs/heads/*:refs/remotes/origin/*
[branch "master"]
remote = origin
merge = refs/heads/master
[user]
name = #####
email = ############


7111  


25  

25 ответов:

Если вы включили двухфакторную аутентификацию в своей учетной записи Github, вы
не удастся нажать через HTTPS с помощью пароля учетной записи. Вместо
вам необходимо создать личный маркер доступа. Это можно сделать в
настройки приложения вашей учетной записи Github. Использование этого токена в качестве вашего
пароль должен позволять вам нажимать на ваш удаленный репозиторий через HTTPS.
Используйте свое имя пользователя как обычный.

https://help.github.com/articles/creating-a-personal-access-token-for-the-command-line/

вам также может потребоваться обновить источник для вашего репозитория, если установлено значение https:

git remote -v 
git remote remove origin 
git remote add origin [email protected]:user/repo.git  

чтобы изменить или удалить сохраненные учетные данные, выполните следующие действия:

  1. Нажмите Кнопку Пуск
  2. Тип: Диспетчер Учетных Данных
  3. посмотреть Windows Credentials Manager ярлык и дважды щелкните его, чтобы открыть приложение.
  4. после того, как приложение открыто, нажмите на Windows Credentials tab.
  5. найдите учетные данные, которые вы хотите удалить / обновить, они будут начинаться с “git:” и могут начинаться с “ada:”
  6. нажмите на учетные данные запись, он откроет детальный вид записи. 7. Нажмите кнопку Изменить или удалить при необходимости и подтвердите.
  7. мыть, полоскать, повторять по мере необходимости.

enter image description here

во-первых, вы можете убедиться, что используете правильный url:

git remote set-url origin https://github.com/zkirkland/Random-Python-Tests.git

тогда, если он работал раньше, и если он не просил вас имя пользователя, это должно быть потому, что вы сохранили свои учетные данные (логин/пароль) в , а пояснил, что. Вы можете дважды проверить эти настройки и убедиться, что ваш прокси-сервер, если он у вас есть, не изменился.

Если это все еще не работает, вы можете переключиться на ssh url:

git remote set-url origin [email protected]:zkirkland/Random-Python-Tests.git

но это означает, что вы опубликовали свой открытый ключ ssh в своем Настройки учетной записи.

это работает для меня, и он также помнит мои учетные данные:

  1. Run gitbash

  2. укажите на каталог РЕПО

  3. Run git config --global credential.helper wincred

возможно, вы недавно изменили пароль для своей учетной записи git
Вы могли бы попробовать git push С -u опции

git push -u origin branch_name_that_you_want_to_push

после выполнения вышеуказанной команды он попросит пароль предоставить ваш обновленный пароль

надеюсь, что это может помочь вам

Я думаю, что по какой-то причине GitHub ожидает, что URL-адрес не будет иметь поддомена www. Когда я использую (например)

git remote set-url origin https://www.github.com/name/repo.git

Он дает следующие сообщения:

remote: Anonymous access to name/repo.git denied
fatal: Authentication failed for https://www.github.com/name/repo.git

однако, если я использую

git remote set-url origin https://github.com/name/repo.git

он работает отлично. Для меня это не имеет особого смысла… но я думаю не забудьте поместить www в удаленный URL для репозиториев GitHub.

также обратите внимание на URL-адреса клонов, предоставленные на веб-странице репозитория GitHub не включает в себя www.

Если вы обнаружили проблему с ошибкой аутентификации при вводе правильного пароля и имени пользователя, это проблема git. Чтобы решить эту проблему при установке git на вашем компьютере снимите флажок Включить git credential managerenter image description here

в основном мои учетные данные были просрочены, и я столкнулся с вышеуказанной проблемой.

следующая команда 2 помогла мне:

git config --global --unset credential.helper

git config credential.helper store

он будет запрашивать у вас учетные данные в следующий раз, когда вы попытаетесь нажать.

следуйте приведенным ниже рекомендациям для получения более подробной информации о защищенном и незащищенном хранении имени пользователя и пароли:

https://git-scm.com/docs/git-credential-store

https://git-scm.com/docs/git-credential-cache

Я столкнулся
“$ git fetch
неустранимо: ошибка проверки подлинности для ‘ http://….”
после того, как мой пароль windows истек и был изменен. Несколько выборок, перезагрузка и даже переустановка git с помощью диспетчера учетных данных windows не помогли.

удивительно правильный ответ где-то здесь в комментариях, но не в ответы (и некоторые из них действительно странные!).
Вам нужно перейти в Панель управления – > Диспетчер учетных данных / учетные данные Windows
и обновить пароль для ГИТ:http://yourrepoaddress

у меня была та же проблема. Я установил url таким образом:

git remote set-url origin https://github.com/zkirkland/Random-Python-Tests.git

Я также удалил из конфигурационного файла эту запись:askpass = /bin/echo.
Затем “git push” попросил меня ввести имя пользователя и пароль, и на этот раз это сработало.

Я не совсем уверен, что я сделал, чтобы получить эту ошибку, но делать:

git remote set-url origin https://...

не работает для меня. Однако:

git remote set-url origin [email protected]:user/repo

как-то работал.

для меня, я забыл, что я изменил пароль на Github.com, и мой брелок для аутентификации оболочки никогда не обновлялся до этого нового пароля. Удаление всего git из моей связки ключей, а затем повторное выполнение запроса git помогло решить проблему, снова предложив мне новый пароль.

просто чтобы перезвонить здесь, что исправило проблему для меня, я просто отменил первоначальное приглашение, ssh открылся с моей учетной записью bitbucket, я ввел пароль там, и все работало, как ожидалось.

Я столкнулся с той же проблемой на windows. Большую часть времени я обычно сталкиваюсь с проблемой из-за использования нескольких учетных записей git. Если вы находитесь в windows, откройте терминал от имени администратора и повторите попытку запуска команд. Убедитесь, что у вас есть права администратора.

Привет я получал ту же ошибку я пробовал все решения в зависимости от того, что упоминается на этой странице, но не работает. Наконец, я нашел решение, поэтому подумал о его публикации. Пожалуйста, поправьте меня, если я где-то ошибаюсь. Такие ошибки возникают, если иногда ваш системный пароль изменился в последнее время в любое время. Он будет пытаться проверить от старого пароля. Поэтому выполните следующие действия: перейти к панели управления – > нажмите на учетные записи пользователей -> в разделе Диспетчер учетных данных – > перейти к управлению учетными данными windows -> Перейдите к общим учетным данным – > разверните вкладку git server – > нажмите кнопку Удалить из хранилища

Я также столкнулся с ошибкой (вот почему я приземлился здесь), но ни одно из предложений не сработало для меня. Это был мой первый раз, когда я пытаюсь развернуть локальный Git в azure. Когда я получил эту ошибку, я сбросил свои учетные данные (щелкнув ссылку в Azure) после нескольких попыток. Проблема в том, что на данный момент он говорит мне, что мое имя пользователя уже занято, поэтому я также изменил свое имя пользователя на другое. В конце концов, я вручную удалил .папка git на моем локальном диске и повторно развернула ее без проблема.

Постановка Задачи: “git fatal authentication failed”. Я использую оба.

устранение:
Я просто удалил пользователя из управления доступом bitbucket, а затем добавил того же пользователя. Этот.файл gitconfig прост

[user]
    name = BlaBla
    email = [email protected]

[push]
    default = simple

с правильными учетными данными, если проблема превалирует

Если вы используете AndroidStudio 2.1 beta, то его ошибка, обновление до beta 2 (3 mb update file), это сработало для меня

убедитесь, что у вас есть разрешение на запись нажать.

read ***write*** admin 

убедитесь, что ваш ключ ssh добавлен в ваш текущий сеанс ssh.

  1. скопировать вывод cat ~/.ssh/id_rsa.pub к вашим настройкам GitHub под ключами SSH и GPG.

  2. обновите текущую сессию ssh с помощью ssh-add ~/.ssh/id_rsa.pub

Я использую Windows Powershell с установленным Openssh.

Если вы включили двухфакторную аутентификацию в своей учетной записи Github, войдите в свою учетную запись GitHub и перейдите по ссылке: https://github.com/settings/tokens/new
чтобы создать новый маркер доступа, скопируйте его и вставьте в качестве пароля для аутентификации в терминале.

в Android studio canary build 3.1+, Если вы используете Android studio git tool, чем вы можете использовать следующее:

  • нажмите на Android Studio
  • нажмите на Настройки…
  • перейти в VersionControl – > Github
  • здесь измените тип аутентификации на пароль
  • этот шаг потребует от вас ввести логин и пароль. Введите имя пользователя github логин s и пароль github в качестве пароля.
  • нажмите на кнопку Тест.

Если соединение успешно, чем вы сделали, и вы можете использовать android studio GitHub UI client.

Если вы находитесь в windows и пытаетесь нажать на сервер windows, на котором пользователи домена работают как пользователи репозитория( TFS), попробуйте войти в URL-адрес TFS (т. е. http:tfs) с IE. введите учетные данные учетной записи домена и позвольте странице появиться.

осторожностью используйте только INTERNET EXPLORER! другие браузеры не изменят учетные данные вашей системы.

Теперь перейдите в git bash и измените удаленного пользователя для репозитория, как показано ниже:

git config user.name "domainNameuserName"

и Done, теперь вы можете нажать!

Если вы используете ssh и клонированы с https это не будет работать. Клон с SSH, а затем нажмите и тянет должен работать, как ожидалось!

thumb

После включения двухфакторной аутентификации в моей учётной записи GitHub, когда Я запускаю команду Git git push она выдаёт следующее сообщение об ошибке:

$ git push
Username for 'https://github.com': Username
Password for 'https://Username@github.com':
remote: Invalid username or password.
fatal: Authentication failed for 'https://github.com/username/repository.git/'

Что вызывает эту ошибку

Это сообщение об ошибке говорит само за себя. Это означает то, что мы пытаемся использовать неверное имя пользователя или пароль. Но Я уверен в том, что использую правильное имя пользователя и пароль. В моём случае, это произошло со мной после того, как Я включил двухфакторную аутентификацию (2FA) в моём аккаунте GitHub. Поэтому я знаю о том, что вызвало это сообщение об ошибке.

Как это решить

Как только мы узнали о том, что вызывает сбой работы git, мы можем использовать это для решения проблемы. Это действительно простой процесс. Для того, чтобы решить эту проблему, нам нужно всего лишь создать личный token доступа GitHub и использовать его вместо нашего пароля GitHub и двухфакторного кода аутентификации. Теперь пошаговое руководство.


Создание token доступа к персональному доступу GitHub.

В правом верхнем углу любой страницы нажмите на фотографию своего профиля, затем нажмите Settings.

В левой боковой панели нажмите Developer settings.

В левой боковой панели нажмите Personal access tokens.

Нажмите Generate new token.

Дайте вашему token имя (любое имя описывающее цель его создания).

Выберите области действия или разрешения, которые вы хотите предоставить этому token. Для того, чтобы использовать ваш token для доступа к репозиториям из командной строки, выберите repo.

Нажмите Generate token.

Скопируйте token в буфер обмена. По соображениям безопасности, после ухода со страницы, вы не сможете снова увидеть token.

Как исправить: fatal: Authentication failed for https://github.com/

Примечание! Относитесь к своим token’ам, как к паролям и держите их в тайне (если вы не хотите, чтобы другие люди использовали API от вашего имени). При работе с API, используйте token’ы как переменные окружения вместо hardcoding их в ваши программы.


Использование token в командной строке.

Как только у нас появился token, мы можем ввести его вместо нашего пароля при выполнении операций Git через HTTPS. Просто введите свой token после запроса пароля, а затем смотрите на то, как происходит магия…

Username: your_username
Password: your_token

Примечание! Token’ы личного доступа могут использоваться только для операций HTTPS Git. Если ваш репозиторий использует удалённый URL SSH, вам нужно будет переключить управление с SSH на HTTPS.

Примечание! Если вам не будет предложено ввести имя пользователя и пароль, ваши учетные данные могут быть кэшированы на вашем компьютере. Вы можете обновить свои учетные данные в Keychain заменить старый пароль на token.

Заключение

Вот и всё, готово. Теперь проблема возникшая после включения двухфакторной аутентификации в учётной записи GitHub устранена. Так просто, не так ли?

Если у вас возникают проблемы в устранении этой проблемы с помощью приведенной выше инструкции, но вы смогли решить эту проблему любым другим способом, пожалуйста, опишите его в разделе комментариев ниже. Спасибо!

Я надеюсь, что эта статья помогла вам узнать, как решить проблему которая возникла после включения двухфакторной аутентификации в учётной записи GitHub. Если эта статья помогла вам решить проблему, пожалуйста, оставьте комментарий :smiley:

Спасибо за прочтение!

This article focuses on discussing how to solve git error (remote: Invalid username or password / fatal: Authentication failed). The approach will be to create a dummy example project file and upload it to the Git Repository properly without the following error.

Prerequisites: Git Repository, GitBash, Git Clone

Step By Step Solution

Step 1: Creating git repository and installing GitBash

You will first create a git repository where you will be pushing all your project files. And for that, you need to be installed with GitBash too (How to Install Gitbash and How to Work and Push Code on Git Repository?)

Once you are familiar with the above things, you can now move ahead with the article which will be focusing on the git error (remote: Invalid username or password / fatal: Authentication failed).

Step 2: For demonstration purposes, we have created a dummy git repository that looks something like the image attached below.

Creating dummy git repo

Creating dummy git repo 

Created successfully and prompted with quick setup

Created successfully and prompted with quick setup

Following image attached below shows the files which we are gonna upload to the GitHub repository.

DEMO FILES

DEMO FILES

Step 3: Checking whether GitBash has been installed on our machine successfully or not.

Checking GitBash

Checking GitBash

Step 4: Once Steps 2 and 3 is been done

If while doing step 2 i.e. following the quick setup tutorial or the article which is attached in step 1 on how git works, if you are prompted with the error (remote: Invalid username or password / fatal: Authentication failed) i.e. as shown in the image attached below. Then this article is gonna focus on that error only.

error

error

Step 5: Solve the error

A) Go to settings in your Github account >> Developer settings >> Personal access token >> Tokens (classic) >> Generate new token. See the images attached below for a better understanding.

A) 1

A) 2

A) 3

A) 4

For generating tokens you can follow up on this article (How to Create GitHub Personal Access Token).

B) Once you are ready with the token go again to your GitBash terminal and execute the push command. You will be redirected to a popup as shown in the image below:

POPUP

POPUP

C) Next, here in the pop-up tab you can:

  1. Simply copy and paste the token which you have generated just now.
  2. Or, you can go ahead and click on Sign in with your browser.

Once that is done you have finally reached your destination, you will be redirected to a new page saying, see the image below.

Succeded

Succeeded

Once this is done close the tab and go to GitBash again and you will see the error is been solved and all the files must be uploaded successfully.

UPLOADED successfully

UPLOADED Successfully

You can also visit the GitHub repository and see your files have been uploaded successfully without the error (remote: Invalid username or password / fatal: Authentication failed).

Verifying by visiting GitHub repo (UPLOADED successfully)

Verifying by visiting the GitHub repo (UPLOADED successfully)

In this way, you can add your Project files to the GitHub repository without the git error i.e. (remote: Invalid username or password / fatal: Authentication failed).

Last Updated :
07 Feb, 2023

Like Article

Save Article

Добавить комментарий