Where to store my Git personal access token?
Asked Answered
R

18

383

Is it necessary to store the personal access token somewhere locally on the machine after generating it in GitHub?

If yes, is there any preferred way where it could be stored?

Rector answered 9/10, 2017 at 11:54 Comment(10)
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. See number 8 from the official docs: help.github.com/articles/…Sundries
Exactly, I saw that comment when generating the access token, but I was not sure how people keep them safe in practice.Chyou
This seems so strange to me. Half the point of passwords is that (ideally) you memorise them and the system hashes them, so therefore they're never stored anywhere in plain text. Yet GitHub's personal access token system seems to basically force you to store the token in plain text?Cryometer
May I ask - why do you need to store them? Maybe there are alternatives that do not require you to store them locally...Habitforming
They are auto generated and long, so memorising them is not an option.Chyou
There seems to be a more up-to-date variant of that referenced by @bytestorm: sudo apt-get install libsecret-1-0 libsecret-1-dev; cd /usr/share/doc/git/contrib/credential/libsecret; sudo make; git config --global credential.helper /usr/share/doc/git/contrib/credential/libsecret/git-credential-libsecret; Have a look here: https://mcmap.net/q/13472/-how-to-use-git-with-gnome-keyring-integrationLawlor
It seems GitHub just disabled password authentication for git push and now enforces using a token instead. So now we have to store the token in plain text or use a credential helper to store it for you. In any case, a person accessing your computer now has write access to your repo. - Back when I could just use a password that I have to enter every time, this particular security risk did not exist. And let's not forget that someone who knows my password could easily use that to create their own tokens. So in terms of security we don't gain anything, unless GitHub also decides to enforce 2FA.Nonego
@Nonego You could create a custom credential management script that stores your password using whatever encryption algorithm you prefer.Smashup
Yes, I could do that. Then the attacker can decide if he gets my GitHub password to create a new token or if he gets my credetial manager password. Everything I gained is a new attack vector compared to when I didn't have to use tokens.Nonego
Maybe I should write a custom push script that asks for my github user+password, uses it to log into my acc and creates a new token every time before doing a git push. The fact that this is possible shows how absurd the token enforcement is.Nonego
A
246

Half the point of passwords is that (ideally) you memorize them and the system hashes them, so therefore they're never stored anywhere in plain text.
Yet GitHub's personal access token system seems to basically force you to store the token in plain text?

First, a PAT (Personal Access Token) is not a simple password, but an equivalent that:

  • you can generate multiple time (for instance, one per machine from which you need to access GitHub repository)
  • you can revoke at any time (from the GitHub web interface), which makes that PAT obsolete, even if it lingers around on one of those machines.

That differs from your password, which is unique to your account, and cannot be easily changed without having to also modify it everywhere you happen to use it.


Since a PAT can be used in place of a password when performing Git operations over HTTPS with Git on the command line or the API, you can use a git credential helper to cache it securely.
On Windows, for instance, that would use the Windows Credential Manager, through the GCM -- Git Credential Manager -- for Windows, Mac or Linux:

git config --global credential.helper manager-core
# Git 2.39+
git config --global credential.helper manager

(manager-core is being replaced by/renamed as manager for Git 2.39+, Q4 2022)

The first time you are pushing to a repo, a popup will ask for your credentials: username and your PAT.
The next time, it won't ask, and reuse directly that PAT, which remains stored securely in your Credential Manager.

A similar idea applies for Mac with the OSX keychain, and Linux with the GNOME Keyring (in 2021, it would need a DBus session and libsecret), but in 2021, GCM-Core covers those use cases.
The idea remains: store the PAT in an encrypted credentials store.


As mentioned above, the more modern solution (Q4 2020) is Microsoft Git-Credential-Manager-Core, or, Q4 2022, Microsoft Git-Credential-Manager

git config --global credential.helper manager-core
# Git 2.39+:
git config --global credential.helper manager

Before Git 2.39 (Q4 2022), for Linux:

You need for that to install git-credential-manager-core, downloading its latest release, like gcmcore-linux_amd64.2.0.474.41365.deb

sudo dpkg -i <path-to-package>
git-credential-manager-core configure

Although, with GCM (Git-Credential-Manager-Core) on Linux, as noted by Mekky Mayata in the comments, you need to define a git config --global credential.credentialStore first.

See "Credential stores on Linux":

There are four options for storing credentials that Git Credential Manager (GCM) manages on Linux platforms:

By default, GCM comes not configured.
You can select which credential store to use by setting the GCM_CREDENTIAL_STORE environment variable, or the credential.credentialStore Git configuration setting.

As noted by agent18 in the comments, using git-credential-libsecret after installing libsecret-1-0 and libsecret-1-dev is a good first step.
But, again, that should be now wrapped by credential-manager-core (before Git 2.39).

Arlie answered 24/7, 2018 at 18:33 Comment(35)
The GNOME Keyring solution you linked does not work for Ubuntu 20.04, as the libgnome-keyring-dev package is not available in that suite. Is this what you meant by Linux support is not fully implemented yet? What recommended workarounds are there, and where can I check the progress being made?Inculcate
@Mxt The GCM-Core does support now Linux (github.com/microsoft/Git-Credential-Manager-Core/blob/master/…), do it is now the official workaround.Arlie
The last two lines give me the following error after git push: /var/tmp/.net/user/git-credential-manager-core/unqypyc0.awl/git-credential-manager-core get: 1: /var/tmp/.net/user/git-credential-manager-core/unqypyc0.awl/git-credential-manager-core: not foundFootlights
@IlyaPalachev Do you have installed git-credential-manager-core? Is it in your $PATH?Arlie
Yes: $ dpkg -l | grep gcm gives me ii gcmcore 2.0.318.44100 amd64Footlights
@IlyaPalachev Do you find git-credential-manager-core anywhere on your system?Arlie
@Arlie I have it with ".dll" extension: /var/tmp/.net/user/git-credential-manager-core/unqypyc0.awl/git-credential-manager-core.dllFootlights
@IlyaPalachev Did you install a Windows version?Arlie
@Arlie I downloaded GCM Linux deb package from official GCM GitHub releases page, gcmcore-linux_amd64.2.0.318.44100.deb - I used wget to download and dpkg -i to install.Footlights
@Arlie So, should I create an issue on GCM repository for that?Footlights
@IlyaPalachev yes, creating an issue is a good idea: let me know of the issue number, I will follow it.Arlie
upon running the above commands on Linux, it worked fine but I got "fatal: No credential backing store has been selected." solved this by editing the git config file git config -e --global and adding a credentialStore value (plaintext, gpg, secretservice) to it. thanks @ArlieIlluminometer
@Illuminometer Good point. I have edited the answer to make that step more visible for Linux, adding the relevant documentation.Arlie
But that cache will only work for 600 seconds (by default) and then if we forget it we have to re-generate a new token which doesn't make sense! Am I misunderstanding something?Evangelin
@Evangelin I thought it was 900, not 600: git-scm.com/docs/git-credential-cache#Documentation/…. And you would then need to enter the same token again. An expired cache does not invalidate an existing PAT.Arlie
@Arlie I was wrong it's 900. Thank you. Yes of course, I know that the PAT will not be affected by the cache, what's strange is that it's not a real solution to be used by humans. Maybe if it's an app it makes sense, but I won't remember such a token and I won't even save it somewhere on my computer because that's very inconvenient and slow to have to copy paste it all the time. In my opinion using ssh keys is the only good solution if GitHub is going to not allow the passwords.Evangelin
@Evangelin If you use the Git Credential Manager Core (and a cache credential.credentialStore), I don't think the default timeout would apply though. I need to test that.Arlie
Please look here for stellar instructions on how to "store" the PAT securely and work with the git workflow.Bee
@Bee Thank you. I have included your comment in the answer for more visibility.Arlie
Hi @VonC, I didn't use the "Credential manager" I think. I don't understand them. I have detailed my answer below. Please do have a look and improve it if you can.Bee
@Bee It is "manager-core", not "manager". And it will wrap whatever secret manager is used by the underlying OS. For Linux: github.com/microsoft/Git-Credential-Manager-Core/issues/…Arlie
This SO link provided the solution for me: stackoverflow.com/questions/13385690/…Isthmus
@Isthmus Thank you. I have edited the answer to include a link to the post you mention. But the right solution in 2021 is the one I detail above: git config --global credential.helper manager-core, with, on Linux, an additional credential.credentialStore configured. It does work well and is a cross-platform credential helper.Arlie
still not convinced why PAT in this form have to be used by everyone. Why not allow multiple passwords and make them revocable. Or let users create a PAT instead of using random strings. life would much easier.Quadrangle
@Quadrangle A password cannot be rescinded like a PAT can. And don't forget the PAT format has recently changed (I had to regenerate mine recently): github.blog/changelog/…Arlie
So, basically, If I lose my secret token, I can any time login to the web interface using my password and generate a new token ?Pelagian
@Programmer Yes, that is the idea.Arlie
@Arlie thank you, I am relieved ! ;) Thought I can't access my GitHub account anymore if I lose that token …Pelagian
broken link @ "Credential Stores on Linux" : linuxcredstores.md moved to credstores.mdSmoulder
@Smoulder Thank you. I have edited the answer accordingly and restored the link.Arlie
I think the answer could be simplifiedCassity
git: 'credential-manager-core' is not a git command. See 'git --help'.Ayres
@Ayres It will be, if your PATH (%PATH%? $PATH? What is your OS) includes /path/to/git/mingw64/bin. Note that manager-core is being deprecated and replaced with manager.Arlie
what about when using PAT in github workflows? where to store it? hard-coded in the .yml file?Hormuz
@Hormuz First, check if you actually need a PAT, considering a GitHub workflow would have an automatic token authentication, through the GITHUB_TOKEN secret.Arlie
S
270

In my case, in Ubuntu, the accepted solution didn't work with a message like

git: 'credential-manager' is not a git command

but store instead of manager worked well:

git config --global credential.helper store

Note that you will be prompted to introduce your credentials again the next time you use git before the credential manager saves them.

Scop answered 1/11, 2020 at 12:51 Comment(6)
Just to add a note to this - after enabling this you will be prompted for your creds on your next commit. After that, they are stored.Eightfold
This seems to store your token in plain text in ~/.git-credentialsPricket
I find it really helpful when people provide atleast a link after making a warning about something. Please look here for stellar instructions on how to "store" the PAT securely and work with the git workflow. Just 3 lines of code.Bee
Just a quick tip, remove --global if you want this configuration for only a specific repoHinman
After lots of messing around I ended up using github's ssh instead of http (docs.github.com/en/authentication/connecting-to-github-with-ssh)Havelock
What this does is that it sets up Git to store the personal access token next time you push it, so it's normal if it doesn't ask for the personal access token directly. Next time you push you will still have to specify the personal access token, but the times after that you won't.Falciform
A
246

Half the point of passwords is that (ideally) you memorize them and the system hashes them, so therefore they're never stored anywhere in plain text.
Yet GitHub's personal access token system seems to basically force you to store the token in plain text?

First, a PAT (Personal Access Token) is not a simple password, but an equivalent that:

  • you can generate multiple time (for instance, one per machine from which you need to access GitHub repository)
  • you can revoke at any time (from the GitHub web interface), which makes that PAT obsolete, even if it lingers around on one of those machines.

That differs from your password, which is unique to your account, and cannot be easily changed without having to also modify it everywhere you happen to use it.


Since a PAT can be used in place of a password when performing Git operations over HTTPS with Git on the command line or the API, you can use a git credential helper to cache it securely.
On Windows, for instance, that would use the Windows Credential Manager, through the GCM -- Git Credential Manager -- for Windows, Mac or Linux:

git config --global credential.helper manager-core
# Git 2.39+
git config --global credential.helper manager

(manager-core is being replaced by/renamed as manager for Git 2.39+, Q4 2022)

The first time you are pushing to a repo, a popup will ask for your credentials: username and your PAT.
The next time, it won't ask, and reuse directly that PAT, which remains stored securely in your Credential Manager.

A similar idea applies for Mac with the OSX keychain, and Linux with the GNOME Keyring (in 2021, it would need a DBus session and libsecret), but in 2021, GCM-Core covers those use cases.
The idea remains: store the PAT in an encrypted credentials store.


As mentioned above, the more modern solution (Q4 2020) is Microsoft Git-Credential-Manager-Core, or, Q4 2022, Microsoft Git-Credential-Manager

git config --global credential.helper manager-core
# Git 2.39+:
git config --global credential.helper manager

Before Git 2.39 (Q4 2022), for Linux:

You need for that to install git-credential-manager-core, downloading its latest release, like gcmcore-linux_amd64.2.0.474.41365.deb

sudo dpkg -i <path-to-package>
git-credential-manager-core configure

Although, with GCM (Git-Credential-Manager-Core) on Linux, as noted by Mekky Mayata in the comments, you need to define a git config --global credential.credentialStore first.

See "Credential stores on Linux":

There are four options for storing credentials that Git Credential Manager (GCM) manages on Linux platforms:

By default, GCM comes not configured.
You can select which credential store to use by setting the GCM_CREDENTIAL_STORE environment variable, or the credential.credentialStore Git configuration setting.

As noted by agent18 in the comments, using git-credential-libsecret after installing libsecret-1-0 and libsecret-1-dev is a good first step.
But, again, that should be now wrapped by credential-manager-core (before Git 2.39).

Arlie answered 24/7, 2018 at 18:33 Comment(35)
The GNOME Keyring solution you linked does not work for Ubuntu 20.04, as the libgnome-keyring-dev package is not available in that suite. Is this what you meant by Linux support is not fully implemented yet? What recommended workarounds are there, and where can I check the progress being made?Inculcate
@Mxt The GCM-Core does support now Linux (github.com/microsoft/Git-Credential-Manager-Core/blob/master/…), do it is now the official workaround.Arlie
The last two lines give me the following error after git push: /var/tmp/.net/user/git-credential-manager-core/unqypyc0.awl/git-credential-manager-core get: 1: /var/tmp/.net/user/git-credential-manager-core/unqypyc0.awl/git-credential-manager-core: not foundFootlights
@IlyaPalachev Do you have installed git-credential-manager-core? Is it in your $PATH?Arlie
Yes: $ dpkg -l | grep gcm gives me ii gcmcore 2.0.318.44100 amd64Footlights
@IlyaPalachev Do you find git-credential-manager-core anywhere on your system?Arlie
@Arlie I have it with ".dll" extension: /var/tmp/.net/user/git-credential-manager-core/unqypyc0.awl/git-credential-manager-core.dllFootlights
@IlyaPalachev Did you install a Windows version?Arlie
@Arlie I downloaded GCM Linux deb package from official GCM GitHub releases page, gcmcore-linux_amd64.2.0.318.44100.deb - I used wget to download and dpkg -i to install.Footlights
@Arlie So, should I create an issue on GCM repository for that?Footlights
@IlyaPalachev yes, creating an issue is a good idea: let me know of the issue number, I will follow it.Arlie
upon running the above commands on Linux, it worked fine but I got "fatal: No credential backing store has been selected." solved this by editing the git config file git config -e --global and adding a credentialStore value (plaintext, gpg, secretservice) to it. thanks @ArlieIlluminometer
@Illuminometer Good point. I have edited the answer to make that step more visible for Linux, adding the relevant documentation.Arlie
But that cache will only work for 600 seconds (by default) and then if we forget it we have to re-generate a new token which doesn't make sense! Am I misunderstanding something?Evangelin
@Evangelin I thought it was 900, not 600: git-scm.com/docs/git-credential-cache#Documentation/…. And you would then need to enter the same token again. An expired cache does not invalidate an existing PAT.Arlie
@Arlie I was wrong it's 900. Thank you. Yes of course, I know that the PAT will not be affected by the cache, what's strange is that it's not a real solution to be used by humans. Maybe if it's an app it makes sense, but I won't remember such a token and I won't even save it somewhere on my computer because that's very inconvenient and slow to have to copy paste it all the time. In my opinion using ssh keys is the only good solution if GitHub is going to not allow the passwords.Evangelin
@Evangelin If you use the Git Credential Manager Core (and a cache credential.credentialStore), I don't think the default timeout would apply though. I need to test that.Arlie
Please look here for stellar instructions on how to "store" the PAT securely and work with the git workflow.Bee
@Bee Thank you. I have included your comment in the answer for more visibility.Arlie
Hi @VonC, I didn't use the "Credential manager" I think. I don't understand them. I have detailed my answer below. Please do have a look and improve it if you can.Bee
@Bee It is "manager-core", not "manager". And it will wrap whatever secret manager is used by the underlying OS. For Linux: github.com/microsoft/Git-Credential-Manager-Core/issues/…Arlie
This SO link provided the solution for me: stackoverflow.com/questions/13385690/…Isthmus
@Isthmus Thank you. I have edited the answer to include a link to the post you mention. But the right solution in 2021 is the one I detail above: git config --global credential.helper manager-core, with, on Linux, an additional credential.credentialStore configured. It does work well and is a cross-platform credential helper.Arlie
still not convinced why PAT in this form have to be used by everyone. Why not allow multiple passwords and make them revocable. Or let users create a PAT instead of using random strings. life would much easier.Quadrangle
@Quadrangle A password cannot be rescinded like a PAT can. And don't forget the PAT format has recently changed (I had to regenerate mine recently): github.blog/changelog/…Arlie
So, basically, If I lose my secret token, I can any time login to the web interface using my password and generate a new token ?Pelagian
@Programmer Yes, that is the idea.Arlie
@Arlie thank you, I am relieved ! ;) Thought I can't access my GitHub account anymore if I lose that token …Pelagian
broken link @ "Credential Stores on Linux" : linuxcredstores.md moved to credstores.mdSmoulder
@Smoulder Thank you. I have edited the answer accordingly and restored the link.Arlie
I think the answer could be simplifiedCassity
git: 'credential-manager-core' is not a git command. See 'git --help'.Ayres
@Ayres It will be, if your PATH (%PATH%? $PATH? What is your OS) includes /path/to/git/mingw64/bin. Note that manager-core is being deprecated and replaced with manager.Arlie
what about when using PAT in github workflows? where to store it? hard-coded in the .yml file?Hormuz
@Hormuz First, check if you actually need a PAT, considering a GitHub workflow would have an automatic token authentication, through the GITHUB_TOKEN secret.Arlie
S
48

Alternatively, you can create a ~/.netrc file in home directory and save your login credentials to it.

cat ~/.netrc
machine github.com login <login-id> password <token-password>
Slumberous answered 28/7, 2021 at 10:35 Comment(12)
Please provide a detailed explanation to your answer, in order for the next user to understand your answer better.Carlsbad
This works like a charm and is very practical. +1. And to me, the answer is clear enough.Guru
Excellent!! It worked great. Can you please add little more explanation what going behind.Irradiate
This is a goddamn arcane wizardy. How does it exactly work? Is it safe?Doorpost
On executing the command, cat ~/.netrc Receiving this error, 'cat' is not recognized as an internal or external command, operable program or batch file.Toby
Details of netrc file and its link with inetutils are explained in this link. gnu.org/software/inetutils/manual/html_node/…Slumberous
@JwalaKumar just create a file in your linux home directory with name .netrc and have the contents as shown in the answer. If you are using windows then please try this stackoverflow.com/questions/6031214/…Slumberous
@Doorpost libcurl supports the older and deprecated netrc standard. Since git is linked to libcurl its able to make http, smtp, and ftp requests using one's .netrc. The syntax is well documented. But one does not use it because its a flat file that even with 0600 perms sits on the filesystem with passwords in clear text that every process ran as that user can abutraily read.Crossbow
while clever use of libcurl's support for netrc. down voted for reasons above.Crossbow
Excellent!! It worked great with git and github.com(PAT).Atlantic
Very well. I have tested it on the Ubuntu 20.04.4 LTS. Its worked out well for me. Thanks a lot, it have saved my time.Providenciaprovident
This stores credentials in ~/.netrc, which is just as good as the answer above which stores credentials in ~/.git-credentials. Use at your own risk, but that can be handy nonetheless.Elan
P
36

To store your credentials in cache and avoid logging in every time you perform a git action, follow these steps:

  1. Navigate to your local repository folder.
  2. In the current folder's terminal: git config --global --replace-all credential.helper cache
  3. Perform git push or git pull.
  4. Login with username and access token (access token is your password). The token can be setup in GitHub and have access to repo, workflow, write:packages and delete:packages.
  5. Repeat git push or any git action and you'll find that it doesn't ask for login credentials from now on.
Pathe answered 13/10, 2021 at 17:33 Comment(0)
B
28

Tested on Ubuntu 20.04, almost fresh install, with Git 2.25.1 and unity 7.5.

Authentication basics

Github needs an authentication key (with certain rights tied to said authentication key). A particular auth key has certain rights, (read private repos, read write public repos etc...) and "acts as a password" coupled with rights which can be revoked whenever the user wants.

Personal Access Token

  1. We start with making a PAT. I.E., Settings --> Developer Settings--> Persaonl access tokens --> Generate new token --> Note --> set permissions (repo,repo_hook maybe) --> generate token
  2. git push the repo and type the generated token(very long password) as password when asked.

Storing the password in different ways

    • Can be done in a file and then using xclip to bring it back to clipboard and paste it everytime (Screw this)
    • Cache with the help of git commands git config credential.helper cache <time-limit-of-cache>. But you still have to somehow clipboard the password after the timelimit.
    • Store it permanently in a file with git commands git config credential.helper store (don't use --global). This is NOT ENCRYPTED. You can open the file and read it. (e.g., If someone gets access to your laptop they can pretty much read the Password using a bootable USB (assuming your whole system is not encrypted)).
    • Or go the encryption route as per here. It is not complicated at all. 3 simple steps.
sudo apt-get install libsecret-1-0 libsecret-1-dev
sudo make --directory=/usr/share/doc/git/contrib/credential/libsecret
    
git config credential.helper /usr/share/doc/git/contrib/credential/libsecret/git-credential-libsecret

This allows to store the password/personal access token in an encrypted format. The git config file can be found in the .git/config file in your loca repo as shown here, if you ever need it.

P.S. There are many places that suggest the use of Gnome-keyring but that is apparently deprecated.

Storing passwords/PATs for more than one account

This becomes tricky and it appears as @VonC suggests that we need a Git-Credential-Manager core (GCM core). This answer is enhanced based on my findings in this answer.

  1. First install GCM core

    1. Download latest .deb package
    2. sudo dpkg -i <path-to-package>
    3. git-credential-manager-core configure
    4. git config --global credential.credentialStore secretservice as we use libsecret
  2. Get latest git

    In my case I had git 2.25 and got error error: unknown option 'show-scope'. It appears that GCM core is using higher git (atleast 2.26).

    So install the latest and greatest git as per here:

     sudo add-apt-repository ppa:git-core/ppa
     sudo apt-get update
     apt list git # shows the latest git currently 2.31
     sudo apt-get install git #or sudo apt-get upgrade
    
  3. Update git remote path with username built in

    GCM core needs this to identify the different accounts.:(

     git remote set-url origin https://[email protected]/user1/myRepo1.git
     git remote set-url origin https://[email protected]/user1/myRepo1.git
                                   ^^^^^
    

Your ~/.gitconfig file will thus have the following :

[credential]
   helper = /usr/bin/git-credential-manager-core
   credentialStore = secretservice
[credential "https://dev.azure.com"]
   useHttpPath = true
Bee answered 2/5, 2021 at 19:56 Comment(4)
I had to use git config --global credential.helper /usr/share/doc/git/contrib/credential/libsecret/git-credential-libsecret erase before and then save the new token. I was already using libsecretBlighter
Your answer was useful, but so much drama. This was all I did git remote set-url origin https://username:[email protected]/username/repo.gitPerspiration
@Perspiration So, you stored your password in a configuration file?Smashup
@9pfssupportsUkraine no password was usedPerspiration
A
6

I like to keep them encrypted within the repository and load them using .envrc (https://direnv.net/)

For doing this I use ssh-vault to encrypt the data using my ssh keys that GitHub already is exposing, for example:

echo MY_TOKEN="secret" | ssh-vault -u <github-user> create > my-encypted-vars.ssh

Then the content of .envrc looks something like this:

echo "Enter ssh key password"
context=$(ssh-vault view $HOME/projects/my-encrypted.ssh | tail -n +2)
export ${context}

This will decrypt the data in my-encrypted-vars.ssh file and set MY_TOKEN into my environment variables every time I cd into the project dir.

By doing this tokens/variables are stored "safely" and always ready to use as environment variables

Agglomerate answered 25/7, 2018 at 10:30 Comment(2)
I prefer using official credential stores, as I explain in my answer, but your proposition of a dedicated vault is interesting. +1Arlie
I would recommend putting my-encrypted-vars.ssh in .git to avoid checking it in into sourceRabbitry
C
6

try enabling this to help with persisting across push / pulls

git config credential.helper store

For ongoing cloning of repo / for macOS users / install iTerm2 https://iterm2.com/

enter image description here

Enable Toolbelt

enter image description here

Just click the snippet whenever you need it. P.S. you are using oh-my-zsh, aren't you? https://github.com/ohmyzsh/ohmyzsh

Chirurgeon answered 15/9, 2021 at 4:43 Comment(0)
F
5

Use git insteadOf. Basically replace every https://github call with your access tokens + https://

git config --global url."https://<username>:<github-token>@github.com/".insteadOf "https://github.com/

Now every call to github will automatically be appended with your credentials.

I found this great answer in here. Some more info about git insteadOf.

Francesfrancesca answered 24/11, 2022 at 2:10 Comment(0)
G
4

You can cache your credentials for a defined time using:

git config --global credential.helper cache

The default cache period is 900 sec (15 min) but can be changed with:

git config --global credential.helper 'cache --timeout=3600'

See the following Github page:

https://docs.github.com/en/github/using-git/caching-your-github-credentials-in-git

This is not a permanent store and as per other comments credentials should not be stored in plain text, which is a security risk. I use a password manager (https://bitwarden.com/) to store the PAT (Personal Access Token) then copy it in for the first use, where it is then cached. A PAT is required if you enable 2FA on your Github account.

Greenhead answered 22/2, 2021 at 4:44 Comment(0)
I
3

Well, you have to save the token somewhere, when you don't want to type it each time your app asks for it :-)

A good solution is using environment variables, as already suggested in one comment.

But you still have to set the environment variable somewhere.
On Windows (which I'm using), you could use the dialog box in the system settings (I don't know if other operating systems have something similar).

I don't do this, I prefer a script in my project.
In a private project, you may commit this to source control, but this is a matter of preference.

In one of my personal projects, I'm calling the GitHub API as well, using a personal access token.
It's a command line app and the end user will save the token in a config file (which is OK).

But I need the token for development as well, because the project has integration tests where I'm calling the GitHub API.

And that project is public on GitHub, so I couldn't save the token in source control.

What I did is this:

  • I have a batch file (remember, I'm on Windows) called environment-variables.bat which sets all required environment variables including the access token
  • I'm calling this in my build script and in the batch file I'm using to run my tests
  • environment-variables.bat is ignored in source control
  • But in source control, there's environment-variables.bat.sample instead, which contains the same, but a fake token/password.

So I can just rename this file to environment-variables.bat, replace the fake password by the real one, and everything works.


This is not the perfect solution for all cases, though.

In my project, I have the problem that I need to use more tokens/passwords for more APIs in the future.

So the number of tokens in my environment-variables.bat will increase, making it difficult for potential contributors to actually execute all integration tests. And I still don't know how to deal with that.

Ionopause answered 11/10, 2017 at 16:25 Comment(0)
M
2

In my use case, I store the PAT in a password manager, e.g. LastPass, KeePass, 1Password. When I need it in a Linux environment ( e.g. Docker ), I save the PAT in an environment variable and then use git's credential helper setting. For example:

git config --global credential.helper 'cache --timeout 600'

<< eof tr -d ' ' | git credential-cache store 
  protocol=https
  host=github.com
  username=nonce
  password=${GITHUB_PAT}
eof

With a PAT the username can be anything except blank. Here's a gist that elaborates:

https://gist.github.com/rwcitek/da862e9e27cc28d3e96e62a2ca4b2b64

Marsala answered 13/1, 2022 at 23:2 Comment(0)
S
1

You can store the github https token using pass.

Two alternatives to map a git host to a pass entry:

  • bash script to map to the right pass entry:
#!/usr/bin/env bash
# assuming "get" action from git and a config like this
# git config --global credential.helper $XDG_BIN_HOME'/git_credentials_from_pass $@'
while IFS= read -r line
do
  echo "$line"
  if [[ "$line" =~ host=.*github.com.* ]]; then
      echo "username=your_user_name"
      echo "password=$(pass show token_github.com/your_username)"
  #else ...
  fi
done

Change your_username and token_github.com the way you set it up with pass insert.

This adds the token to pass without typing or pasting twice:

echo your_github_token | sed p | pass add token_github.com/your_username
git config --global credential.helper '!pass-git-helper $@'

pass-git-helper needs an ini-file to map between the git request and the pass entry. ${XDG_CONFIG_HOME}/pass-git-helper/git-pass-mapping.ini example:

[DEFAULT]
username_extractor=entry_name
[github.com*]
target=token_${host}/your_github_username
Serenity answered 31/7, 2021 at 13:32 Comment(1)
Actually this is a great answer! way better than the .netrc one. Downsides it's a linux/macos only solution. But windows has its own cred store anyways.Crossbow
A
1
curl -fsSL https://cli.github.com/packages/githubcli-archive-keyring.gpg | sudo dd of=/usr/share/keyrings/githubcli-archive-keyring.gpg
echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/githubcli-archive-keyring.gpg] https://cli.github.com/packages stable main" | sudo tee /etc/apt/sources.list.d/github-cli.list > /dev/null
sudo apt update
sudo apt install gh
gh auth login

it will ask to enter the protocol and token

Then I clones the repo again . Its not asking for token

Archon answered 26/8, 2022 at 19:46 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Quitrent
D
1

For Storing PAT you can use gh library

Installation

conda install -c conda-forge gh -y

Once the installation is complete, type this command:

gh auth login
Use the arrow and enter keys to navigate a series of prompts.

What account do you want to log into?

    > Github.com
      GitHub Enterprise Server

What is your preferred protocol for Git operations?

    > HTTPS
      SSH

Authenticate Git with your GitHub credentials? (Y/n)

How would you like to authenticate GitHub CLI?

      Login with a web browser
    > Paste an authentication token 

Now you’ve added your token — this will make pulling and pushing code a lot easier!

Dentilabial answered 9/3, 2023 at 12:45 Comment(0)
R
0

Install Git Credential Manager! https://github.com/GitCredentialManager/git-credential-manager . GCM supports caching as well as a variety of platform-specific credential stores that persist between sessions.

Even better: GCM supports user-friendly secure authentication to GitHub and GitLab via web browser with OAuth. This means you no longer even need to create personal access tokens. When you git push, simply follow a link to GitHub and authorize the app. Subsequent authentications require no interaction.

OAuth is more secure than personal access tokens, because the tokens have short expiry, refreshed when required using longer-lived refresh tokens.

Rhinoceros answered 13/6, 2022 at 8:46 Comment(0)
T
0

I resort to an unorthodox solution.

I have saved it in my Telegram Saved Messages. Every time one expires, I create a new one and edit the message. I feel It's secure, as long as I don't lose access to my Telegram.

Tend answered 26/12, 2023 at 4:42 Comment(0)
C
0

The easiest way on windows is to:

  1. try to clone a private repository,
  2. (as of 2024) git will produce a pop up that asks you to sign in your device or use an access code
  3. select access code,
  4. then paste in your token and
  5. hit enter.

That's an extremely simple way to get git/windows to remember your GitHub personal access token!

Courson answered 25/3 at 0:30 Comment(0)
T
-1

Basically I did this on my machine:

https://gist.github.com/bsara/5c4d90db3016814a3d2fe38d314f9c23

My profile script is slightly different than described:

env=~/.ssh/agent.env

agent_load_env () { test -f "$env" && . "$env" >| /dev/null ; }

agent_start () {
    (umask 077; ssh-agent >| "$env")
        . "$env" >| /dev/null ; 
}

agent_load_env

# agent_run_state: 0=agent running w/ key; 1=agent w/o key; 2= agent not running
agent_run_state=$(ssh-add -l >| /dev/null 2>&1; echo $?)

if [ ! "$SSH_AUTH_SOCK" ] || [ $agent_run_state = 2 ]; then
    agent_start
    ssh-add
elif [ "$SSH_AUTH_SOCK" ] && [ $agent_run_state = 1 ]; then
    ssh-add
fi

unset env
Tropic answered 24/7, 2018 at 12:5 Comment(1)
downvoting; while a nice solution for ssh key access does not address OP's question for personal access tokens (aka https username:PAT pairs).Crossbow

© 2022 - 2024 — McMap. All rights reserved.