cPanel API Tokens for Enhanced Security

By Anurag Singh

Updated on Feb 03, 2025

cPanel API Tokens for Enhanced Security

In this tutorial, we'll learn how to use cPanel API tokens for enhanced security.

What are cPanel API Tokens and How Do They Work?

cPanel API tokens are unique, secure keys that allow you to authenticate and access cPanel features programmatically without needing to log in through the cPanel interface. These tokens are used to call cPanel API functions, enabling tasks such as managing accounts, retrieving data, and performing various operations on your server.

API tokens work by providing a secure way to authenticate API requests. When you create an API token, it is tied to your cPanel account and can be used to make API calls on your behalf. The token can be restricted or unrestricted, and you can set an expiration date for added security. Once created, the token must be kept secure, as it grants access to your cPanel account's data and functions.

cPanel API Tokens for Enhanced Security

Step-by-Step Guide to Generate and Use API Tokens

Generating an API Token

1. Log in to cPanel:

Access your cPanel account using your username and password.

2. Navigate to the Manage API Tokens Interface:

Scroll down to the Security section and click on Manage API Tokens.

3. Create a New API Token:

Click on the Create button to open the Create API Token interface.

4. Enter Token Details:

API Token Name: Enter a unique name for your API token. This name is for your reference and can help you identify the token's purpose. It can contain up to 50 characters, including letters, numbers, dashes, and underscores.

Expiration: Choose whether the token should expire. You can select "The API Token will not expire" or specify an expiration date using the calendar icon or by entering a date in YYYY-MM-DD format. Note that you cannot change the expiration date after the token is created.

5. Generate the Token:

Click the Create button to generate the API token. A new page will display the token. Click Copy to save the token to your clipboard.

6. Save the Token Securely:

Store the token in a secure location. You will not be able to retrieve it again from the cPanel interface if you lose it. You must create a new token if you misplace it.

7. Confirm Token Creation:

Click Yes, I Saved My Token to complete the process.

Using an API Token

To use the API token, you need to include it in your API requests. Here’s how you can do it:

1. Include the Token in API Requests:

When making an API call, include the token in the request header. The format for the header is:

Authorization: cpanel username:token

Replace username with your cPanel username and token with the API token you generated.

2. Example of an API Request:

Here’s an example of how to use the token in a Perl script to list cPanel accounts:

#!/usr/bin/perl
use strict;
use warnings;
use JSON       ();
use HTTP::Tiny ();

my $user  = 'your_cpanel_username';
my $token = 'your_api_token';
my $ua = HTTP::Tiny->new(
    'verify_SSL'      => 0,
    'default_headers' => {
        'Authorization' => "cpanel $user:$token",
    },
);
my $response = $ua->get("https://your_server_ip:2083/json-api/listaccts?api.version=1");
if ( $response->{'success'} ) {
    my $json = JSON::decode_json( $response->{'content'} );
    print "[+] Current cPanel users on the system:\n";
    print "\t$_\n" for map { $_->{'user'} } @{ $json->{'data'}->{'acct'} };
}
else {
    print "[!] Error: $response->{'status'} $response->{'reason'} returned\n";
}

Replace your_cpanel_username, your_api_token, and your_server_ip with your actual cPanel username, API token, and server IP address.

Python Example

Here's an example of how to make an API request using Python's requests library:

import requests

# Define your cPanel credentials and API endpoint
cpanel_username = 'your_cpanel_username'
api_token = 'your_api_token'
api_url = 'https://your_server_ip:2083/json-api/listaccts?api.version=1'

# Set up the headers with the API token
headers = {
    'Authorization': f'cpanel {cpanel_username}:{api_token}',
    'Content-Type': 'application/json'
}

# Make the API request
response = requests.get(api_url, headers=headers, verify=False)

# Check if the request was successful
if response.status_code == 200:
    data = response.json()
    print("Current cPanel users on the system:")
    for account in data['data']['acct']:
        print(account['user'])
else:
    print(f"Error: {response.status_code} - {response.reason}")

cURL Example

Here's how you can make the same API request using cURL from the command line:

curl -k \
     -H "Authorization: cpanel your_cpanel_username:your_api_token" \
     -H "Content-Type: application/json" \
     "https://your_server_ip:2083/json-api/listaccts?api.version=1"
  • -k: This flag tells cURL to ignore SSL certificate verification. Use this only in a trusted environment.
  • -H: This flag is used to add headers to the request.
  • your_cpanel_username and your_api_token: Replace these with your actual cPanel username and API token.
  • your_server_ip: Replace this with your server's IP address or domain name.

TypeScript Example

Here's an example of how to make the API request using TypeScript with the axios library:

import axios from 'axios';

// Define your cPanel credentials and API endpoint
const cpanelUsername = 'your_cpanel_username';
const apiToken = 'your_api_token';
const apiUrl = 'https://your_server_ip:2083/json-api/listaccts?api.version=1';

// Set up the headers with the API token
const headers = {
    'Authorization': `cpanel ${cpanelUsername}:${apiToken}`,
    'Content-Type': 'application/json'
};

// Make the API request
axios.get(apiUrl, { headers })
    .then(response => {
        console.log("Current cPanel users on the system:");
        response.data.data.acct.forEach(account => {
            console.log(account.user);
        });
    })
    .catch(error => {
        console.error(`Error: ${error.response.status} - ${error.response.statusText}`);
    });

Key Points to Remember

  • Security: Always keep your API tokens secure. Do not expose them in publicly accessible code or repositories.
  • SSL Verification: In production environments, always verify SSL certificates. The verify=False parameter in Python and the -k flag in cURL should only be used for testing purposes.
  • Error Handling: Implement proper error handling to manage different response statuses and potential issues.

By following these examples, you can securely access cPanel features using API tokens in Python, cURL, and TypeScript.

Revoking an API Token

If you need to revoke an API token, go to the Manage API Tokens interface, click Manage next to the token, and then click Yes Revoke the Token. This action will invalidate the token, and it will no longer be usable.

In this tutorial, we've learnt how to use cPanel API tokens for enhanced security. By following these steps, you can securely generate and use cPanel API tokens to access and manage your cPanel account's features programmatically. Always ensure that your API tokens are stored securely and are used in a controlled environment to maintain the security of your account.

Checkout our dedicated servers India, Instant KVM VPS, and Web Hosting India