Authentication overview

The Hugging Face API primarily utilizes API tokens for authentication, granting developers secure access to its extensive ecosystem, which includes the Hugging Face Hub, Inference API, and Spaces. These tokens serve as the primary mechanism to verify a user's identity and authorize their requests to interact with models, datasets, and various machine learning services. By integrating an API token into requests, users can access public models, manage private repositories, or deploy custom models through the Inference API.

Authentication ensures that operations such as pushing models to the Hub, deploying a Transformer model for inference, or accessing private datasets are performed by authorized entities. The system relies on a token-based approach, where a unique string acts as a credential, eliminating the need for traditional username and password combinations in API calls. This method is common across many web services for securing programmatic access, as detailed in various API security guidelines, including those for Google Maps API security best practices.

Hugging Face API tokens can be scoped with different permissions (e.g., read, write, admin), allowing for granular control over what actions an application or user can perform. This capability is crucial for implementing the principle of least privilege, a fundamental security practice where users are granted only the minimum necessary permissions to perform their tasks. The tokens are generated and managed within the user's Hugging Face Hub account, providing a centralized location for credential management and revocation.

Supported authentication methods

Hugging Face API primarily supports API tokens for authentication. These tokens are generated by users within their Hugging Face Hub account and are then used to authorize API requests. This method is suitable for programmatic access to the Hugging Face ecosystem, including the Inference API, Hugging Face Hub, and Spaces.

The following table outlines the primary authentication method:

Method When to Use Security Level
Hugging Face API Token Programmatic access to Inference API, Hugging Face Hub (e.g., uploading models, downloading private datasets, deploying Spaces), and general API interactions. High (bearer token, revocable, scoped permissions)

When making requests to the Hugging Face Inference API or interacting with the Hugging Face Hub programmatically, the API token is typically passed in the Authorization header as a Bearer token. This is a standard practice for OAuth 2.0 and similar token-based authentication schemes, as outlined in RFC 6750 for Bearer Token Usage. For Python SDK users, the token can often be set as an environment variable or passed directly to the client library, which then handles the header construction.

The choice of using API tokens aligns with modern best practices for API security, offering a balance of flexibility and control for developers. Tokens can be easily revoked if compromised, and their scoped permissions limit the potential damage from a leaked credential. Hugging Face's commitment to security is further underscored by its SOC 2 Type II compliance, indicating adherence to established security standards for managing customer data.

Getting your credentials

To obtain your Hugging Face API token, follow these steps within your Hugging Face Hub account:

  1. Log in to Hugging Face Hub: Navigate to the Hugging Face homepage and log in to your account. If you don't have an account, you will need to create one.
  2. Access Settings: Once logged in, click on your profile picture in the top-right corner of the page to open the dropdown menu. Select 'Settings' from this menu.
  3. Navigate to Access Tokens: On the settings page, look for the 'Access Tokens' section in the left-hand navigation pane and click on it.
  4. Generate a New Token: In the Access Tokens section, you will see a list of your existing tokens (if any). To create a new token, click the 'New token' button.
  5. Configure Token Properties:
    • Name: Provide a descriptive name for your token (e.g., 'My Inference API Key', 'CI/CD Token'). This helps you identify its purpose later.
    • Role: Select the appropriate role for the token. Options typically include 'read', 'write', and 'admin'. Choose the least privileged role necessary for your application's needs. For example, if you only intend to use the Inference API, 'read' might suffice. If you plan to push models to the Hub, 'write' or 'admin' would be required.
  6. Create Token: After naming the token and selecting its role, click the 'Generate a token' or similar button.
  7. Copy Your Token: The newly generated token will be displayed. Copy this token immediately, as it will only be shown once for security reasons. If you lose it, you will need to generate a new one.

Once you have copied your API token, you can use it in your API requests or configure it within the Hugging Face Python SDK. It is recommended to store this token securely, for example, as an environment variable, rather than hardcoding it directly into your application code. For more detailed instructions, refer to the Hugging Face security tokens documentation.

Authenticated request example

This example demonstrates how to make an authenticated request to the Hugging Face Inference API using Python, passing the API token in the Authorization header. This is a common pattern for authenticating with the API to perform tasks like running a model for text classification.

First, ensure you have your Hugging Face API token. For this example, we'll assume it's stored in an environment variable named HF_API_TOKEN.

import os
import requests

# Retrieve your Hugging Face API token from an environment variable
hf_api_token = os.getenv("HF_API_TOKEN")

if not hf_api_token:
    raise ValueError("Hugging Face API token not found. Please set the HF_API_TOKEN environment variable.")

# Define the API endpoint for a specific model (e.g., sentiment analysis)
API_URL = "https://api-inference.huggingface.co/models/distilbert-base-uncased-finetuned-sst-2-english"

# Set the headers, including the Authorization header with your API token
headers = {
    "Authorization": f"Bearer {hf_api_token}"
}

# Define the payload for the API request
payload = {
    "inputs": "I love using Hugging Face APIs for my projects!",
}

# Make the POST request to the Inference API
def query(payload):
    response = requests.post(API_URL, headers=headers, json=payload)
    response.raise_for_status() # Raise an HTTPError for bad responses (4xx or 5xx)
    return response.json()

# Execute the query and print the result
output = query(payload)
print(output)

In this example:

  • os.getenv("HF_API_TOKEN") retrieves the API token from your environment variables. This is a recommended practice to avoid hardcoding sensitive credentials.
  • The API_URL points to a specific model hosted on the Hugging Face Inference API. You would replace this with the URL for the model you intend to use.
  • The headers dictionary includes the Authorization key with the value Bearer {hf_api_token}. This is the standard way to pass a Bearer token for authentication.
  • The payload contains the input data for the model, in this case, text for sentiment analysis.
  • The requests.post function sends the request to the API. response.raise_for_status() is used to check for HTTP errors.
  • The API's JSON response, containing the model's output, is then printed.

This structure ensures that your requests are properly authenticated, allowing you to leverage the full capabilities of the Hugging Face Inference API and interact with various models. For more examples and detailed parameters, consult the Hugging Face Inference API reference.

Security best practices

Implementing robust security practices is essential when working with Hugging Face API tokens to protect your models, data, and account. Adhering to these guidelines minimizes the risk of unauthorized access and potential breaches:

  • Principle of Least Privilege: When generating an API token, always assign the minimum necessary permissions (role). For example, if an application only needs to read public models, grant it a 'read' token, not a 'write' or 'admin' token. This limits the scope of damage if the token is compromised.
  • Environment Variables: Never hardcode API tokens directly into your source code. Instead, store them as environment variables (e.g., HF_API_TOKEN). This prevents tokens from being exposed in version control systems or publicly accessible code repositories. Most programming languages and CI/CD pipelines offer secure ways to manage environment variables.
  • Secure Storage: If tokens must be stored, use secure storage mechanisms such as a secrets manager (e.g., AWS Secrets Manager, Google Secret Manager, Azure Key Vault) or a secure vault application. Avoid storing tokens in plain text files or insecure databases.
  • Regular Rotation: Periodically rotate your API tokens. This means generating a new token and revoking the old one. Regular rotation reduces the window of opportunity for a compromised token to be exploited. The frequency of rotation should be determined by your organization's security policy and risk assessment.
  • Immediate Revocation: If you suspect an API token has been compromised, revoke it immediately through your Hugging Face Hub account settings. This will invalidate the token, preventing any further unauthorized use.
  • Audit Logs: Monitor access logs and activity associated with your API tokens, if available. Unusual activity patterns (e.g., requests from unexpected IP addresses, high volume of failed authentication attempts) could indicate a compromise.
  • Network Security: When making API requests, ensure that your client environment is secure. Use HTTPS for all communications, as the Hugging Face API enforces it, to encrypt data in transit and prevent eavesdropping.
  • Educate Developers: Ensure that all developers working with Hugging Face APIs are aware of these security best practices and understand the importance of secure token handling.
  • Avoid Public Exposure: Be extremely cautious when sharing code snippets or configuration files publicly (e.g., on GitHub, Stack Overflow). Always double-check that no sensitive tokens are included.
  • Use Dedicated Tokens: For different applications or services, create separate, dedicated API tokens. This allows for easier management, targeted revocation, and clearer auditing of which application is performing which actions.

By diligently following these security best practices, you can significantly enhance the protection of your Hugging Face API interactions and safeguard your valuable machine learning assets. Further guidance on general API security is available from reputable sources like OAuth 2.0 Bearer Token usage documentation.