Api token git linux

Проверка подлинности в REST API

Вы можете пройти проверку подлинности в REST API, чтобы получить доступ к большему набору конечных точек и установить более высокий предел скорости.

Об аутентификации

Многие конечные точки REST API требуют проверки подлинности или возвращают дополнительные сведения, если вы прошли проверку подлинности. Кроме того, вы можете делать больше запросов в час при проверке подлинности.

Вы можете проверить подлинность запроса, отправив маркер в заголовке Authorization запроса. В следующем примере замените YOUR-TOKEN ссылкой на маркер:

curl --request GET \ --url "https://api.github.com/octocat" \ --header "Authorization: Bearer YOUR-TOKEN" \ --header "X-GitHub-Api-Version: 2022-11-28"

Примечание. В большинстве случаев передать маркер с помощью Authorization: Bearer или Authorization: token . Однако при передаче веб-токена JSON (JWT) необходимо использовать Authorization: Bearer .

При попытке использовать конечную точку REST API без маркера или с маркером, у которого недостаточно разрешений, вы получите 404 Not Found ответ или 403 Forbidden .

Проверка подлинности с помощью personal access token

Если вы хотите использовать REST API GitHub для личного использования, можно создать personal access token. По возможности GitHub рекомендует использовать fine-grained personal access token вместо personal access token (classic). Дополнительные сведения о создании personal access token см. в разделе Управление личными маркерами доступа.

Если вы используете personal access token (classic) для доступа к организации, которая применяет единый вход SAML для проверки подлинности, вам потребуется авторизовать маркер после создания. Fine-grained personal access tokens авторизоваться во время создания маркера, прежде чем будет предоставлен доступ к организации. Дополнительные сведения см. в разделе Авторизация личного токена доступа для использования с документами единого входа SAML.

Если вы не авторизуете personal access token (classic) для SAML SSO, прежде чем пытаться использовать его для доступа к организации, которая применяет единый вход SAML, может возникнуть 404 Not Found ошибка или 403 Forbidden . Если появляется сообщение об ошибке 403 Forbidden , вы можете следовать url-адресу в заголовке X-GitHub-SSO , чтобы авторизовать маркер. Срок действия URL-адреса истекает через час. Если вы запросили данные, которые могут поступать из нескольких организаций, API не будет возвращать результаты из организаций, которым требуется единый вход SAML. В X-GitHub-SSO заголовке будет указан идентификатор организаций, которым требуется авторизация единого входа SAML для personal access token (classic). Например: X-GitHub-SSO: partial-results; organizations=21955855,20582480 .

Проверка подлинности с помощью маркера, созданного приложением

Если вы хотите использовать API для организации или от имени другого пользователя, GitHub рекомендует использовать GitHub App. Дополнительные сведения см. в разделе Сведения о проверке подлинности с помощью Приложение GitHub.

Читайте также:  Поставить kali linux второй системой

Вы также можете создать маркер OAuth с OAuth app для доступа к REST API. Однако GitHub рекомендует использовать вместо него GitHub App. GitHub Apps обеспечивают больший контроль над доступом и разрешениями приложения.

Маркеры доступа, созданные приложениями, автоматически авторизоваться для единого входа SAML.

Использование обычной аутентификации

Некоторые конечные точки REST API для GitHub Apps и OAuth apps требуют использования обычной проверки подлинности для доступа к конечной точке. Вы будете использовать идентификатор клиента приложения в качестве имени пользователя и секрет клиента приложения в качестве пароля.

curl --request POST \ --url "https://api.github.com/authorizations" \ --user ":" \ --header "X-GitHub-Api-Version: 2022-11-28"

Вы можете найти идентификатор клиента и создать секрет клиента на странице параметров приложения. Дополнительные сведения о переходе на страницу параметров GitHub App см. в разделе Изменение регистрации Приложение GitHub.

Проверка подлинности в рабочем процессе GitHub Actions

Если вы хотите использовать API в рабочем процессе GitHub Actions, GitHub рекомендует выполнять проверку подлинности с помощью встроенного GITHUB_TOKEN вместо создания маркера. Вы можете предоставить разрешения для GITHUB_TOKEN с помощью ключа permissions . Дополнительные сведения см. в разделе Автоматическая проверка подлинности токенов.

Проверка подлинности с помощью имени пользователя и пароля

Проверка подлинности с использованием имени пользователя и пароля не поддерживается. При попытке пройти проверку подлинности с помощью имени пользователя и пароля вы получите ошибку 4xx.

Дополнительные материалы

Источник

Managing your personal access tokens

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.

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.
Читайте также:  Проверить версию openssl linux

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 «Encrypted secrets.» You can also store your token as a Codespaces secret and run your script in Codespaces. For more information, see «Managing encrypted secrets for your 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 GitHub's account menu showing options for users to view and edit their profile, content, and settings. 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 GitHub's account menu showing options for users to view and edit their profile, content, and settings. 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

Screenshot of GitHub's account menu showing options for users to view and edit their profile, content, and settings. The menu item

  1. 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

Источник

Оцените статью
Adblock
detector