Course contentsShow
← Python
Lesson 541 of 1,0608. Professional Tooling and PackagingFree lesson

Authenticating with PyPI Using Trusted Publishers

Set up secure authentication methods using OIDC or API tokens to safely upload your packages to the Python Package Index.

In this lesson, you will learn how to automate your package uploads to PyPI securely using OpenID Connect (OIDC) instead of relying on long-lived API tokens.

Moving Beyond API Tokens

Historically, developers authenticated with PyPI by creating a global API token, storing it in their local configuration, and hoping it never leaked. If that token was compromised, an attacker could upload malicious versions of your package. Trusted Publishers solve this by using OIDC, which allows your project to authenticate via a verified identity provider—most commonly GitHub Actions.

When you use a Trusted Publisher, PyPI doesn't ask for a password or token. Instead, it checks with GitHub to confirm that the request is coming from a specific repository and a specific workflow run.

Setting Up Trusted Publishing

To configure this, you don't write code in your pyproject.toml; rather, you configure the trust relationship directly on your project's PyPI dashboard:

  1. Log in to PyPI.org.
  2. Navigate to your project's Settings and select Publishing.
  3. Click Add a new publisher.
  4. Choose GitHub as your provider and fill in the repository details, including the specific Workflow name (e.g., release.yml) and Environment (optional).

Automating the Upload

Once configured, you can use the pypa/gh-action-pypi-publish action in your GitHub Actions workflow. Because the publisher is "trusted," the action can exchange an OIDC identity token for a short-lived, single-use upload credential from PyPI. Your YAML workflow looks like this:

jobs:
  pypi-publish:
    runs-on: ubuntu-latest
    permissions:
      id-token: write  # Essential for OIDC authentication
    steps:
      - uses: actions/checkout@v4
      - name: Publish package
        uses: pypa/gh-action-pypi-publish@release/v1

By removing the need for secrets, you eliminate the risk of leaking credentials in your CI/CD logs or repository settings. You are now delegating the authentication burden to a secure, automated handshake between GitHub and PyPI.

Key Takeaway: Trusted Publishers eliminate the risk of long-lived credentials by using OIDC to authenticate your CI/CD pipeline directly with PyPI via verified GitHub Action identities.