tl;dr How to manage access tokens for GitLab and GitHub in Composer on your local machine, stages and CI
When you have a private package stored on GitHub or GitLab you'll need to store an access token in Composer to let Composer fetch the access protected package.
This post will show you how to save this token.
Get the token
- Generate GitHub Access Token: https://github.com/settings/tokens
- Generate GitLab Access Token: https://docs.gitlab.com/ee/user/profile/personal_access_tokens.html
- …or generate a Deploy Token instead (not bound to a GitLab user account): https://docs.gitlab.com/ee/user/project/deploy_tokens/
Local Development
For a single project on your machine:
- Run
composer config github-oauth.github.com <token>
orcomposer config gitlab-token.gitlab.com <token>
- This will create or extend the file
auth.json
- Hint: Add the
auth.json
to.gitignore
, as it contains credentials
- Hint: Add the
For all projects on your machine:
- Run
composer config -g <auth provider> <token>
Stages
- Create a local auth file (see »Local Development« above), or set an environment variable (see »CI« below)
CI
- Set the environment variable
COMPOSER_AUTH
, with the JSON formated content of theauth.json
file
Example for GitHub:
COMPOSER_AUTH='{"github-oauth":{"github.com":"XXXXXXXXXXXXXXXXXX"}}'
See https://getcomposer.org/doc/03-cli.md#composer-auth
GitHub Actions
-
Project > Settings > Environments > Environment secrets > Add secret
- Name it
COMPOSER_AUTH
and paste the JSON string as value
- Name it
-
…or set a single token secret (Settings > Secrets) like
COMPOSER_TOKEN
and use it inaction.yml
jobs:
job1:
env:
COMPOSER_AUTH: '{"github-oauth":{"github.com":"${{ secrets.COMPOSER_TOKEN }}"}}'
See https://docs.github.com/en/actions/reference/encrypted-secrets
In this example we used a GitHub access token in a GitHub action, but you could set up any other access token instead of course.
GitLab CI
-
Project > Settings > CI/CD > Variables
- Name it
COMPOSER_AUTH
and paste the JSON string as value
- Name it
-
…or set a single token variable like
COMPOSER_TOKEN
and use it in.gitlab-ci.yml
job1:
variables:
COMPOSER_AUTH: '{"gitlab-token":{"gitlab.com":"$COMPOSER_TOKEN"}}'
See https://docs.gitlab.com/ee/ci/variables/
When you use a GitLab Deoloyment Token instead, you'll need to pass the username
COMPOSER_AUTH: '{"gitlab-token":{"gitlab.com": {"username": "gitlab-deploy-token-username", "token": "XXXXXXXXXXXXXXXXXX"}}}'