Перейти к содержимому

Github token где взять

  • автор:

Как создать токен персонального доступа на github

введите сюда описание изображения

Я воспользовался командой git push и он потребовал у меня токен персонального доступа. Я начал искать, что это такое и как его получить. Везде пишут, что нужно зайти в settings, а затем в developer settings. Однако у меня нет вкладки developer settings. Как мне установить этот токен?

Отслеживать
задан 7 фев 2022 в 11:50
JasonStatham JasonStatham
1 1 1 серебряный знак 1 1 бронзовый знак
настройки профиля, а не репозитория
7 фев 2022 в 11:52

1 ответ 1

Сортировка: Сброс на вариант по умолчанию

Нужен другой settings — не проекта а пользователя (в правом верхнем углу кликаем иконку с аватаркой — в выпадающем меню в самом низу — Settings). Далее на открывшейся странице справа меню — в самом низу Developer settings. После перехода по этой ссылке откроется страница где можно создать и скопировать персональный токен. Сохраняете его в своей секретной папочке и используете в дальнейшем для авторизации. В командной строке это будет выглядеть примерно так: git push https://@github.com//.git

ссылка на генерацию токена

Но, вообще говоря, есть еще один способ сделать git push, при этом не получив «сообщений об ошибке», связанных с авторизацией. Это — так называемая «авторизация по ключам».

Обратите внимание, что в командах, которые предлагает «скопировать» github присутствует такой параметр, как протокол:

github protocols

И для https требуется токен, а для git — не требуется. Зато для git требуется импортировать публичную часть ключа в github, но это хорошо описано, например, здесь:

Управление личными маркерами доступа

You can use a personal access token in place of a password when authenticating to GitHub in the command line or with the API.

Warning: Treat your access tokens like passwords. For more information, see «Keeping your personal access tokens secure.»

About personal access tokens

Personal access tokens are an alternative to using passwords for authentication to GitHub when using the GitHub API or the command line.

Personal access tokens are intended to access GitHub resources on behalf of yourself. To access resources on behalf of an organization, or for long-lived integrations, you should use a GitHub App. For more information, see «About creating GitHub Apps.»

Types of personal access tokens

GitHub currently supports two types of personal access tokens: fine-grained personal access tokens and personal access tokens (classic). GitHub recommends that you use fine-grained personal access tokens instead of personal access tokens (classic) whenever possible.

Both fine-grained personal access tokens and personal access tokens (classic) are tied to the user who generated them and will become inactive if the user loses access to the resource.

Organization owners can set a policy to restrict the access of personal access tokens (classic) to their organization. For more information, see «Setting a personal access token policy for your organization.»

Fine-grained personal access tokens

Fine-grained personal access tokens have several security advantages over personal access tokens (classic):

  • Each token can only access resources owned by a single user or organization.
  • Each token can only access specific repositories.
  • Each token is granted specific permissions, which offer more control than the scopes granted to personal access tokens (classic).
  • Each token must have an expiration date.
  • Organization owners can require approval for any fine-grained personal access tokens that can access resources in the organization.
Personal access tokens (classic)

Personal access tokens (classic) are less secure. However, some features currently will only work with personal access tokens (classic):

  • Only personal access tokens (classic) have write access for public repositories that are not owned by you or an organization that you are not a member of.
  • Outside collaborators can only use personal access tokens (classic) to access organization repositories that they are a collaborator on.
  • Some REST API operations are not available to fine-grained personal access tokens. For a list of REST API operations that are supported for fine-grained personal access tokens, see «Endpoints available for fine-grained personal access tokens».

If you choose to use a personal access token (classic), keep in mind that it will grant access to all repositories within the organizations that you have access to, as well as all personal repositories in your personal account.

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.

Keeping your personal access tokens secure

Personal access tokens are like passwords, and they share the same inherent security risks. Before creating a new personal access token, consider if there is a more secure method of authentication available to you:

  • To access GitHub from the command line, you can use GitHub CLI or Git Credential Manager instead of creating a personal access token.
  • When using a personal access token in a GitHub Actions workflow, consider whether you can use the built-in GITHUB_TOKEN instead. For more information, see «Automatic token authentication.»

If these options are not possible, and you must create a personal access token, consider using another CLI service to store your token securely.

When using a personal access token in a script, you can store your token as a secret and run your script through GitHub Actions. For more information, see «Using secrets in GitHub Actions.» You can also store your token as a Codespaces secret and run your script in Codespaces. For more information, see «Managing your account-specific secrets for GitHub Codespaces.»

For more information about best practices, see «Keeping your API credentials secure.»

Creating a fine-grained personal access token

Note: Fine-grained personal access token are currently in beta and subject to change. To leave feedback, see the feedback discussion.

Screenshot of a user's account menu on GitHub. The menu item

  1. Verify your email address, if it hasn’t been verified yet.
  2. In the upper-right corner of any page, click your profile photo, then click Settings.

If you selected an organization as the resource owner and the organization requires approval for fine-grained personal access tokens, then your token will be marked as pending until it is reviewed by an organization administrator. Your token will only be able to read public resources until it is approved. If you are an owner of the organization, your request is automatically approved. For more information, see «Reviewing and revoking personal access tokens in your organization.»

Creating a personal access token (classic)

Note: Organization owners can restrict the access of personal access token (classic) to their organization. If you try to use a personal access token (classic) to access resources in an organization that has disabled personal access token (classic) access, your request will fail with a 403 response. Instead, you must use a GitHub App, OAuth app, or fine-grained personal access token.

Note: Your personal access token (classic) can access every repository that you can access. GitHub recommends that you use fine-grained personal access tokens instead, which you can restrict to specific repositories. Fine-grained personal access tokens also enable you to specify fine-grained permissions instead of broad scopes.

Screenshot of a user's account menu on GitHub. The menu item

  1. Verify your email address, if it hasn’t been verified yet.
  2. In the upper-right corner of any page, click your profile photo, then click Settings.

Screenshot of the

.

Deleting a personal access token

You should delete a personal access token if it is no longer needed. If you delete a personal access token that was used to create a deploy key, the deploy key will also be deleted.

Screenshot of a user's account menu on GitHub. The menu item

    In the upper-right corner of any page, click your profile photo, then click Settings.

Using a personal access token on the command line

Once you have a personal access token, you can enter it instead of your password when performing Git operations over HTTPS.

For example, to clone a repository on the command line you would enter the following git clone command. You would then be prompted to enter your username and password. When prompted for your password, enter your personal access token instead of a password.

$ git clone https://github.com/USERNAME/REPO.git Username: YOUR_USERNAME Password: YOUR_PERSONAL_ACCESS_TOKEN 

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 personal access token for every HTTPS Git operation, you can cache your personal access token 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.»

Further reading

  • «About authentication to GitHub»
  • «Token expiration and revocation»

Персональный токен для Git-репозиториев

Популярные хостинги для Git-репозиториев, такие как Bitbucket и GitLab, не позволяют взаимодействовать с системой контроля версий приложениям, авторизованным по паролю от учетной записи.

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

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

JAICP предоставляет интеграцию с GitHub и Bitbucket, которая позволяет размещать на них проекты без персонального токена. Для таких проектов токен необходим только при редактировании настроек.

Bitbucket

  1. Нажмите на свой аватар в правом верхнем углу и перейдите в меню Personal settings.
  2. Из боковой панели перейдите в App passwords.
  3. Нажмите Create app password.
    1. В поле Label введите назначение токена.
    2. В списке разрешений выберите Repositories > Write.

    GitHub

    1. Подтвердите адрес электронной почты, если он еще не подтвержден.
    2. Нажмите на свой аватар в правом верхнем углу и перейдите в меню Settings.
    3. Из боковой панели перейдите в Developer settings > Personal access tokens.
    4. Нажмите Generate new token, при необходимости введите пароль от учетной записи.
      1. В поле Note введите назначение токена.
      2. В выпадающем списке Expiration выберите срок действия токена.
      3. Выберите набор действий, которые разрешено выполнять по токену (scope).
        • Выберите repo, если среди репозиториев, с которыми вы работаете, есть приватные.
        • В противном случае вы можете выбрать только public_repo.

      GitLab

      1. Нажмите на свой аватар в правом верхнем углу и перейдите в меню Preferences.
      2. Из боковой панели перейдите в Access Tokens.
      3. Создайте новый персональный токен:
        1. В поле Token name введите назначение токена.
        2. В поле Expiration date введите дату, когда токен перестанет действовать (опционально).
        3. Выберите набор разрешений write_repository.

        Как использовать токен для Github Actions с приватными репозиториями

        В этом руководстве я покажу, как использовать API, который нам предлагает GitHub через свой токен, чтобы применить Action для непрерывного развертывания приватных репозиториев.

        Выберите пункт меню Developer settings.

        Кликните на опцию Personal access tokens.

        Нажмите на кнопку generate new token, затем скопируйте и сохраните его для дальнейшего использования.

        Создание секретных ключей

        Откройте настройки нашего проекта и нажмите на раздел Secrets. В моем случае у меня уже есть следующие секретные ключи:

        URL репозитория по API

        Для загрузки последних изменений из приватного репозитория мы будем использовать GitHub API вместе с нашим ранее сгенерированным и настроенным токеном, выглядит это следующим образом:

        git pull https://$>:x-oauth-basic@github.com/susomejias/portfolio.git master

        Пример разворачивания на VPS

        • В нашем проекте мы создаём папку с названием .github , а в папке под названием workflows будут содержаться файлы для наших Actions.
        • В данном примере мы создаём файл ci.yml , который содержит функциональность нашего Action.
        • В моем случае я показываю вам пример Action, который я использую для развертывания своего портфолио:
        name: CI on: [push] jobs: deploy: if: github.ref == 'refs/heads/master' runs-on: ubuntu-latest steps: - uses: actions/checkout@master - name: Push to server uses: appleboy/ssh-action@master with: host: $> username: $> password: $> script: cd $> && git pull https://$>:x-oauth-basic@github.com/susomejias/portfolio.git master && npm install && ng build --prod && cp htaccess dist/portfolio/

        Проверка работы

        Выполните загрузку для проверки нового Action:

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

Ваш адрес email не будет опубликован. Обязательные поля помечены *