How to store Personal Access Tokens in Composer

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

Local Development

For a single project on your machine:

  • Run composer config github-oauth.github.com <token> or composer 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

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 the auth.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
  • …or set a single token secret (Settings > Secrets) like COMPOSER_TOKEN and use it in action.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
  • …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"}}}'

⌛ Warning! This post is old. The information may be outdated.

No comments on this notepad. If you would like to add something, then dont hesitate to contact me via E-Mail or Twitter.