- The GitHub Blog
- Token authentication requirements for Git operations
- Workflows affected
- Background
- What you need to do today
- Enabling two-factor authentication
- Brownouts
- Creating a personal access token
- Создание токена персонального доступа для командной строки
- Создание токена
- Использование токена в командной строке
- Аутентификация с GitHub с помощью токена
- Чтобы не передать «ключи от замка» .
- Accessing GitHub using two-factor authentication
The GitHub Blog
December 15, 2020
Token authentication requirements for Git operations
In July 2020, we announced our intent to require the use of token-based authentication (for example, a personal access, OAuth, or GitHub App installation token) for all authenticated Git operations. Beginning August 13, 2021, we will no longer accept account passwords when authenticating Git operations on GitHub.com.
Workflows affected
- Command line Git access
- Desktop applications using Git (GitHub Desktop is unaffected)
- Any apps/services that access Git repositories on GitHub.com directly using your password
The following customers remain unaffected by this change:
- If you have two-factor authentication enabled for your account, you are already required to use token- or SSH-based authentication.
- If you use GitHub Enterprise Server, we have not announced any changes to our on-premises offering.
- If you maintain a GitHub App, GitHub Apps do not support password authentication.
Background
We described our motivation as we announced similar changes to authenticating with the API as follows:
In recent years, GitHub customers have benefited from a number of security enhancements to GitHub.com, such as two-factor authentication, sign-in alerts, verified devices, preventing the use of compromised passwords, and WebAuthn support. These features make it more difficult for an attacker to take a password that’s been reused across multiple websites and use it to try to gain access to your GitHub account. Despite these improvements, for historical reasons customers without two-factor authentication enabled have been able to continue to authenticate Git and API operations using only their GitHub username and password.
Beginning August 13, 2021, we will no longer accept account passwords when authenticating Git operations and will require the use of token-based authentication, such as a personal access token (for developers) or an OAuth or GitHub App installation token (for integrators) for all authenticated Git operations on GitHub.com. You may also continue using SSH keys where you prefer.
Tokens offer a number of security benefits over password-based authentication:
- Unique – tokens are specific to GitHub and can be generated per use or per device
- Revocable – tokens can can be individually revoked at any time without needing to update unaffected credentials
- Limited – tokens can be narrowly scoped to allow only the access necessary for the use case
- Random – tokens are not subject to the types of dictionary or brute force attempts that simpler passwords that you need to remember or enter regularly might be
What you need to do today
- For developers, if you are using a password to authenticate Git operations with GitHub.com today, you must begin using a personal access token over HTTPS (recommended) or SSH key by August 13, 2021, to avoid disruption. If you receive a warning that you are using an outdated third-party integration, you should update your client to the latest version.
- For integrators, you must authenticate integrations using the web or device authorization flows by August 13, 2021, to avoid disruption. For more information, see Authorizing OAuth Apps and the announcement on the developer blog.
Enabling two-factor authentication
If you would like to ensure that your account does not allow password-based authentication, you can enable two-factor authentication for your account today. This will require you to use a personal access token for all authenticated operations via Git and third-party integrations.
Brownouts
To ensure all affected customers are aware of the authentication change, during two scheduled brownouts, we will temporarily disable support for password authentication, and Git operations made using a password will temporarily fail. The brownouts are scheduled for the following dates and times:
Источник
Creating a personal access token
You should create a personal access token to use in place of a password with the command line or with the API.
Note: If you use GitHub CLI to authenticate to GitHub on the command line, you can skip generating a personal access token and authenticate via the web browser instead. For more information about authenticating with GitHub CLI, see gh auth login .
Personal access tokens (PATs) are an alternative to using passwords for authentication to GitHub when using the GitHub API or the command line.
If you want to use a PAT to access resources owned by an organization that uses SAML SSO, you must authorize the PAT. For more information, see «About authentication with SAML single sign-on» and «Authorizing a personal access token for use with SAML single sign-on.»
As a security precaution, GitHub automatically removes personal access tokens that haven’t been used in a year. To provide additional security, we highly recommend adding an expiration to your personal access tokens.
A token with no assigned scopes can only access public information. To use your token to access repositories from the command line, select repo . For more information, see “Available scopes”.
Creating a token
Verify your email address, if it hasn’t been verified yet.
In the upper-right corner of any page, click your profile photo, then click Settings.
In the left sidebar, click Developer settings.
In the left sidebar, click Personal access tokens.
Click Generate new token.
Give your token a descriptive name.
To give your token an expiration, select the Expiration drop-down menu, then click a default or use the calendar picker.
Select the scopes, or permissions, you’d like to grant this token. To use your token to access repositories from the command line, select repo.
Click Generate token.
Warning: Treat your tokens like passwords and keep them secret. When working with the API, use tokens as environment variables instead of hardcoding them into your programs.
To use your token to authenticate to an organization that uses SAML SSO, authorize the token for use with a SAML single-sign-on organization.
Using a token on the command line
Once you have a token, you can enter it instead of your password when performing Git operations over HTTPS.
For example, on the command line you would enter the following:
Personal access tokens can only be used for HTTPS Git operations. If your repository uses an SSH remote URL, you will need to switch the remote from SSH to HTTPS.
If you are not prompted for your username and password, your credentials may be cached on your computer. You can update your credentials in the Keychain to replace your old password with the token.
Instead of manually entering your PAT for every HTTPS Git operation, you can cache your PAT with a Git client. Git will temporarily store your credentials in memory until an expiry interval has passed. You can also store the token in a plain text file that Git can read before every request. For more information, see «Caching your GitHub credentials in Git.»
Источник
Создание токена персонального доступа для командной строки
Вы можете создать токен доступа и использовать его вместо пароля при выполнении операций Git через HTTPS с Git в командной строке или API.
Для аутентификации в GitHub требуется токен персонального доступа в следующих ситуациях:
- Когда вы используете двухфакторную аутентификацию
- Для доступа к защищенному контенту в организации, использующей единый вход SAML (SSO). Токены, используемые с организациями, использующими SAML SSO, должны быть авторизованы.
Создание токена
1) Проверьте свой адрес электронной почты , если он еще не подтвержден.
2)В правом верхнем углу любой страницы щелкните фотографию своего профиля и нажмите «Settings» .
3) В левой боковой панели нажмите «Developer settings»
4) В левой боковой панели нажмите «Personal access tokens» и затем чтобы создать новый токен нажмите «Generate new token»
5) Задайте маркеру описание и выберите область действия или разрешения, которые нужно предоставить этому токену. Чтобы использовать маркер для доступа к репозиториям из командной строки, выберите repo.
6) Нажмите «Generate token», чтобы создать токен.
7) Скопируйте полученный токен в буфер обмена для следующего использования.
Использование токена в командной строке
Теперь, с помощью токена, вы можете ввести его вместо пароля при выполнении операций Git через HTTPS.
Например, в командной строке вы должны ввести следующее:
Источник
Аутентификация с GitHub с помощью токена
Я пытаюсь пройти аутентификацию в GitHub, используя токен личного доступа. В файлах справки на github говорится об использовании метода cURL для аутентификации ( https://help.github.com/articles/creating-an-access-token-for-command-line-use ). Я пробовал это, но все еще не могу нажать на GitHub. Обратите внимание, я пытаюсь выполнить отправку с неаутентифицированного сервера (Travis-CI).
Этот код вызывает ошибки:
удаленный: анонимный доступ к scuzzlebuzzle / ol3-1.git запрещен.
Ваша curl команда совершенно неверна. Вы должны использовать следующие
Кроме того, это не разрешает вашему компьютеру клонировать репозиторий, если он на самом деле является частным. (Однако взгляд показывает, что это не так.) Обычно вы делаете следующее:
Это добавит ваши учетные данные на пульт, созданный при клонировании репозитория. Однако, к сожалению, вы не можете контролировать, как Трэвис клонирует ваш репозиторий, поэтому вам нужно отредактировать пульт таким образом.
Это исправит ваш проект для использования пульта дистанционного управления со встроенными учетными данными.
Предупреждение: токены имеют доступ для чтения / записи и должны рассматриваться как пароли. Если вы вводите свой токен в URL-адрес клона при клонировании или добавлении пульта, Git writes it to your .git/config file in plain text, which is a security risk.
Как ни смешно, в статье рассказывается, как его создать, но совершенно не говорится, что с ним делать. Примерно через час изучения документации и Stack Overflow я наконец нашел ответ:
Я был фактически вынужден включить двухфакторную аутентификацию политикой компании, когда я работал удаленно и все еще вносил локальные изменения, так что на самом деле это было не clone мне нужно, но push . Я читал во многих местах, что мне нужно было удалить и воссоздать пульт, но на самом деле моя обычная push команда работала точно так же, как указано clone выше, и пульт не изменился:
(@YMHuang направил меня на правильный путь с помощью ссылки на документацию.)
Чтобы не передать «ключи от замка» .
Обратите внимание, что ответ sigmavirus24 требует, чтобы вы предоставили Трэвису токен с довольно широкими разрешениями — поскольку GitHub предлагает только токены с широкими областями действия, такими как «напишите все мои публичные репозитории» или «напишите все мои частные репозитории».
Если вы хотите ограничить доступ (с немного большей работой!), Вы можете использовать ключи развертывания GitHub в сочетании с зашифрованными полями yaml Travis.
Вот набросок того, как работает эта техника .
Сначала сгенерируйте вызванный ключ развертывания RSA (через ssh-keygen ) my_key и добавьте его в качестве ключа развертывания в настройки репозитория github.
Затем используйте $password файл для расшифровки ключа развертывания во время интеграции, добавив в файл yaml:
Примечание: последняя строка предварительно заполняет ключ RSA github, что позволяет избежать необходимости принимать вручную во время подключения.
Источник
Accessing GitHub using two-factor authentication
With 2FA enabled, you’ll be asked to provide your 2FA authentication code, as well as your password, when you sign in to GitHub.
With two-factor authentication enabled, you’ll need to provide an authentication code when accessing GitHub through your browser. If you access GitHub using other methods, such as the API or the command line, you’ll need to use an alternative form of authentication. For more information, see «About authentication to GitHub.»
Providing a 2FA code when signing in to the website
After you sign in to GitHub using your password, you’ll be prompted to provide an authentication code from a text message or your TOTP app.
GitHub will only ask you to provide your 2FA authentication code again if you’ve logged out, are using a new device, or your session expires.
Generating a code through a TOTP application
If you chose to set up two-factor authentication using a TOTP application on your smartphone, you can generate an authentication code for GitHub at any time. In most cases, just launching the application will generate a new code. You should refer to your application’s documentation for specific instructions.
If you delete the mobile application after configuring two-factor authentication, you’ll need to provide your recovery code to get access to your account. For more information, see «Recovering your account if you lose your two-factor authentication credentials»
Receiving a text message
If you set up two-factor authentication via text messages, GitHub will send you a text message with your authentication code.
Using two-factor authentication with the command line
After you’ve enabled 2FA, you must use a personal access token or SSH key instead of your password when accessing GitHub on the command line.
Authenticating on the command line using HTTPS
After you’ve enabled 2FA, you must create a personal access token to use as a password when authenticating to GitHub on the command line using HTTPS URLs.
When prompted for a username and password on the command line, use your GitHub username and personal access token. The command line prompt won’t specify that you should enter your personal access token when it asks for your password.
Authenticating on the command line using SSH
Enabling 2FA doesn’t change how you authenticate to GitHub on the command line using SSH URLs. For more information about setting up and using an SSH key, see «Connecting to GitHub with SSH.»
Using two-factor authentication to access a repository using Subversion
When you access a repository via Subversion, you must provide a personal access token instead of entering your password. For more information, see «Creating a personal access token.»
If you lose access to your two-factor authentication credentials, you can use your recovery codes or another recovery method (if you’ve set one up) to regain access to your account. For more information, see «Recovering your account if you lose your 2FA credentials.»
If your authentication fails several times, you may wish to synchronize your phone’s clock with your mobile provider. Often, this involves checking the «Set automatically» option on your phone’s clock, rather than providing your own time zone.
Источник