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.»
Источник
Где хранить персональный токен доступа из GitHub?
необходимо ли хранить маркер личного доступа где-то локально на машине после его генерации в GitHub?
Если да, есть ли способ, где он может храниться?
4 ответов
половина смысла паролей заключается в том, что (в идеале) вы запоминаете их, и система хэширует их, поэтому они никогда не хранятся нигде в обычном тексте.
Тем не менее, личная система токенов доступа GitHub, похоже, в основном заставляет вас хранить токен в обычном тексте?
во-первых, a PAT (персональный токен доступа) — это не простой пароль, а эквивалент, который:
- вы можете генерировать несколько раз (например, один на машина, с которой вам нужно получить доступ к репозиторию GitHub)
- вы можете отменить в любое время (из веб-интерфейса GitHub), что делает этот ПЭТ устаревшим, даже если он задерживается на одной из этих машин.
это отличается от вашего пароля, который уникален для вашей учетной записи и не может быть легко изменен без необходимости его изменения, а также везде, где вы его используете.
Так как ПЭТ может использоваться вместо пароль при выполнении операций Git через HTTPS с Git в командной строке или API вы можете использовать git credential helper надежно кэшировать.
Например, в Windows это будет использовать диспетчер учетных данных Windows доступ через GCM — Git менеджер учетных данных — для Windows.
при первом нажатии на репо всплывающее окно запросит ваши учетные данные: username и ваш ПОХЛОПЫВАНИЕ.
В следующий раз он не будет спрашивать и повторно использовать непосредственно этот PAT, который остается надежно сохраненным в Вашем менеджере учетных данных.
аналогичная идея применяется для Mac с OSX брелок, и Linux с брелок GNOME.
Идея остается: хранить PAT в зашифрованные хранилище учетных данных.
Ну, вы должны сохранить маркер где-то, когда вы не хотите вводить его каждый раз, когда приложение попросит об этом 🙂
хорошим решением является использование переменных среды, как уже отмечалось в комментарий.
но вы все равно должны установить переменную окружения где-то.
В Windows (которую я использую) вы можете использовать поле в настройках системы (Я не знаю, есть ли другие операционные системы что-то похожее).
я этого не делаю, я предпочитаю сценарий в своем проекте.
В частном проекте вы мая зафиксируйте это в системе управления версиями, но это вопрос предпочтения.
в одном из моих личных проектов я также вызываю API GitHub, используя личный токен доступа.
Это приложение командной строки, и конечный пользователь сохранит токен в файле конфигурации (что нормально).
но мне нужен маркер для разработка также, потому что в проекте есть интеграционные тесты, где я вызываю API GitHub.
и этот проект является общедоступным на GitHub, поэтому я не смог сохранить токен в системе управления версиями.
вот что я сделал:
- у меня есть пакетный файл (помните, я на Windows) под названием environment-variables.bat , который устанавливает все необходимые переменные среды, включая маркер доступа
- я называю это в мой создать скрипт и в the пакетным файлом Я использую для запуска моих тестов
- environment-variables.bat is игнорируется в системе управления версиями
- но в системе управления версиями, есть environment-variables.bat.sample вместо этого, который содержит то же самое, но поддельный токен/пароль.
поэтому я могу просто переименовать этот файл в environment-variables.bat заменить поддельные пароль, и все работает.
Это не идеальное решение для всех случаев, хотя.
в моем проекте у меня есть проблема, что мне нужно использовать больше токенов/паролей для большего количества API в будущем.
Источник
Создание токена персонального доступа для командной строки
Вы можете создать токен доступа и использовать его вместо пароля при выполнении операций 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.
Например, в командной строке вы должны ввести следующее:
Источник
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.»
Источник