Page tree
Skip to end of metadata
Go to start of metadata

 

Introduction

cPanel & WHM supports several API authentication methods. Whenever code calls an API function, it must first authenticate to the server. The authentication process accesses the server in order to run code as a specific cPanel or WHM user with a specific set of permissions.

Note:

This document only includes cPanel & WHM authentication methods. For Manage2 authentication information, read our Guide to the Manage2 API documentation.

Important:

API calls that use a method that includes a URL must use the correct port:

  • 2082 — Unsecure calls to cPanel's APIs.
  • 2083 — Secure calls to cPanel's APIs.
  • 2086 — Unsecure calls to WHM's APIs, or to cPanel's APIs via the WHM API.
  • 2087 — Secure calls to WHM's APIs, or to cPanel's APIs via the WHM API.
  • 2095 — Unsecure calls to cPanel's APIs via a Webmail session.
  • 2096 — Secure calls to cPanel's APIs via a Webmail session.

Otherwise-correct calls will return Permission denied or Function not found errors if they use an incorrect port number. 

Browser-based authentication

To call API functions through a web browser, you must first log in to WHM or cPanel.

  • The API function determines which cPanel, Inc. product to log in to.
  • Some functions require specific feature lists or user permissions.

For help to log in to WHM or cPanel, read our How to Access cPanel & WHM Services documentation.

For more information about browser-based calls, read the documentation for the function's API:

  • Guide to cPanel API 2 — cPanel API 2 accesses cPanel account information and modifies settings.
  • Guide to UAPI — UAPI accesses the cPanel interface's features.

  • Guide to WHM API 1 — WHM API 1 accesses the WHM interface's features.

    Note:

    You can call cPanel API2 and UAPI functions through the WHM API. This is useful, for example, when you develop plugins for WHM users, particularly resellers, but need to access cPanel functions. For more information, read our Use WHM API to Call cPanel API and UAPI documentation.

API token

You can use API tokens instead of a password or access hash key to execute WHM API 1 functions over HTTPS. For more information about API tokens, read our Manage API Tokens documentation.

To create or view an API token, use WHM's Manage API Tokens interface (Home >> Security Center >> Manage API Tokens).

Example Perl script

 Click to view...

Notes:

  • Specify either the root user or a reseller user in line 9.

  • Replace MYAPITOKEN in line 10 with a valid API token.
  • Replace 127.0.0.1 in line 18 with your server's IP address.
#!/usr/bin/perl
use strict;
use warnings;

use JSON       ();
use HTTP::Tiny ();


my $user  = 'root';
my $token = 'MYAPITOKEN';
my $ua = HTTP::Tiny->new(
    'verify_SSL'      => 0,
    'default_headers' => {
        'Authorization' => "token $user:$token",
    },
);

my $response = $ua->get("https://127.0.0.1:2087/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";
}
  • In line 10, the script declares the $token variable and assigns the API token hash to it as a value.
  • In line 11, the script creates an HTTP::Tiny user agent and configures it to send the token authorization headers with every request.
  • Line 18 invokes the WHM API 1 listaccts function via the HTTP::Tiny user agent and saves the response in the $response variable.
  • The script prints the following output:
    • If the listacct function succeeds, the function parses the JSON data and returns the account's usernames.
    • If the listacct function fails, the function returns an error message.

Example PHP script

 Click to view...

Notes:

  • Specify either the root user or a reseller user in line 2.

  • Replace MYAPITOKEN in line 3 with a valid API token.
  • Replace 127.0.0.1 in line 5 with your server's IP address.
<?
    $user = "root";
    $token = "MYAPITOKEN";

    $query = "https://127.0.0.1:2087/json-api/listaccts?api.version=1";

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST,0);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER,0);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER,1);

    $header[0] = "Authorization: token $user:$token";
    curl_setopt($curl,CURLOPT_HTTPHEADER,$header);
    curl_setopt($curl, CURLOPT_URL, $query);

    $result = curl_exec($curl);

    $http_status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    if ($http_status != 200) {
        echo "[!] Error: " . $http_status . " returned\n";
    } else {
        $json = json_decode($result);
        echo "[+] Current cPanel users on the system:\n";
        foreach ($json->{'data'}->{'acct'} as $userdetails) {
            echo "\t" . $userdetails->{'user'} . "\n";
        }
    }

    curl_close($curl);
?>
  • Line 2 sets the $user value as the root user.
  • Line 3 sets the $token value as the contents of the appropriate API token.
  • Line 5 initializes the WHM API 1 listaccts function via a curl call and configures it to send the Authorization: token $user:$token headers with every request.

  • Line 16 performs the WHM API 1 listaccts function via a curl call and saves the response in the $response variable.
  • The script prints the following output:
    • If the listacct function succeeds, the function parses the JSON data and returns the account's usernames.
    • If the listacct function fails, the function returns an error message.


Access hash authentication

Warnings:

  • We deprecated this method in cPanel & WHM version 64. We strongly recommend that you use the API token method to authenticate with a WHM server.
  • This method is only available for WHM authentication. 

An access hash is a key that authenticates with the server as the root user. Scripts can include an access hash in the HTTP header that they send to the server during API functions.

  • To view or retrieve an access hash, use WHM's Remote Access Key interface (Home >> Clusters >> Remote Access Key).
  • The system stores access hashes in the .accesshash file in each user's home directory.

Example Perl script

 Click to view...

Notes:

  • Replace accesshashhere in line 7 with the contents of the /root/.accesshash file. You must supply the access hash as a single line with no breaks.
  • This script requires the LWP::Protocol:https module. If you attempt to run this script, you must first run the /scripts/perlinstaller LWP::Protocol::https command to install the module.
  • This script calls WHM API 1's  listaccts function. Make certain that you update this code for the correct API version, port, and other function-specific call information.
#!/usr/bin/perl
use strict;
use LWP::UserAgent;
use LWP::Protocol::https;
use MIME::Base64;
 
my $hash = "accesshashhere";
 
$hash =~ s/\n//g;
 
my $auth = "WHM root:" . $hash;
 
my $ua = LWP::UserAgent->new(
ssl_opts   => { verify_hostname => 0, SSL_verify_mode => 'SSL_VERIFY_NONE', SSL_use_cert => 0 },
	);
my $request = HTTP::Request->new(GET => "https://127.0.0.1:2087/json-api/listaccts?api.version=1");
$request->header( Authorization => $auth );
my $response = $ua->request($request);
print $response->content;
  • In line 7, the script declares the $hash variable and assigns the access hash to it as a value.
  • In line 11, the script declares the $auth variable, and assigns it a value of WHM root: $hash.
  • Line 15 declares the $request variable, which stores information about the call. To set its value, the HTTP::Request module's new() method creates a function to the WHM API 1 listaccts function.
    • This call uses the GET method. 
    • When you construct URLs to use this method, use the same methods as for a browser-based call.
  • Line 16 uses the header() method to use the $auth value as the call's authentication information.
  • Line 17 uses the LWP::UserAgent module to run the function.
  • Line 18 prints the function's output.

Example PHP script

 Click to view...

Notes:

  • Replace accesshashhere with the contents of the /root/.accesshash file. You must supply the access hash as a single line with no breaks.
  • This script calls WHM API 1's listaccts function. Make certain that you update this code for the correct API version, port, and other function-specific call information.
<?
$whmusername = "root";
 
# The contents of /root/.accesshash
$hash = "accesshashhere";
 
$query = "https://127.0.0.1:2087/json-api/listaccts?api.version=1";
 
$curl = curl_init();
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST,0);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER,0);
curl_setopt($curl, CURLOPT_RETURNTRANSFER,1);
 
$header[0] = "Authorization: WHM $whmusername:" . preg_replace("'(\r|\n)'","",$hash);
curl_setopt($curl,CURLOPT_HTTPHEADER,$header);
curl_setopt($curl, CURLOPT_URL, $query);
 
$result = curl_exec($curl);
if ($result == false) {
    error_log("curl_exec threw error \"" . curl_error($curl) . "\" for $query");
}
curl_close($curl);
 
print $result;
?>
  • Line 2 sets the $whmusername value as the root user.
  • Line 5 sets the $hash value as the contents of the appropriate access hash.
  • Line 7 assigns a WHM API 1 listaccts function to the $query value.
    • This call uses the GET method. 
    • When you construct URLs to use this method, use the same methods as for a browser-based call.
  • Line 14 assigns the $header[0] variable a value of WHM $whmusername: $hash.
    • The $whmusername variable contains the account's username, which must be root for this authentication method.
    • The $hash variable contains the account's access hash.
  • Line 15 uses the $header hash to properly configure the HTTP header for the function.
  • Line 16 uses the $query variable to pass in the function itself.
  • Lines 18 through 22 execute the function.
  • Line 24 prints the function's output.

Username and password authentication

Warning:

Do not use this method to authenticate over an unsecured connection (port 2086, 2095, or 2082). Only use this method with a secure SSL connection over port 2083 (cPanel), port 2096 (Webmail), or port 2087 (WHM). 

Scripts can include the username and password in an HTTP header. The script sends an HTTP header to the server during API functions. This allows the script to effectively log in as the desired user before the function.

Example Perl script

 Click to view...

Notes:

  • This script runs as the root user.
  • This script requires the LWP::Protocol:https module. If you attempt to run this script, you must first run the /scripts/perlinstaller LWP::Protocol::https command to install the module.
  • This script calls WHM API 1's listaccts function. Make certain that you update this code for the correct API version, port, and other function-specific call information.
#!/usr/bin/perl
use strict;
use LWP::UserAgent;
use LWP::Protocol::https;
use MIME::Base64; 

my $user = "root";
my $pass = "12345luggage";

my $auth = "Basic " . MIME::Base64::encode( $user . ":" . $pass );

my $ua = LWP::UserAgent->new(
    ssl_opts   => { verify_hostname => 0, SSL_verify_mode => 'SSL_VERIFY_NONE', SSL_use_cert => 0 },
);
my $request = HTTP::Request->new( GET => "https://127.0.0.1:2087/json-api/listaccts?api.version=1" );
$request->header( Authorization => $auth );
my $response = $ua->request($request);
print $response->content;
  • Line 6 declares the $user variable and assigns it a value of root.
  • Line 7 declares the $pass variable and assigns it the root account's password, 12345luggage.
  • Line 9 declares the $auth variable, and assigns it a value of Basic root:12345luggage.
  • Line 12 declares the $request variable, which stores information about the call. To set its value, the HTTP::Request module's new() method creates a function to the WHM API 1 listaccts function.
    • This call uses the GET method. 
    • When you construct URLs to use this method, use the same methods as for a browser-based call.
  • Line 13 uses the header() method to use the $auth value as the call's authentication information.
  • Line 14 uses the LWP::UserAgent module to run the function.
  • Line 15 prints the function's output.

Example PHP script

 Click to view...

Notes:

  • Replace accesshashhere with the contents of the /root/.accesshash file.
  • This script calls WHM API 1's listaccts function. Make certain that you update this code for the correct API version, port, and other function-specific call information.
<?
$whmusername = "root";
$whmpassword = "12345luggage";

$query = "https://127.0.0.1:2087/json-api/listaccts?api.version=1";

$curl = curl_init();		                        // Create Curl Object
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER,0);	    // Allow self-signed certs
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST,0); 	    // Allow certs that do not match the hostname
curl_setopt($curl, CURLOPT_HEADER,0);			    // Do not include header in output
curl_setopt($curl, CURLOPT_RETURNTRANSFER,1);	    // Return contents of transfer on curl_exec
$header[0] = "Authorization: Basic " . base64_encode($whmusername.":".$whmpassword) . "\n\r";
curl_setopt($curl, CURLOPT_HTTPHEADER, $header);    // set the username and password
curl_setopt($curl, CURLOPT_URL, $query);			// execute the query
$result = curl_exec($curl);
if ($result == false) {
	error_log("curl_exec threw error \"" . curl_error($curl) . "\" for $query");	
                                                    // log error if curl exec fails
}
curl_close($curl);

print $result;

?>
  • Line 3 sets the $whmusername value as the root user.
  • Line 4 sets the $whmpassword value as the root account's password, 12345luggage.
  • Line 6 assigns a WHM API 1 listaccts function to the $query value.
    • When you construct URLs to use this method, use the same methods as for a browser-based call.
  • Line 13 assigns the $header[0] variable a value of Authorization: Basic $whmusername: $whmpassword.
    • The $whmusername variable contains the account's username.
    • The $whmpassword variable contains the account's password.
  • Line 14 uses the $header hash to properly configure the HTTP header for the function.
  • Line 15 uses the $query variable to pass in the function itself.
  • Lines 17 through 22 execute the function.
  • Line 24 prints the function's output.

Two-factor authentication

Important:

We introduced this feature in cPanel & WHM version 54.

The Two-Factor Authentication feature requires an additional six-digit security code to log in to cPanel & WHM. A smartphone with a supported time-based one-time password (TOTP) app provides the security code.

2FA with Session-based Authentication

This script sends the OTP once to establish an authenticated session, and then performs all of the API calls within that session.

Example Perl Script

 Click to view...

Note:

This script requires the LWP::Protocol:https module. If you attempt to run this script, you must first run the /scripts/perlinstaller LWP::Protocol::https command to install the module.

#!/usr/local/cpanel/3rdparty/bin/perl

use strict;
use warnings;
use Data::Dumper;

use Cpanel::JSON::XS                               ();
use LWP::UserAgent                                 ();
use HTTP::Cookies                                  ();
use Cpanel::Security::Authn::TwoFactorAuth::Google ();

my $user = 'cptest';
my $pass = 'blahblah';

my $base_url  = 'https://127.0.0.1:2083';
my $login_url = $base_url . '/login';

my $cookie_jar = HTTP::Cookies->new();
my $ua         = LWP::UserAgent->new(
    ssl_opts => {
        verify_hostname => 0,
    },
    cookie_jar => $cookie_jar,
);

# This takes the secret that is generated for the account when 2FA
# was configured - if you do not have the secret handy, you can
# choose to reconfigure 2FA on the account, and note the new secret.
my $google_auth = Cpanel::Security::Authn::TwoFactorAuth::Google->new(
    {
        'account_name' => $user,
        'secret'       => 'QSARBVKLZHYHLJ3M',
        'issuer'       => 'issuer name'
    }
);

# Login, and establish a session
my $resp = $ua->post( $login_url, { 'user' => $user, 'pass' => $pass, 'tfa_token' => $google_auth->generate_code() } );
# Parse the security token out, so that you can provide it properly in the subsequent requests
my $security_token = ( split /\//, $resp->header('location') )[1];

my $api_url = $base_url . '/' . $security_token . '/execute/Email/list_pops';
$resp = $ua->get($api_url);
my $json = Cpanel::JSON::XS::decode_json( $resp->decoded_content );
print Dumper $json;

Example PHP script

 Click to view...
<?
// Path to your OTP Library
// The one used for this script can be downloaded from:
// https://github.com/lelag/otphp
require_once('otphp-master/lib/otphp.php');

$user = "username";
$pass = "password";
$secret = "secret"; // the secret generated from the 2fa setup page

$base_url  = 'https://127.0.0.1:2083';
$login_url = $base_url . '/login';
$cookie_jar = 'cookie.txt';

// get the token
$totp = new \OTPHP\TOTP($secret);
$token = $totp->now();

// these are the fields we went to send in the body of the POST request
$params = array(
    'user' => $user,
    'pass' => $pass,
    'tfa_token' => $token
);

// create a request to the login page that sends your username, password, and tfa token
$login_request = curl_init();                                     // Create Curl Object.
curl_setopt($login_request, CURLOPT_SSL_VERIFYPEER, false);       // Allow self-signed certificates...
curl_setopt($login_request, CURLOPT_SSL_VERIFYHOST, false);       // and certificates that don't match the hostname.
curl_setopt($login_request, CURLOPT_HEADER, true);                // Include headers
curl_setopt($login_request, CURLOPT_RETURNTRANSFER, true);        // Return contents of transfer on curl_exec.
curl_setopt($login_request, CURLOPT_POST, true);                  // We want a POST submission
curl_setopt($login_request, CURLOPT_POSTFIELDS, $params);         // Set the parameters we want
curl_setopt($login_request, CURLOPT_COOKIEJAR, $cookie_jar);      // Set the cookie jar.
curl_setopt($login_request, CURLOPT_URL, $login_url);             // Execute the query.
$result = curl_exec($login_request);
if (!$result) {
    error_log("curl_exec threw error \"" . curl_error($login_request) . "\" for $login_url");
}
curl_close($login_request);

$found_location = preg_match("/cpsess\d+/i", $result, $matches);
if (!$found_location) {
    error_log("Could not find the security token.");
    die;
}

// create an api request to fetch email accounts on your cPanel account
$security_token = $matches[0];
$api_url = $base_url . '/' . $security_token . '/execute/Email/list_pops';

$api_request = curl_init();
curl_setopt($api_request, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($api_request, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($api_request, CURLOPT_RETURNTRANSFER, true);
curl_setopt($api_request, CURLOPT_POST, true);
curl_setopt($api_request, CURLOPT_COOKIEFILE, $cookie_jar); // Send the cookie file with our request
curl_setopt($api_request, CURLOPT_URL, $api_url);
$api_result = curl_exec($api_request);
if (!$api_result) {
    error_log("curl_exec threw error \"" . curl_error($api_request) . "\" for $api_url");
}
curl_close($api_request);

print $api_result;

// remove the cookie jar
unlink($cookie_jar);

?>

2FA with Basic HTTP Authentication, Not Session-based

This script allows you to perform API calls without the need to establish a session, but requires you to send the OTP token with every request in the X-CPANEL-OTP header. This script also requires that you know the 2FA secret in order to generate the required tokens.

Example Perl script

 Click to view...
use strict;
use warnings; 

use Data::Dumper;
use MIME::Base64 ();
use HTTP::Tiny   ();

use Cpanel::Security::Authn::TwoFactorAuth::Google ();

my $user = "asder";
my $pass = "blah1";

my $auth_str    = "Basic " . MIME::Base64::encode( $user . ":" . $pass );
chomp $auth_str;
my $ua          = HTTP::Tiny->new( 'verify_ssl' => 0 );
my $google_auth = Cpanel::Security::Authn::TwoFactorAuth::Google->new(
    {
        'account_name' => $user,
        'secret'       => 'FZ4ZVGTMFTIOF54T',
        'issuer'       => 'e'
    }
);

my $resp = $ua->request(
    "GET",
    "https://127.0.0.1:2083/execute/Ftp/list_ftp",
    {
        headers => {
            'Authorization' => $auth_str,
            'X-CPANEL-OTP'  => $google_auth->generate_code(),
        }
    }
);
 
if ( $resp->{'success'} ) {
    print "CPANEL API Request successful using user/pass combination\n";
    print "Return:\n$resp->{'content'}\n";
}
else {
    print "CPANEL API Request failed using user/pass combination. $resp->{'status'}: $resp->{'reason'}\n";
}
 
my $accesshash = "7287c7dc48af430f8d72e836c3facda4
ecc6d5b802f9f046e6ed204353eddc5e
82a4cc0e57d018efb7bf2604af339489
f491c01c30dd659c5955b16c91511602
51285e0e8fcd150b3c5b772b8c244989
a53b36af96d78798b656cbcbff34e443
3bd557787825f1eedcf8504c9b96196c
6fb5b3c5946282625d316c2e64876aab
7578ce0918180c907f5f64317345ea7a
48b8499a38db5dc2ae0d97ae8c69de30
86a7cfac479add55b8005d87c33ec5f8
8045986c5a61c48ab57adbe5c25e30f9
759a7c2f149925a9be0bd1371f78fb45
e214bfd7039deb9cbd44fa358913ca2f
c44733c749bd269079ba87aedb83b75f
0ee50b6c6c320dcaa12147c4f07e3257
125dda32b1acccfc4a09dc42d022f493
294903bd3fa14c646a31a4847b7fcdf6
55d8bc29804e4719b4f377fe92bd5115
5e3f77f720ee1bd2571749c8aa8f081a
47a2f87085253d3c1ee012111bf1d221
8cda0e2131080682d7d30ed55c0f7260
7673392f8d775f50923903d38f8bc742
c98afb0802b4b04064b8782922308423
31f87c300eae452ca7588304b59e10a7
64da2083bcc3ad568c872b8e3e537896
d49da203ece1a37e1c81ead3713591d9
832c6aa23cb7931643d17f79cfd6ba8e
4609538e308b14dd8b1b2529afd1b458
56243e84055f8366b0f675ce0ab19958";
$accesshash =~ s/\n//g;
 
$auth_str = "WHM $user:$accesshash";
$resp = $ua->request(
    "GET",
    "https://127.0.0.1:2087/json-api/applist?api.version=1",
    {
        headers => {
            'Authorization' => $auth_str,
            'X-CPANEL-OTP'  => $google_auth->generate_code(),
        }
    }
);
 
if ( $resp->{'success'} ) {
    print "WHM API Request successful using user/pass combination\n";
    print "Return:\n$resp->{'content'}\n";
}
else {
    print "WHM API Request failed using user/pass combination. $resp->{'status'}: $resp->{'reason'}\n";
}

 

Single Sign On

Important:

We introduced this feature in cPanel & WHM version 11.40.

The Single Sign On feature generates a temporary session to authenticate with cPanel & WHM.

For example, this feature generates a temporary session whenever the root user or a reseller uses the following methods to access a cPanel user's account:

Third-party applications with WHM access can use this feature to log in to cPanel accounts without the need to store their account passwords. The system automatically destroys the temporary session when it logs out or expires (sessions expire after 15 minutes of inactivity). This feature also creates temporary sessions when a cPanel user logs in to Webmail through the cPanel interface.

To use this method, perform the following steps:

  1. Call WHM API 1's create_user_session function.
  2. Send a GET request to the URL that the function returns as the url value.

    Note:

    The session will not function until you send this request. The GET request to the login URL returns a cookie that must exist for subsequent API calls to authenticate successfully. 

  3. Configure your script to use the temporary session ID and security token to access the account through either the access hash or username and password methods.

Example Perl script

 Click to view...

Note:

This script calls WHM API 1's create_user_session function. Make certain that you update this code for the correct API version, port, and other function-specific call information.

#!/usr/bin/perl
use strict;
use LWP::UserAgent;
use LWP::Protocol::https;
use HTTP::Cookies ();
use MIME::Base64 ();
use JSON;
 
# This can also be the reseller who owns the cPanel user
my $user = "root";
my $pass = "password";
 
# The user on whose behalf the API call runs
my $cpanel_user = "username";

# form the authentication header 
my $auth = "Basic " . MIME::Base64::encode( "${user}:${pass}" );

# instantiate the root http request object
my $root_ua = LWP::UserAgent->new(
    ssl_opts   => { verify_hostname => 0, SSL_verify_mode => 'SSL_VERIFY_NONE', SSL_use_cert => 0 },
);
# Set the authentication header
$root_ua->default_header( Authorization => $auth );
# Allows for self signed certificates
$root_ua->ssl_opts( verify_hostname => 0 );  

# make the request to create the user session
my $response = $root_ua->get("https://10.0.0.1:2087/json-api/create_user_session?api.version=1&user=$cpanel_user&service=cpaneld" );

# Decode the json formatted response
my $json_decoded_payload = decode_json($response->decoded_content());
my $session_url = $json_decoded_payload->{'data'}->{'url'};

# Create the user cookie jar, this will contain the cookies needed to continue making requests after login 
my $user_cookie_jar  = HTTP::Cookies->new();

# instantiate the user http request object
my $user_ua = LWP::UserAgent->new;
# Enable cookies for this request session
$user_ua->cookie_jar($user_cookie_jar);
# Allow self signed certificates
$user_ua->ssl_opts( verify_hostname => 0 );

# login as the user using the session url
$response = $user_ua->get($session_url);

# strip the login portion of the url to make $session_url = https://10.0.0.1/$session_key
$session_url =~ s{/login(?:/)??.*}{};

# Continue using the authenticated http request object to perform API calls
$response = $user_ua->get("$session_url/execute/Ftp/list_ftp");
print $response->content;

Example PHP script

 Click to view...

Note:

This script calls WHM API 1's create_user_session function. Make certain that you update this code for the correct API version, port, and other function-specific call information.

<?

// This can also be the reseller who owns the cPanel user.
$whmusername = "root";
$whmpassword = "password";

// The user on whose behalf the API call runs.
$cpanel_user = "username";

$query = "https://10.0.0.1:2087/json-api/create_user_session?api.version=1&user=$cpanel_user&service=cpaneld";
 
$curl = curl_init();                                     // Create Curl Object.
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);       // Allow self-signed certificates...
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);       // and certificates that don't match the hostname.
curl_setopt($curl, CURLOPT_HEADER, false);               // Do not include header in output
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);        // Return contents of transfer on curl_exec.
$header[0] = "Authorization: Basic " . base64_encode($whmusername.":".$whmpassword) . "\n\r";
curl_setopt($curl, CURLOPT_HTTPHEADER, $header);         // Set the username and password.
curl_setopt($curl, CURLOPT_URL, $query);                 // Execute the query.
$result = curl_exec($curl);
if ($result == false) {
    error_log("curl_exec threw error \"" . curl_error($curl) . "\" for $query"); 
                                                    // log error if curl exec fails
}


$decoded_response = json_decode( $result, true );

$session_url = $decoded_response['data']['url'];
$cookie_jar = 'cookie.txt';

curl_setopt($curl, CURLOPT_HTTPHEADER, null);             // Unset the authentication header.
curl_setopt($curl, CURLOPT_COOKIESESSION, true);          // Initiate a new cookie session.
curl_setopt($curl, CURLOPT_COOKIEJAR, $cookie_jar);       // Set the cookie jar.
curl_setopt($curl, CURLOPT_COOKIEFILE, $cookie_jar);      // Set the cookie file.
curl_setopt($curl, CURLOPT_URL, $session_url);            // Set the query url to the session login url.

$result = curl_exec($curl);                               // Execute the session login call.
if ($result == false) {
    error_log("curl_exec threw error \"" . curl_error($curl) . "\" for $query"); 
                                                    // Log an error if curl_exec fails.
}

$session_url = preg_replace( '{/login(?:/)??.*}', '', $session_url );  // make $session_url = https://10.0.0.1/$session_key

$query = "$session_url/execute/Ftp/list_ftp";

curl_setopt($curl, CURLOPT_URL, $query);  // Change the query url to use the UAPI call.
$result = curl_exec($curl);               // Execute the UAPI call.
if ($result == false) {
    error_log("curl_exec threw error \"" . curl_error($curl) . "\" for $query"); 
                                                    // log error if curl exec fails
}

curl_close($curl);
 
print $result;
 
?> 

 

The Single Sign On session log

Whenever the Single Sign On feature generates or destroys a temporary session, the system stores information to the Single Sign On session log:

127.0.0.1 [12/05/2013:06:36:09 -0000] PURGE fz49w:ym5mFKRIAChAQ_yHyn6i19p6DQupDepQN4I3HnH490AAWPFSP2ZipQ7YpE_uA_CG logout
127.0.0.1 [12/05/2013:06:36:12 -0000] NEW z2p:BADVVmryioLExTGvKITEbSuDFHztNAyEeetBPpUmA8sA8Iu_y4eofHZmbbzIG2UU address=127.0.0.1,app=cpaneld,creator=z2p,method=handle_form_login,path=form,possessed=0
127.0.0.1 [12/05/2013:06:36:13 -0000] PURGE z2p:BADVVmryioLExTGvKITEbSuDFHztNAyEeetBPpUmA8sA8Iu_y4eofHZmbbzIG2UU loginsucess
127.0.0.1 [12/05/2013:06:36:13 -0000] NEW z2p:qgBu2rqQh_9R4tDhD2qgqVx0Oy21Ezy6_E581eYvBv0AbuA5oMZAWw_l0vahOhiH address=127.0.0.1,app=cpaneld,creator=z2p,method=handle_form_login,path=form,possessed=0

The system logs the following types of entries:

  • NEW  — The system logs a NEW entry for each new temporary session.
  • PURGE  — The system logs a PURGE entry each time that it removes a temporary session.

NEW entries

NEW entries include the following information in a comma-separated list:

KeyDescriptionPossible valuesExample

(Session ID)

The session ID that the system created.

Note:

Unlike other log entry items, the session ID does not appear in key=value format. 

A valid session ID.
 Click to view...
z2p:BADVVmryioLExTGvKITEbSuDFHztNAyEeetBPpUmA8sA8Iu_y4eofHZmbbzIG2UU
addressThe IP address that requested the session.A valid IP address.
127.0.0.1
appThe application that created the session.A valid application or service name.
cpaneld
creatorThe WHM account that created the session.A valid WHM username.
z2p
methodThe method through which the user created the session.
  • handle_form_login — The creator logged in from a login form.
  • handle_auth_transfer — The creator logged in through a cPanel & WHM interface.
handle_form_login
pathThe path to the process that created the session.
  • A valid path.
  • form — The creator logged in from a login form.
form
possessedWhether the session runs with another user's privileges (impersonation).
  • 1 — The session runs with another user's privileges.
  • 0 — The session runs with the creator's privileges.
0

PURGE entries

PURGE entries include the session ID, and one of the following reason codes:

Reason codeDescription
badpassThe temporary session authentication failed.
expiredThe session expired.
killThe system stopped the session but did not provide a reason.
loadsessionThe creator logged in with a session token that the system destroyed when it created the new session.
loginsuccessThe creator logged in successfully and the system created a new session.
logoutThe creator logged out.
xfercpanelWHM transferred the session to cPanel.
xferwebmailcPanel transferred the session to Webmail.
xferwhmcPanel transferred the session to WHM.

Secure remote logins

To allow users to log in to cPanel & WHM remotely, write a script that calls the Cpanel::LogMeIn module's get_loggedin_url() subroutine. This subroutine returns a URL for remote logins to cPanel, WHM, or Webmail.

  • In cPanel & WHM version 11.38.0 and earlier, the URL is a single-use URL.
  • cPanel & WHM version 11.38.1 introduced reusable remote login URLs. These URLs expire when the user logs out, or after a normal session timeout.

Parameters

When you call the get_loggedin_url() subroutine, you must pass in the following parameters:

ParameterTypeDescriptionPossible valuesExample
userstring

Required

The cPanel, WHM, or Webmail username.

A valid username.

In most scripts, retrieve this value from user input.

username
passstring

Required

The account's password.

A secure password.

In most scripts, retrieve this value from user input.

12345luggage
hostnamestring

Required

The cPanel, WHM, or Webmail account's main domain.

A valid domain on the server.example.com
servicestring

Required

The account's service type.

  • cpanel
  • whm
  • webmail
cpanel
goto_uristring

Required

The location to which the script will redirect the user. The get_loggedin_url() subroutine uses this value to create the URL.

A valid path, relative to the /usr/local/cpanel/base/ directory./frontend/paper_lantern/park/index.html

Returns

The get_loggedin_url() subroutine returns the following values:

ReturnTypeDescriptionPossible valuesExample
login_okbooleanWhether the function authenticated the user successfully.
  • 1 — Success.
  • 0 — Failure.
1
login_messagestringA status message from the subroutine.
  • Login OK
  • An error message.
Login OK
login_urlstringThe secure remote login URL.A valid URL that includes a valid session token and directs the user to the goto_uri path.https://example.com:2083/cpsess##########/frontend/paper_lantern/park/index.html

Example

 Click to view...

Note:

This script reuses the session URL. For cPanel & WHM version 11.38.0 and earlier, you must call the get_loggedin_url() subroutine each time that you generate a URL. 

#!/usr/bin/perl 
 
use lib '/usr/local/cpanel';
use Cpanel::LogMeIn ();
  
# The cPanel, WHM, or Webmail username entered at login.
my $user    = 'YYYYYY'; 
 
# The cPanel, WHM, or Webmail password entered at login. 
my $pass    = 'XXXXXX';
 
# The cPanel, WHM, or Webmail account's main domain.
my $host    = 'localhost';
 
# The service to log in to (cpanel, whm, or webmail).
my $service = 'cpanel';
 
# Call the get_loggedin_url subroutine.
my ( $login_ok, $login_message, $login_url, $security_token ) = Cpanel::LogMeIn::get_loggedin_url(
    'user'     => $user,
    'pass'     => $pass,
    'hostname' => $host,
    'service'  => $service,
    'goto_uri' => '/'
);
  
# Set up HTTP headers with the returned values.
if ($login_ok) {
    print "Location: $login_url\r\n\r\n";
}
else {
    print "Content-type: text/plain\r\n\r\n";
    print "LOGIN FAILED: $login_message\n";
}
  
# Call the get_loggedin_url subroutine for a different URL.
( $login_ok, $login_message, $login_url, $security_token ) = Cpanel::LogMeIn::get_loggedin_url(
    'active_token_for_reuse'    => $security_token,                                                                                                                                                   
    'user'     => $user,
    'pass'     => $pass,
    'hostname' => $host,
    'service'  => $service,
    'goto_uri' => '/frontend/paper_lantern/park/index.html'
);
  
# Set up HTTP headers with the returned values.
if ($login_ok) {
    print "Location: $login_url\r\n\r\n";
}
else {
    print "Content-type: text/plain\r\n\r\n";
    print "LOGIN FAILED: $login_message\n";
}