Authentication overview

The Heroku Platform API provides a programmatic interface for managing Heroku applications, resources, and add-ons. To interact with this API, requests must be authenticated to verify the identity and permissions of the caller. Heroku employs standard authentication mechanisms to ensure secure access while offering flexibility for different use cases, such as interactive CLI sessions, continuous integration/continuous deployment (CI/CD) pipelines, or third-party integrations.

Authentication for the Heroku Platform API primarily relies on two methods: OAuth 2.0 and Personal API Tokens. OAuth 2.0 is an authorization framework that allows a third-party application to obtain limited access to an HTTP service, either on behalf of a resource owner by orchestrating an approval interaction between the resource owner and the HTTP service, or by itself using its own credentials, as described in the OAuth 2.0 Authorization Framework RFC 6749. Personal API Tokens, conversely, are long-lived credentials suitable for automated scripts and integrations where user interaction is not feasible or desired.

All authenticated requests to the Heroku Platform API must be made over HTTPS to protect credentials and data in transit. The API expects an Authorization header containing the appropriate token for authentication, following the Bearer token scheme. Understanding the strengths and appropriate use cases for each authentication method is crucial for building secure and efficient integrations with Heroku.

Supported authentication methods

Heroku supports two primary methods for authenticating with its Platform API:

  1. OAuth 2.0: This is the recommended method for interactive user sessions and when integrating with third-party applications that require user authorization. It provides a secure way to delegate limited access without sharing user credentials directly.
  2. Personal API Tokens (API Keys): These are long-lived tokens suitable for server-to-server communication, CI/CD systems, and other automated tasks where a user session is not practical.

OAuth 2.0

Heroku utilizes OAuth 2.0 for user authentication and authorization. When you log in via the Heroku CLI (heroku login) or authorize a third-party application, you are using OAuth 2.0. This process involves:

  • Authorization Code Grant: Typically used by web applications to obtain an access token and a refresh token. The user is redirected to Heroku for login and consent.
  • Client Credentials Grant: Used by applications to access their own service resources, not on behalf of a user. While Heroku's primary OAuth flow is user-centric, API clients can obtain tokens directly.

Upon successful authorization, an access_token is issued, which is a short-lived credential used to make API calls. A refresh_token may also be issued, which can be used to obtain new access tokens once the current one expires, without requiring the user to re-authenticate. The Heroku Dev Center provides detailed documentation on OAuth usage.

Personal API Tokens

Personal API Tokens are essentially API keys that grant direct access to your Heroku account's resources. They are generated manually from your Heroku dashboard and are long-lived until explicitly revoked. These tokens are ideal for:

  • Automated scripts
  • CI/CD pipelines (e.g., GitHub Actions, GitLab CI)
  • Server-side applications that need to interact with the Heroku API without user intervention.

Because Personal API Tokens grant broad access and do not expire automatically, their security and management are critical. Treat them like passwords and store them securely, typically as environment variables in deployment systems. The Heroku Platform API reference explains API token usage.

Comparison of Authentication Methods

Method When to Use Security Level & Considerations
OAuth 2.0
  • Interactive user sessions (e.g., Heroku CLI)
  • Third-party applications requiring user consent
  • Delegated access with scopes
  • High security: Tokens are short-lived, refreshable
  • Requires user interaction for initial authorization
  • Supports granular scopes for limited access
  • Mitigates risk of credential compromise
Personal API Token
  • Automated scripts
  • CI/CD pipelines
  • Server-to-server integrations
  • Non-interactive environments
  • Moderate security: Long-lived, direct access
  • No user interaction required after generation
  • Must be stored securely (e.g., environment variables)
  • Revocation is manual; compromise grants full API access to your account

Getting your credentials

The process for obtaining credentials depends on the authentication method you choose.

For OAuth 2.0 (Heroku CLI)

When using the Heroku CLI, the authentication process is largely automated. You typically initiate it by running:

heroku login

This command will open a web browser, prompt you to log in to your Heroku account, and authorize the CLI. Upon successful authorization, the CLI receives an OAuth access token, which it then stores securely on your local machine. This token is used for subsequent CLI commands. The Heroku CLI login process is designed for user convenience and security.

For Personal API Tokens

To obtain a Personal API Token for automated tasks:

  1. Log in to your Heroku Dashboard.
  2. Navigate to your account settings by clicking on your avatar in the top right corner and selecting "Account settings".
  3. Scroll down to the "API Key" section.
  4. Click "Reveal" to display your current API key, or "Regenerate API Key" if you need a new one or suspect your current one has been compromised.

Once revealed, copy this token immediately as it will be masked again for security. Store this token securely, for example, as an environment variable in your CI/CD system or local development environment. Do not hardcode it directly into your application code or commit it to version control.

Authenticated request example

After obtaining your access token (OAuth) or Personal API Token, you include it in the Authorization header of your HTTP requests to the Heroku Platform API. The API base URL is https://api.heroku.com.

Here's an example using curl to list your Heroku applications, authenticated with an API key:

curl -X GET https://api.heroku.com/apps \
  -H "Accept: application/vnd.heroku+json; version=3" \
  -H "Authorization: Bearer <YOUR_HEROKU_API_TOKEN>"

Replace <YOUR_HEROKU_API_TOKEN> with your actual Personal API Token. The Accept header specifies the API version and format, which is a required header for all Heroku Platform API requests.

For programmatic access in a Node.js application, you might use a library like node-fetch:

const fetch = require('node-fetch');

const HEROKU_API_TOKEN = process.env.HEROKU_API_TOKEN; // Stored securely as an environment variable

async function listHerokuApps() {
  try {
    const response = await fetch('https://api.heroku.com/apps', {
      method: 'GET',
      headers: {
        'Accept': 'application/vnd.heroku+json; version=3',
        'Authorization': `Bearer ${HEROKU_API_TOKEN}`,
      },
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const apps = await response.json();
    console.log('Your Heroku Apps:', apps.map(app => app.name));
  } catch (error) {
    console.error('Failed to fetch Heroku apps:', error);
  }
}

listHerokuApps();

This example demonstrates retrieving an API token from an environment variable, which is a key security practice.

Security best practices

Securing your Heroku Platform API credentials is paramount to protect your applications and data. Adhere to these best practices:

  1. Use OAuth 2.0 for user-facing applications: Always prefer OAuth 2.0 for any application that involves direct user interaction or requires delegated access to a user's Heroku account. This limits the exposure of long-lived credentials and allows users to revoke access without compromising their main account passwords. OAuth 2.0 also supports scopes, enabling you to request only the permissions necessary for your application, adhering to the principle of least privilege.
  2. Do not hardcode API tokens: Never embed Personal API Tokens directly into your source code. Instead, store them as environment variables (e.g., HEROKU_API_TOKEN) in your deployment environment or CI/CD system. This prevents accidental exposure in version control and allows for easier rotation of credentials.
  3. Rotate API tokens regularly: Periodically regenerate your Personal API Tokens. The recommended frequency depends on your organization's security policies, but quarterly or bi-annually is a common practice. If you suspect a token has been compromised, regenerate it immediately.
  4. Restrict access to tokens: Limit who has access to your API tokens. Only authorized personnel or automated systems should be able to retrieve or use these credentials. Implement role-based access control (RBAC) where possible.
  5. Monitor API usage: Regularly review your Heroku account activity and application logs for any suspicious or unauthorized API calls. Heroku provides various logging and monitoring tools that can help detect unusual patterns.
  6. Use HTTPS exclusively: All communications with the Heroku Platform API must use HTTPS. This encrypts your requests and responses, protecting your authentication tokens and data from eavesdropping. Heroku enforces HTTPS for all API endpoints.
  7. Understand token scopes (where applicable): While Personal API Tokens currently provide broad access, if you are developing an OAuth application, carefully define and request only the necessary scopes. This minimizes the impact of a compromised access token.
  8. Secure your development environment: Ensure your local development machine and any build servers are secure and free from malware. Compromised development environments can lead to credential theft.

By following these guidelines, you can significantly reduce the risk of unauthorized access to your Heroku resources and maintain the integrity of your applications.