Session API
Manage user sessions and authentication with support for two-factor authentication
Overview
The Session API provides endpoints for authenticating users, managing sessions, and handling two-factor authentication (2FA). Sessions are managed using JWT (JSON Web Token) tokens that authenticate all subsequent API requests.
The Session API supports authentication using login credentials (username and password). When 2FA is enabled for a user account, an additional security token must be provided during login.
Note: For API key authentication, see the JWT Tokens
documentation. API keys authenticate at the authentication layer and use the
/customer/jsonwebtoken endpoint to obtain JWT tokens.
POST Login (Create Session)
Authenticate a user and create a new session. Returns a JWT token for use in subsequent API requests.
Request
{
"cmd": "session.login",
"username": "user@example.com",
"password": "your_password",
"jwt": 1,
"serviceProviderCustomerId": 1,
"clientip": "192.168.1.1"
}
<?php
$ch = curl_init('https://api.rackcorp.net/api/rest/v2.9/json.php');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
'cmd' => 'session.login',
'username' => 'user@example.com',
'password' => 'your_password',
'jwt' => 1
]));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
$response = curl_exec($ch);
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$headers = substr($response, 0, $header_size);
$body = substr($response, $header_size);
$data = json_decode($body, true);
if ($data['code'] === 'OK') {
// Get JWT token from response
$jwt_token = $data['sessionId'];
// Or extract from Set-Cookie header
preg_match('/JWTSESSIONID=([^;]+)/', $headers, $matches);
if (isset($matches[1])) {
$jwt_token = $matches[1];
}
echo "JWT Token: " . $jwt_token . "\n";
} else {
echo "Login failed: " . $data['message'] . "\n";
}
curl_close($ch);
?>
import requests
response = requests.post(
'https://api.rackcorp.net/api/rest/v2.9/json.php',
json={
'cmd': 'session.login',
'username': 'user@example.com',
'password': 'your_password',
'jwt': 1
}
)
data = response.json()
if data['code'] == 'OK':
# Get token from response body
jwt_token = data.get('sessionId')
# Or get token from cookie
jwt_token = response.cookies.get('JWTSESSIONID')
print(f"JWT Token: {jwt_token}")
# Use token in subsequent requests
headers = {
'Authorization': f'Bearer {jwt_token}'
}
else:
print(f"Login failed: {data['message']}")
curl -X POST https://api.rackcorp.net/api/rest/v2.9/json.php \
-H "Content-Type: application/json" \
-d '{
"cmd": "session.login",
"username": "user@example.com",
"password": "your_password",
"jwt": 1
}' \
-c cookies.txt
Request Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
cmd |
string | Yes | Must be "session.login" |
username |
string | Yes | User's email address or username |
password |
string | Yes | User's password |
sectoken |
string | No | Two-factor authentication token (6-digit code). Required if 2FA is enabled for the account. |
2fatoken |
string | No | Alternative parameter name for 2FA token. Same as sectoken. |
jwt |
integer | No | Set to 1 to receive a JWT token in the response. Defaults to 0 if not provided. |
serviceProviderCustomerId |
integer | No | Service provider customer ID. Defaults to 1 if not provided. |
clientip |
string | No | Client IP address for logging purposes. Usually set automatically by the server. |
Response
On successful authentication:
{
"code": "OK",
"message": "Login successful",
"sessionId": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"user": {
"id": 123,
"login": "user@example.com",
"customerID": 456
}
}
The JWT token is returned in both the sessionId and token fields,
and also as a JWTSESSIONID cookie. Use this token in the Authorization header
or as a cookie for all subsequent API requests.
Error Responses
If authentication fails:
{
"code": "FAULT",
"message": "Invalid credentials"
}
If 2FA is required but not provided:
{
"code": "FAULT",
"message": "Two-factor authentication required"
}
POST Login with Two-Factor Authentication
When a user account has 2FA enabled, you must provide the 2FA token (6-digit code from the authenticator app) along with the username and password.
Request
{
"cmd": "session.login",
"username": "user@example.com",
"password": "your_password",
"sectoken": "123456",
"jwt": 1
}
<?php
$ch = curl_init('https://api.rackcorp.net/api/rest/v2.9/json.php');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
'cmd' => 'session.login',
'username' => 'user@example.com',
'password' => 'your_password',
'sectoken' => '123456', // 6-digit 2FA code
'jwt' => 1
]));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$data = json_decode($response, true);
if ($data['code'] === 'OK') {
$jwt_token = $data['sessionId'];
echo "JWT Token: " . $jwt_token . "\n";
} else {
echo "Login failed: " . $data['message'] . "\n";
}
curl_close($ch);
?>
import requests
# Login with 2FA
response = requests.post(
'https://api.rackcorp.net/api/rest/v2.9/json.php',
json={
'cmd': 'session.login',
'username': 'user@example.com',
'password': 'your_password',
'sectoken': '123456', # 6-digit 2FA code from authenticator app
'jwt': 1
}
)
data = response.json()
if data['code'] == 'OK':
jwt_token = data['sessionId']
print(f"JWT Token: {jwt_token}")
else:
print(f"Login failed: {data['message']}")
curl -X POST https://api.rackcorp.net/api/rest/v2.9/json.php \
-H "Content-Type: application/json" \
-d '{
"cmd": "session.login",
"username": "user@example.com",
"password": "your_password",
"sectoken": "123456",
"jwt": 1
}'
2FA Workflow
The typical workflow for handling 2FA is:
- Attempt login with username and password (without 2FA token)
- If the response indicates 2FA is required, prompt the user for their 2FA code
- Retry the login request with the 2FA token included
Example: Handling 2FA Programmatically
import requests
def login_with_2fa(username, password, two_factor_token=None):
"""Login with optional 2FA support"""
payload = {
'cmd': 'session.login',
'username': username,
'password': password,
'jwt': 1
}
# Add 2FA token if provided
if two_factor_token:
payload['sectoken'] = two_factor_token
response = requests.post(
'https://api.rackcorp.net/api/rest/v2.9/json.php',
json=payload
)
data = response.json()
if data['code'] == 'OK':
return data['sessionId']
elif 'two-factor' in data['message'].lower() or '2fa' in data['message'].lower():
# 2FA required - return None to indicate token needed
return None
else:
raise Exception(f"Login failed: {data['message']}")
# Usage
username = "user@example.com"
password = "your_password"
# First attempt without 2FA
token = login_with_2fa(username, password)
if token is None:
# 2FA required - prompt user for code
two_factor_code = input("Enter 2FA code: ")
token = login_with_2fa(username, password, two_factor_code)
if token:
print(f"Successfully logged in. JWT Token: {token}")
POST Logout (End Session)
Invalidate the current session and log out the user.
Request
{
"cmd": "session.logout"
}
<?php
$ch = curl_init('https://api.rackcorp.net/api/rest/v2.9/json.php');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
'cmd' => 'session.logout'
]));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer YOUR_JWT_TOKEN'
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$data = json_decode($response, true);
if ($data['code'] === 'OK') {
echo "Successfully logged out\n";
} else {
echo "Logout failed: " . $data['message'] . "\n";
}
curl_close($ch);
?>
import requests
response = requests.post(
'https://api.rackcorp.net/api/rest/v2.9/json.php',
json={
'cmd': 'session.logout'
},
headers={
'Authorization': 'Bearer YOUR_JWT_TOKEN'
}
)
data = response.json()
if data['code'] == 'OK':
print("Successfully logged out")
else:
print(f"Logout failed: {data['message']}")
curl -X POST https://api.rackcorp.net/api/rest/v2.9/json.php \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_JWT_TOKEN" \
-d '{
"cmd": "session.logout"
}'
Response
{
"code": "OK",
"message": "Logout successful"
}
Using Sessions
Once you have obtained a JWT token from session.login, use it to authenticate
all subsequent API requests. The token can be provided in one of two ways:
Authorization Header (Recommended)
Authorization: Bearer YOUR_JWT_TOKEN
Cookie
Cookie: JWTSESSIONID=YOUR_JWT_TOKEN
Example: Making Authenticated Requests
import requests
# First, login to get JWT token
login_response = requests.post(
'https://api.rackcorp.net/api/rest/v2.9/json.php',
json={
'cmd': 'session.login',
'username': 'user@example.com',
'password': 'your_password',
'jwt': 1
}
)
jwt_token = login_response.json()['sessionId']
# Use token in subsequent requests
headers = {
'Authorization': f'Bearer {jwt_token}'
}
# Example: Get load balancers
response = requests.get(
'https://api.rackcorp.net/api/rest/v2.9/json.php',
params={'cmd': 'loadbalancer.getall'},
headers=headers
)
print(response.json())
Error Handling
Common error codes and messages:
- FAULT - Invalid credentials, missing required parameters, or general authentication failure
- ACCESS_DENIED - Account is disabled, locked, or lacks permission to access the API
Always check the code field in the response before proceeding with API operations.
Security Best Practices
- Use API keys for automation - API keys are better suited for automated scripts and applications
- Store credentials securely - Never commit credentials to version control. Use environment variables or secure credential storage
- Enable 2FA - Two-factor authentication adds an extra layer of security to your account
- Rotate credentials regularly - Change passwords and regenerate API keys periodically
- Use HTTPS only - Always make API requests over HTTPS to protect credentials in transit
- Invalidate sessions when done - Call
session.logoutwhen your application is finished to invalidate the session