[github] Authenticate with GitHub using a token

I am trying to authenticate with GitHub using a personal access token. In the help files at github, it states to use the cURL method to authenticate (https://help.github.com/articles/creating-an-access-token-for-command-line-use). I have tried this, but I still cannot push to GitHub. Please note, I am trying to push from an unauthenticated server (Travis-CI).

cd $HOME
git config --global user.email "[email protected]"
git config --global user.name "username"

curl -u "username:<MYTOKEN>" https://github.com/username/ol3-1.git
git clone --branch=gh-pages https://github.com/username/ol3-1.git gh-pages

cd gh-pages
mkdir buildtest
cd buildtest
touch asdf.asdf

git add -f .
git commit -m "Travis build $TRAVIS_BUILD_NUMBER pushed to gh-pages"
git push -fq origin gh-pages

This code causes the errors:

remote: Anonymous access to scuzzlebuzzle/ol3-1.git denied.

fatal: Authentication failed for 'https://github.com/scuzzlebuzzle/ol3-1.git/'"

This question is related to github github-pages

The answer is


If you're using GitHub Enterprise and cloning the repo or pushing gives you a 403 error instead of prompting for a username/token, you can use this:

  1. Delete the repo
  2. Open command prompt and navigate to the folder you want the repo in
  3. Type:
git clone https://[USERNAME]:[TOKEN]@[GIT_ENTERPRISE_DOMAIN]/[ORGANIZATION]/[REPO].git

Normally I do like this

 git push https://$(git_token)@github.com/user_name/repo_name.git

The git_token is reading from variable config in azure devops.

You can read my full blog here


To avoid handing over "the keys to the castle"...

Note that sigmavirus24's response requires you to give Travis a token with fairly wide permissions -- since GitHub only offers tokens with wide scopes like "write all my public repos" or "write all my private repos".

If you want to tighten down access (with a bit more work!) you can use GitHub deployment keys combined with Travis encrypted yaml fields.

Here's a sketch of how the technique works...

First generate an RSA deploy key (via ssh-keygen) called my_key and add it as a deploy key in your github repo settings.

Then...

$ password=`openssl rand -hex 32`
$ cat my_key | openssl aes-256-cbc -k "$password" -a  > my_key.enc
$ travis encrypt --add password=$password -r my-github-user/my-repo

Then use the $password file to decrypt your deploy key at integration-time, by adding to your yaml file:

before_script: 
  - openssl aes-256-cbc -k "$password" -d -a -in my_key.enc -out my_deploy_key
  - echo -e "Host github.com\n  IdentityFile /path/to/my_deploy_key" > ~/.ssh/config
  - echo "github.com ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAq2A7hRGmdnm9tUDbO9IDSwBK6TbQa+PXYPCPy6rbTrTtw7PHkccKrpp0yVhp5HdEIcKr6pLlVDBfOLX9QUsyCOV0wzfjIJNlGEYsdlLJizHhbn2mUjvSAHQqZETYP81eFzLQNnPHt4EVVUh7VfDESU84KezmD5QlWpXLmvU31/yMf+Se8xhHTvKSCZIFImWwoG6mbUoWf9nzpIoaSjB+weqqUUmpaaasXVal72J+UX2B+2RPW3RcT0eOzQgqlJL3RKrTJvdsjE3JEAvGq3lGHSZXy28G3skua2SmVi/w4yCE6gbODqnTWlg7+wC604ydGXA8VJiS5ap43JXiUFFAaQ==" > ~/.ssh/known_hosts

Note: the last line pre-populates github's RSA key, which avoids the need for manually accepting at the time of a connection.


I'm on Ubuntu 20.04 and I kept getting the message that soon I wouldn't be able to login from console. I was terribly confused. Finally, I got to the URL below which will work. But you need to know how to create a PAT (Personal Access Token) which you are going to have to keep in a file on your computer.

Here's what the final URL will look like:

git push https://[email protected]/user-name/repo.git

long PAT (Personal Access Token) value -- The entire long value between the // and the @ sign in the url is your PAT.

user-name will be your exact username

repo.git will be your exact repo name

You need to generate a PAT following the steps at: https://docs.github.com/en/github/authenticating-to-github/creating-a-personal-access-token

That will give you the PAT value that you will place in your URL.

When you create the PAT make sure you choose the following options so it has the ability to allow you to manage your REPOs. PAT settings

Save Your PAT Or Lose It

Once you have your PAT. You're going to need to save it in a file locally so you can use it again. If you don't save it somewhere there is no way to ever see it again and you'll be forced to create a new PAT

Now you're going to need at the very least :

  1. a way to display it in your console so you can see it again.
  2. or, A way to copy it to your clipboard automatically.

For 1, just use :

$ cat ~/files/myPatFile.txt

Where the path is a real path to the location and file where you stored your PAT value.

For 2

$ xclip -selection clipboard < ~/files/myPatFile.txt

That'll copy the contents of the file to the clipboard so you can use your PAT more easily.

FYI - if you don't have xclip do the following:

$ sudo apt-get install xclip

Downloads and installs xclip. If you don't have apt-get, you might need to use another installer (like yum)


Step 1: Get access token

In your github account
Click on the image on the top corner of the page that contains your profile picture ->
Settings ->
In the side menu ->
Developer Settings ->
Personal access Tokens ->
Generate new token.

Step 2: Use the token

$ git push
Username: <your username>
Password: <the access token>

Now I do not have to type username and password every time I push changes.
I just type git push and press Enter, And changes will be pushed.


Having struggled with this issue for pretty much a full day hard coding in the ORG/REPO section into our build script getting the dreaded 'remote not found' error, eventually found a working solution to be to use the TRAVIS_REPO_SLUG. Switching this in for the hardcoded attributes worked immediately.

git remote set-url origin https://[ORG]:${TOKEN}@github.com/${TRAVIS_REPO_SLUG}

For those coming from GitLab what's worked for me:

Step 1.

add remote

git remote add origin https://<access-token-name>:<access-token>@gitlab.com/path/to/project.git

Step 2.

pull once

https://<access-token-name>:<access-token>@gitlab.com/path/to/project.git

now you are able to read/write to/from repository


This worked for me using ssh:

SettingsDeveloper settingsGenerate new token.

git remote set-url origin https://[APPLICATION]:[NEW TOKEN]@github.com/[ORGANISATION]/[REPO].git

By having struggling so many hours on applying GitHub token finally it works as below:

$ cf_export GITHUB_TOKEN=$(codefresh get context github --decrypt -o yaml | yq -y .spec.data.auth.password)

  • code follows Codefresh guidance on cloning a repo using token (freestyle}
  • test carried: sed %d%H%M on match word '-123456-whatever'
  • push back to the repo (which is private repo)
  • triggered by DockerHub webhooks

Following is the complete code:

version: '1.0'
steps:
  get_git_token:
    title: Reading Github token
    image: codefresh/cli
    commands:
      - cf_export GITHUB_TOKEN=$(codefresh get context github --decrypt -o yaml | yq -y .spec.data.auth.password)
  main_clone:
    title: Updating the repo
    image: alpine/git:latest
    commands:
      - git clone https://chetabahana:[email protected]/chetabahana/compose.git
      - cd compose && git remote rm origin
      - git config --global user.name "chetabahana"
      - git config --global user.email "[email protected]"
      - git remote add origin https://chetabahana:[email protected]/chetabahana/compose.git
      - sed -i "s/-[0-9]\{1,\}-\([a-zA-Z0-9_]*\)'/-`date +%d%H%M`-whatever'/g" cloudbuild.yaml
      - git status && git add . && git commit -m "fresh commit" && git push -u origin master

Output...

On branch master 
Changes not staged for commit: 
  (use "git add ..." to update what will be committed) 
  (use "git checkout -- ..." to discard changes in working directory) 

modified:   cloudbuild.yaml 

no changes added to commit (use "git add" and/or "git commit -a") 
[master dbab20f] fresh commit 
 1 file changed, 1 insertion(+), 1 deletion(-) 
Enumerating objects: 5, done. 
Counting objects:  20% (1/5) ...  Counting objects: 100% (5/5), done. 
Delta compression using up to 4 threads 
Compressing objects:  33% (1/3) ... Writing objects: 100% (3/3), 283 bytes | 283.00 KiB/s, done. 
Total 3 (delta 2), reused 0 (delta 0) 
remote: Resolving deltas:   0% (0/2)  ...   (2/2), completed with 2 local objects. 
To https://github.com/chetabahana/compose.git 
   bbb6d2f..dbab20f  master -> master 
Branch 'master' set up to track remote branch 'master' from 'origin'. 
Reading environment variable exporting file contents. 
Successfully ran freestyle step: Cloning the repo 

Automation / Git automation with OAuth tokens

$ git clone https://github.com/username/repo.git
  Username: your_token
  Password:

It also works in the git push command.

Reference: https://help.github.com/articles/git-automation-with-oauth-tokens/


First, you need to create a personal access token (PAT). This is described here: https://help.github.com/articles/creating-an-access-token-for-command-line-use/

Laughably, the article tells you how to create it, but gives absolutely no clue what to do with it. After about an hour of trawling documentation and Stack Overflow, I finally found the answer:

$ git clone https://github.com/user-or-organisation/myrepo.git
Username: <my-username>
Password: <my-personal-access-token>

I was actually forced to enable two-factor authentication by company policy while I was working remotely and still had local changes, so in fact it was not clone I needed, but push. I read in lots of places that I needed to delete and recreate the remote, but in fact my normal push command worked exactly the same as the clone above, and the remote did not change:

$ git push https://github.com/user-or-organisation/myrepo.git
Username: <my-username>
Password: <my-personal-access-token>

(@YMHuang put me on the right track with the documentation link.)


The password that you use to login to github.com portal does not work in VS Code CLI/Shell. You should copy PAT Token from URL https://github.com/settings/tokens by generating new token and paste that string in CLI as password.