token github что это
About authentication to GitHub
In this article
You can securely access your account’s resources by authenticating to GitHub, using different credentials depending on where you authenticate.
About authentication to GitHub
To keep your account secure, you must authenticate before you can access certain resources on GitHub. When you authenticate to GitHub, you supply or confirm credentials that are unique to you to prove that you are exactly who you declare to be.
You can access your resources in GitHub in a variety of ways: in the browser, via GitHub Desktop or another desktop application, with the API, or via the command line. Each way of accessing GitHub supports different modes of authentication.
Authenticating in your browser
You can authenticate to GitHub in your browser in different ways.
If you’re a member of an enterprise with managed users, you will authenticate to GitHub in your browser using your IdP. For more information, see «Authenticating as a managed user» in the GitHub Enterprise Cloud documentation. If you’re not a member of an enterprise with managed users, you will authenticate using your browser on GitHub.com.
Username and password only
Two-factor authentication (2FA) (recommended)
Authenticating with GitHub Desktop
You can authenticate with GitHub Desktop using your browser. For more information, see «Authenticating to GitHub.»
Authenticating with the API
You can authenticate with the API in different ways.
Authenticating with the command line
You can access repositories on GitHub from the command line in two ways, HTTPS and SSH, and both have a different way of authenticating. The method of authenticating is determined based on whether you choose an HTTPS or SSH remote URL when you clone the repository. For more information about which way to access, see «About remote repositories.»
You can work with all repositories on GitHub over HTTPS, even if you are behind a firewall or proxy.
If you authenticate without GitHub CLI, you must authenticate with a personal access token. When Git prompts you for your password, enter your personal access token (PAT) instead. Password-based authentication for Git has been removed, and using a PAT is more secure. For more information, see «Creating a personal access token.» Every time you use Git to authenticate with GitHub, you’ll be prompted to enter your credentials to authenticate with GitHub, unless you cache them a credential helper.
You can work with all repositories on GitHub over SSH, although firewalls and proxys might refuse to allow SSH connections.
If you authenticate without GitHub CLI, you will need to generate an SSH public/private keypair on your local machine and add the public key to your account on GitHub.com. For more information, see «Generating a new SSH key and adding it to the ssh-agent.» Every time you use Git to authenticate with GitHub, you’ll be prompted to enter your SSH key passphrase, unless you’ve stored the key.
Authorizing for SAML single sign-on
To use a personal access token or SSH key to access resources owned by an organization that uses SAML single sign-on, you must also authorize the personal token or SSH key. For more information, see «Authorizing a personal access token for use with SAML single sign-on» or «Authorizing an SSH key for use with SAML single sign-on.»
GitHub’s token formats
GitHub issues tokens that begin with a prefix to indicate the token’s type.
Token type | Prefix | More information |
---|---|---|
Personal access token | ghp_ | «Creating a personal access token» |
OAuth access token | gho_ | «Authorizing OAuth Apps» |
User-to-server token for a GitHub App | ghu_ | «Identifying and authorizing users for GitHub Apps» |
Server-to-server token for a GitHub App | ghs_ | «Authenticating with GitHub Apps» |
Refresh token for a GitHub App | ghr_ | «Refreshing user-to-server access tokens» |
Help us make these docs great!
All GitHub docs are open source. See something that’s wrong or unclear? Submit a pull request.
Создание токена персонального доступа для командной строки
Вы можете создать токен доступа и использовать его вместо пароля при выполнении операций Git через HTTPS с Git в командной строке или API.
Для аутентификации в GitHub требуется токен персонального доступа в следующих ситуациях:
Создание токена
3) В левой боковой панели нажмите «Developer settings»
4) В левой боковой панели нажмите «Personal access tokens» и затем чтобы создать новый токен нажмите «Generate new token»
5) Задайте маркеру описание и выберите область действия или разрешения, которые нужно предоставить этому токену. Чтобы использовать маркер для доступа к репозиториям из командной строки, выберите repo.
6) Нажмите «Generate token», чтобы создать токен.
7) Скопируйте полученный токен в буфер обмена для следующего использования.
Использование токена в командной строке
Теперь, с помощью токена, вы можете ввести его вместо пароля при выполнении операций Git через HTTPS.
Например, в командной строке вы должны ввести следующее:
Automatic token authentication
In this article
GitHub provides a token that you can use to authenticate on behalf of GitHub Actions.
About the GITHUB_TOKEN secret
At the start of each workflow run, GitHub automatically creates a unique GITHUB_TOKEN secret to use in your workflow. You can use the GITHUB_TOKEN to authenticate in a workflow run.
Before each job begins, GitHub fetches an installation access token for the job. The token expires when the job is finished.
The token is also available in the github.token context. For more information, see «Contexts.»
Using the GITHUB_TOKEN in a workflow
Example 1: passing the GITHUB_TOKEN as an input
This example workflow uses the labeler action, which requires the GITHUB_TOKEN as the value for the repo-token input parameter:
Example 2: calling the REST API
You can use the GITHUB_TOKEN to make authenticated API calls. This example workflow creates an issue using the GitHub REST API:
Permissions for the GITHUB_TOKEN
For information about the API endpoints GitHub Apps can access with each permission, see «GitHub App Permissions.»
The following table shows the permissions granted to the GITHUB_TOKEN by default. People with admin permissions to an enterprise, organization, or repository, can set the default permissions to be either permissive or restricted. For information on how to set the default permissions for the GITHUB_TOKEN for your enterprise, organization, or repository, see «Enforcing policies for GitHub Actions in your enterprise,» «Disabling or limiting GitHub Actions for your organization,» or «Managing GitHub Actions settings for a repository.»
Scope | Default access (permissive) | Default access (restricted) | Maximum access by forked repos |
---|---|---|---|
actions | read/write | none | read |
checks | read/write | none | read |
contents | read/write | read | read |
deployments | read/write | none | read |
id-token | read/write | none | read |
issues | read/write | none | read |
metadata | read | read | read |
packages | read/write | none | read |
pull requests | read/write | none | read |
repository projects | read/write | none | read |
security events | read/write | none | read |
statuses | read/write | none | read |
Modifying the permissions for the GITHUB_TOKEN
You can see the permissions that GITHUB_TOKEN had for a specific job in the «Set up job» section of the workflow run log. For more information, see «Using workflow run logs.»
You can use the permissions key in your workflow file to modify permissions for the GITHUB_TOKEN for an entire workflow or for individual jobs. This allows you to configure the minimum required permissions for a workflow or job. When the permissions key is used, all unspecified permissions are set to no access, with the exception of the metadata scope, which always gets read access.
You can use the permissions key to add and remove read permissions for forked repositories, but typically you can’t grant write access. The exception to this behavior is where an admin user has selected the Send write tokens to workflows from pull requests option in the GitHub Actions settings. For more information, see «Managing GitHub Actions settings for a repository.»
The two workflow examples earlier in this article show the permissions key being used at the workflow level, and at the job level. In Example 1 the two permissions are specified for the entire workflow. In Example 2 write access is granted for one scope for a single job.
For full details of the permissions key, see «Workflow syntax for GitHub Actions.»
How the permissions are calculated for a workflow job
The permissions for the GITHUB_TOKEN are initially set to the default setting for the enterprise, organization, or repository. If the default is set to the restricted permissions at any of these levels then this will apply to the relevant repositories. For example, if you choose the restricted default at the organization level then all repositories in that organization will use the restricted permissions as the default. The permissions are then adjusted based on any configuration within the workflow file, first at the workflow level and then at the job level. Finally, if the workflow was triggered by a pull request from a forked repository, and the Send write tokens to workflows from pull requests setting is not selected, the permissions are adjusted to change any write permissions to read only.
Granting additional permissions
Help us make these docs great!
All GitHub docs are open source. See something that’s wrong or unclear? Submit a pull request.
Creating a personal access token
In this article
You should create a personal access token to use in place of a password with the command line or with the API.
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.
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 более 100 тысяч проектов, в которых в открытом виде хранятся токены, криптографические ключи и другие секретные данные. Всего в общем доступе оказалось более полумиллиона таких объектов, из них более 200 тысяч — уникальные. Причем периодически там попадаются токены сгенерированные крупными компаниями, такими как Google, Amazon MWS, Twitter, Facebook, MailChimp, MailGun, Stripe, Twilio, Square, Braintree и Picatic.
GitHub — это самый популярный ресурс для совместной разработки. Он позволяет хранить программный код в репозиториях с открытым или ограниченным доступом, советоваться с коллегами, привлекать их к тестированию программ и пользоваться готовыми наработками. Это значительно упрощает и ускоряет создание приложений и сервисов, поэтому многие программисты охотно прибегают к нему. Компании, создающие продукты на базе open-source кода активно используют его в работе. Кроме того, он часто используется компаниями из соображений «прозрачности».
Однако при загрузке кода в GitHub следует соблюдать особую осторожность — о чем разработчики, к сожалению, помнят не всегда.
Какие данные попали в общий доступ?
В открытом доступе на GitHub оказались блоки кода, содержащие токены и ключи, которых достаточно, чтобы проходить авторизацию и выполнять определенные действия от имени пользователей или приложений. Так, среди опубликованной секретной информации были:
Чем грозит утечка токенов и криптоключей?
Несанкционированный доступ к вашим аккаунтам, даже ограниченный, — серьезная угроза для бизнеса. Вот несколько примеров.
Один из возможных сценариев преступного применения опубликованных на GitHub токенов — рассылки и посты от имени опубликовавшей их компании. Злоумышленник может, например, получить доступ к корпоративному сайту или аккаунту в Facebook или Twitter и разместить там вредоносное объявление или фишинговую ссылку. Поскольку официальные сайты и аккаунты традиционно считаются надежными источниками информации, велик риск, что многие читатели будут уверены в безопасности такой публикации.
Кроме того, преступники могут распространить по вашему листу рассылки фишинговую рассылку (например, если вы пользуетесь MailChimp). Как и в предыдущем сценарии, расчет здесь на доверие пользователей к рассылке серьезной компании, на которую они к тому же добровольно подписались. Подобного рода атаки могут серьезно повредить репутации компании, привести к потере клиентов и затратам на восстановление нормального режима работы.
Как секретные данные попали на GitHub?
Как показал анализ результатов исследования, не только молодые и неопытные программисты оставляют в открытом доступе конфиденциальную информацию. Например, данные, дающие доступ к сайту крупного правительственного учреждения, разместил на GitHub разработчик с 10-летним стажем.
Причины публикации токенов и всевозможных ключей в хранилищах GitHub могут быть разными. Средства авторизации могут потребоваться, в частности, для интеграции приложения с каким-либо сервисом. Но чаще, это просто невнимательность программиста.
Кроме того, разработчики могут просто не задумываться о том, что оставлять токены в хранилищах GitHub рискованно и нужно прицельно искать и удалять (или заменять) их перед размещением там кода.
Как защитить свои ресурсы?
Чтобы вашими токенами или ключами не воспользовались злоумышленники, мы рекомендуем вам: