Github personal access token

Github personal access token

Где хранить токен доступа от GitHub?

Нужно ли хранить токен локального доступа где-то локально на машине после его создания в GitHub?

Если да, есть ли какой-либо предпочтительный способ его хранения?

git github access-token

4 ответа

3 Решение VonC [2018-07-24 21:33:00]

Половина паролей — это то, что (в идеале) вы их запоминаете, а система хэширует их, поэтому они никогда не хранятся в текстовом формате.
Тем не менее, система доступа к персональному доступу GitHub, похоже, в основном заставляет вас хранить токен в виде обычного текста?

Во-первых, PAT (Personal Access Token) — это не простой пароль, а эквивалент, который:

  • вы можете создать несколько раз (например, по одному на машину, с которой вам нужно получить доступ к репозиторию GitHub)
  • вы можете отменить в любой момент (с веб-интерфейса GitHub), что делает этот PAT устаревшим, даже если он задерживается на одной из этих машин.

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

Поскольку PAT можно использовать вместо пароля при выполнении операций Git через HTTPS с Git в командной строке или API, вы можете использовать помощник учетных данных git для безопасного кэширования.
Например, в Windows, который будет использовать диспетчер учетных данных Windows, доступ через GCM-Git Credential Manager для Windows.

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

Аналогичная идея применима к Mac с брелками OSX, а Linux — к GNOME Keyring.
Идея остается: хранить PAT в зашифрованном хранилище учетных данных.

1 nbari [2018-07-25 13:30:00]

Мне нравится держать их зашифрованными в репозитории и загружать их с помощью .envrc (https://direnv.net/)

Для этого я использую ssh-vault для шифрования данных, используя мои ssh-ключи, которые GitHub уже разоблачает, например:

Тогда содержимое .envrc выглядит примерно так:

Это позволит расшифровать данные в my-encrypted-vars.ssh файл и установить MY_TOKEN в моих переменных окружения каждый раз, когда я cd в реж проекта.

Делая это, токены/переменные хранятся «безопасно» и всегда готовы к использованию в качестве переменных среды

1 memo [2018-07-24 15:05:00]

В основном я сделал это на своей машине:

Скрипт моего профиля немного отличается от описанного:

Ну, вы должны где-то сохранить токен, когда вы не хотите вводить его каждый раз, когда ваше приложение запрашивает его: -)

Хорошим решением является использование переменных среды, как уже было предложено в одном комментарии.

Но вы все равно должны установить переменную окружения где-нибудь.
В Windows (который я использую) вы можете использовать диалоговое окно в системных настройках (я не знаю, есть ли у других операционных систем что-то подобное).

Я не делаю этого, я предпочитаю script в своем проекте.
В частном проекте вы можете передать это правилу источника, но это зависит от предпочтения.

В одном из моих личных проектов я также называю API GitHub, используя токен доступа. Это приложение командной строки, и конечный пользователь сохранит токен в файле конфигурации (это нормально).

Но мне нужен токен для разработки, потому что у проекта есть интеграционные тесты, где я называю API GitHub.

И этот проект является общедоступным в GitHub, поэтому я не смог сохранить токен в исходном элементе управления.

Читать еще:  Access формат даты в запросе

Я сделал следующее:

  • У меня есть пакетный файл (помните, я нахожусь в Windows) под названием environment-variables.bat , который устанавливает все необходимые переменные среды, включая токен доступа
  • Я называю это в build script и в пакетный файл Я использую для запуска своих тестов
  • environment-variables.bat игнорируется в исходном управлении
  • Но в контроле источника там environment-variables.bat.sample вместо этого, который содержит то же самое, но поддельный токен/пароль.

Поэтому я могу просто переименовать этот файл в environment-variables.bat , заменить поддельный пароль на реальный, и все будет работать.

Это не идеальное решение для всех случаев.

В моем проекте у меня есть проблема, что в будущем мне нужно будет использовать больше токенов/паролей для большего количества API.

Creating a personal access token for the command line

You can create a personal access token and use it in place of a password when performing Git operations over HTTPS with Git on the command line or the API.

In this article

A personal access token is required to authenticate to GitHub Enterprise when 2FA is enabled on your account.

Creating a token

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.

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.

to copy the token to your clipboard. For security reasons, after you navigate off the page, you will not be able to see the token again.

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.

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.

Accessing github https repos, without typing credentials everytime.

When as a user you have many accounts in all sorts of places, you reach a point where you are tired of typing in an email/username and password every time. To solve this inconvenience, most of us choose to either:

  • remember password on the browser.
  • store passwords in a keychain e.g. lastpass.
  • use the same password everywhere.
  • sign up for services using our facebook, twitter or google accounts.

While these are all good options for most web accounts, they do not apply when you are using the terminal to access a resource like github over https.

As a programmer using github, you often have to interact with it several times in a day, and when you have to retype your credentials that often it gets frustrating. To work around this problem when working with https repo addresses, you can use personal access tokens, or the credential helper tool in git (requires version 1.7.10 and later).

Personal Access Tokens

The personal access token is similar to the Oauth tokens with the exception that this does not require you to set up two-factor authentication.

  1. Create a token in your github account accessible on the url: https://github.com/settings/tokens/new
  2. On this page you type in a description, and select the scope for the token. The scope is simply defining the limit of the token how much can a person authenticated with the token do on the repo.
  3. Once the scope and description are set, then you are ready to generate a new token by clicking on the Generate token button.
  4. Once the token is generated, copy it and save it somewhere safe, like in the credential helper or keyring e.g. gnome keyring file. This is because the token is not displayed again to you.
Читать еще:  Маска ввода даты в access

Now when accessing your repo on github from the terminal, you change your repo origin string to look like below as described in this stack overflow reply (http://stackoverflow.com/questions/18935539/authenticate-with-github-using-token):

But what if I forget my token? The good news is that on the Personal Access Tokens page (https://github.com/settings/tokens) you can edit the token and either update it or regenerate it. The not so good news is that if you had already used the token on several applications, they will need to be updated too. This is why you keep the token safe 🙂

Credential helper

Git itself has a credential helper which can be used to store your credentials in the cache for your interactions with github. This requires that your git version is 1.7.10 or newer. You can check what version you are running on linux by typing:

To set up the credential helper on git. Follow these steps as outlined on the github help pages (https://help.github.com/articles/caching-your-github-password-in-git/).

By default, Git will cache your password for 15 minutes.

  1. On the command line, enter the following:

2. To change the default password cache timeout, enter the following:

Thats it! You are now good to make your pull, push commands from the terminal to github over https without a hassle.

Hope you found this useful, leave a comment on your thoughts. Lets keep discovering Linux together.

GitHub

KnisterPeter

vscode-github README

This vscode extension integrates with GitHub.

Note: I recommend to use GitHub Pull Requests instead of this, because most usecases are supported and there is a team at Microsoft/GitHub supporting development

Features

Currently it is possible to do the following:

  • Checkout one of the open pull requests
  • Open github page for the current project in your default browser
  • Browse one of the open pull requests in your default browser
  • Browse the pull requests of your current branch
  • Display pull request and current status (e.g. mergeable, travis build done, . ) in the StatusBar (if enabled)
  • Create a new pull request based on the current branch and the last commit The current branch will be requested to merge into master and the pull request title is the commit message summary, or a custom message if configured that way.
  • Create a pull request in forked repositories
  • Allow to select a branch to create a pull request for
  • Merge current pull request with either of ‘merge’, ‘squash’ or ‘rebase’ method.
  • Configure default branch, merge method and refresh interval.
  • Allow to manage assignees for pull requests
    • Assign or unassign a user (currently only one)
  • Allow to create and cancel pull request reviews
  • Support for GitHub Enterprise (on-premise installations)
  • Browse open issues
  • Browse the current open file (including current cursor position)
  • Configure the statusbar behaviour by setting the github.statusBarCommand configuration value.
  • Specify a GitLab private access token and connect to a GitLab server
  • Support multi folder setup

Setup Personal Access Token

To use this extension one needs to create a new GitHub Personal Access Token and registers it in the extension. The ‘GitHub: Set Personal Access Token’ should be executed for that. To execute the ‘GitHub: Set Personal Access Token’ type Ctrl+Shift+p in VSCode to open the command palette and type ‘GitHub: Set Personal Access Token’. You will then be prompted to enter the token generated from GitHub.

Читать еще:  Маски ввода в access примеры

Additionally, by default this extension assumes your remote for a checked out repo is named «origin». If you wish to use a remote with a different name, you can control this by the github.remoteName setting.

There are additional settings for this extension as well, enter github. in the User Settings pane of VS Code to see them all.

Pushing to remote Git repository from a build

Sometimes during the build (say, on successful build) you need to make a commit to Git repo and push it back to your remote repository. This could be a new tag as well which could be used to kick off deployment or mark a release.

Running something on successful builds is not a problem. Just add to your appveyor.yml :

Note: AppVeyor checks out only the last commit and not the entire branch. So you may have to check out the wanted branch: git checkout master

But the main question here is how to authenticate Git commands. If you try using any Git command against remote repository you’ll get stuck build because Git is asking for credentials. In most cases you can’t supply username/password in command line (we are not considering the case when credentials are embedded in repo URL as this is bad).

Two methods to access remote Git repository exist: SSH and credentials store. The scenario with custom SSH key is described in this article (with the only difference is that the key should be deployed under GitHub user account, not repo, to have write access).

This article will demonstrate how to use Git credential store to avoid Git asking for credentials and stalling the build. We will be using GitHub as a repository provider, however described technique could be applied to any Git hosting.

Creating GitHub Personal Access Token

Of course, you can use your GitHub username/password to authenticate, but there is a better approach — Personal Access Tokens which:

  1. Could be easily revoked from GitHub UI;
  2. Have a limited scope;
  3. Can be used as credentials with Git commands (this is what we need).

The scope needed is public_repo for a public repository or repo for a private repository.

Configuring build secure variable with access token

Encrypt access token on “Encrypt configuration data” page in AppVeyor (AccountEncrypt YAML) and then put it as secure variable into your appveyor.yml , for example:

Enabling Git credential store

Git doesn’t preserve entered credentials between calls. However, it provides a mechanism for caching credentials called Credential Store. To enable credential store we use the following command:

Adding access token to credential store

Default credential store keeps passwords in clear text (this is OK for us as build worker is private and not re-used or shared between builds). The storage represents a single %USERPROFILE%.git-credentials file where each line has a form of:

For example, for GitHub access token it will be:

When authenticating with access token x-oauth-basic is used as a stub password.

To append that line to .git-credentials we use the following PowerShell command:

Note: $HOME is an automatic variable available in powershell on Windows and Linux and is therefore cross-platform. If you currently use cmd: you can use %USERPROFILE% instead.

.git-credentials is very “sensitive” to a new line that must be n . If you try appending a line with something more “natural” like echo https://%access_token%:x-oauth-basic@github.com>> %USERPROFILE%.git-credentials it won’t work because rn will be used.

Indicate git user name and mail

You have to indicate your git user name and mail:

Updating remote

If you are pushing to the same private repository the build was cloned from you should probably update its remote or add a new one using HTTPS protocol.

IT Новости из мира ПК
Добавить комментарий