github-packagesghcrgithub-container-registry

How to get API token to GitHub Container Registry


I'm trying to authenticate to the GitHub Container Registry (ghcr.io) over curl and I'm not having much luck. I know I need a GitHub PAT with package:read rights which I have, and then I can use that to generate a token.

When fetching a public image I can run this command and get a token just fine assuming the $USER_NAME and $IMAGE environment variables are set to the correct values.

curl -v "https://ghcr.io/token?service=ghcr.io&scope=repository:$USER_NAME/$IMAGE:pull"

But when trying the same thing for a private image.

curl -v -H "Authorization: Bearer $GITHUB_TOKEN" "https://ghcr.io/token?service=ghcr.io&scope=repository:$USER_NAME/$IMAGE:pull"

I get

< HTTP/2 401
< content-type: application/json
< docker-distribution-api-version: registry/2.0
< www-authenticate: Bearer realm="https://ghcr.io/token",service="ghcr.io",scope="repository:user/image:pull"
< date: Fri, 08 Nov 2024 00:36:26 GMT
< content-length: 73
< x-github-request-id: C559:34E8D2:158A23A:18442CA:672D5D0A
<
{"errors":[{"code":"UNAUTHORIZED","message":"authentication required"}]}
 * Connection #0 to host ghcr.io left intact

I've even tried to give the PAT all permissions in my account. I can see in the curl output that the PAT output is correctly.


Solution

  • It turns out that ghcr.io uses basic authentication in the form of <username>:<PAT>

    So it would look something like this.

    curl -H "Authorization: Basic $BASE64_CREDENTIALS" "https://ghcr.io/token?service=ghcr.io&scope=repository:<user>/<image>:pull"
    
    {"token":"xyz"}