The Central Auth System is a Single Sign-On (SSO) solution that allows users to authenticate once and access multiple applications with the same credentials.
The system consists of the following components:
Register a new user account
{
"email": "user@example.com",
"phone": "1234567890",
"password": "secure_password"
}
{
"success": true,
"message": "User registered successfully",
"user_id": "550e8400-e29b-41d4-a716-446655440000"
}
| Field | Type | Required | Description |
|---|---|---|---|
| string | Optional | User's email address | |
| phone | string | Optional | User's phone number |
| password | string | Required | User's password (min 6 characters) |
Authenticate user and get access tokens
X-API-Key: your_project_api_key
{
"email": "user@example.com",
"password": "secure_password"
}
{
"success": true,
"message": "Login successful",
"user_id": "550e8400-e29b-41d4-a716-446655440000",
"role": "user",
"access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...",
"refresh_token": "def50200d8e3e3...",
"expires_in": 3600
}
| Field | Type | Required | Description |
|---|---|---|---|
| string | Optional | User's email address | |
| phone | string | Optional | User's phone number |
| password | string | Required | User's password |
Refresh access token using refresh token
X-API-Key: your_project_api_key
{
"refresh_token": "def50200d8e3e3..."
}
{
"success": true,
"message": "Token refreshed successfully",
"access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...",
"refresh_token": "def50200d8e3e3...",
"expires_in": 3600
}
| Field | Type | Required | Description |
|---|---|---|---|
| refresh_token | string | Required | Valid refresh token |
Verify access token validity
X-API-Key: your_project_api_key
{
"access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9..."
}
{
"success": true,
"user_id": "550e8400-e29b-41d4-a716-446655440000",
"role": "user",
"expires_at": "2023-12-01 15:30:00"
}
| Field | Type | Required | Description |
|---|---|---|---|
| access_token | string | Required | Access token to verify |
Logout user and revoke tokens
{
"access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9..."
}
{
"success": true,
"message": "Logged out successfully"
}
| Field | Type | Required | Description |
|---|---|---|---|
| access_token | string | Required | Access token to revoke |
CREATE TABLE `users` (
`id` VARCHAR(36) NOT NULL PRIMARY KEY,
`email` VARCHAR(255) UNIQUE,
`phone` VARCHAR(20) UNIQUE,
`password` VARCHAR(255) NOT NULL,
`role` ENUM('user', 'admin', 'service', 'superadmin') DEFAULT 'user',
`status` ENUM('active', 'blocked') DEFAULT 'active',
`created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
`updated_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
INDEX `idx_email` (`email`),
INDEX `idx_phone` (`phone`),
INDEX `idx_status` (`status`)
)
CREATE TABLE `projects` (
`id` INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
`name` VARCHAR(255) NOT NULL,
`domain` VARCHAR(255) NOT NULL,
`api_key` VARCHAR(255) NOT NULL UNIQUE,
`status` ENUM('active', 'inactive') DEFAULT 'active',
`created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
`updated_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
INDEX `idx_domain` (`domain`),
INDEX `idx_api_key` (`api_key`)
)
CREATE TABLE `tokens` (
`id` INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
`user_id` VARCHAR(36) NOT NULL,
`access_token` VARCHAR(255) NOT NULL UNIQUE,
`refresh_token` VARCHAR(255) NOT NULL UNIQUE,
`access_expires_at` DATETIME NOT NULL,
`refresh_expires_at` DATETIME NOT NULL,
`project_id` INT(11),
`status` ENUM('active', 'revoked', 'expired') DEFAULT 'active',
`ip_address` VARCHAR(45),
`user_agent` TEXT,
`created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
`updated_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE CASCADE,
FOREIGN KEY (`project_id`) REFERENCES `projects`(`id`) ON DELETE SET NULL,
INDEX `idx_access_token` (`access_token`),
INDEX `idx_refresh_token` (`refresh_token`),
INDEX `idx_user_id` (`user_id`),
INDEX `idx_status` (`status`)
)
CREATE TABLE `roles` ( `id` INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, `name` VARCHAR(50) NOT NULL UNIQUE, `permissions` JSON, `description` TEXT, `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP, `updated_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP )
CREATE TABLE `sessions` ( `id` VARCHAR(128) NOT NULL PRIMARY KEY, `user_id` VARCHAR(36) NOT NULL, `ip_address` VARCHAR(45) NOT NULL, `user_agent` TEXT, `payload` TEXT, `last_activity` INT(10) UNSIGNED NOT NULL, FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE CASCADE, INDEX `idx_last_activity` (`last_activity`) )
To integrate your application with the Central Auth System:
Before integrating, you need to register your project:
/admin/Proper token management is crucial for security:
password_hash() function<?php
class SSOClient {
private $authServiceUrl;
private $apiKey;
public function __construct($authServiceUrl, $apiKey) {
$this->authServiceUrl = $authServiceUrl;
$this->apiKey = $apiKey;
}
public function register($email, $password) {
$data = [
'email' => $email,
'password' => $password
];
$response = $this->makeRequest('/api/register', $data);
return $response;
}
public function login($email, $password) {
$data = [
'email' => $email,
'password' => $password
];
$response = $this->makeRequest('/api/login', $data);
return $response;
}
public function verifyToken($accessToken) {
$data = [
'access_token' => $accessToken
];
$response = $this->makeRequest('/api/auth/verify', $data);
return $response;
}
public function refreshAccessToken($refreshToken) {
$data = [
'refresh_token' => $refreshToken
];
$response = $this->makeRequest('/api/token/refresh', $data);
return $response;
}
public function logout($accessToken) {
$data = [
'access_token' => $accessToken
];
$response = $this->makeRequest('/api/logout', $data);
return $response;
}
private function makeRequest($endpoint, $data) {
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => $this->authServiceUrl . $endpoint,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => json_encode($data),
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
'X-API-Key: ' . $this->apiKey
],
]);
$response = curl_exec($curl);
$httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
return [
'success' => $httpCode === 200,
'data' => json_decode($response, true),
'http_code' => $httpCode
];
}
}
// Usage example:
$sso = new SSOClient('http://your-auth-service.com', 'your_api_key');
// Verify existing token
$verifyResult = $sso->verifyToken($_COOKIE['access_token']);
if ($verifyResult['success'] && $verifyResult['data']['success']) {
// User is authenticated
echo "Welcome, user " . $verifyResult['data']['user_id'];
} else {
// Redirect to login
header('Location: login.php');
}
?>
// SSO Client for JavaScript
class SSOClient {
constructor(authServiceUrl, apiKey) {
this.authServiceUrl = authServiceUrl;
this.apiKey = apiKey;
}
async register(email, password) {
const response = await fetch(`${this.authServiceUrl}/api/register`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ email, password })
});
return await response.json();
}
async login(email, password) {
const response = await fetch(`${this.authServiceUrl}/api/login`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-API-Key': this.apiKey
},
body: JSON.stringify({ email, password })
});
return await response.json();
}
async verifyToken(accessToken) {
const response = await fetch(`${this.authServiceUrl}/api/auth/verify`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-API-Key': this.apiKey
},
body: JSON.stringify({ access_token: accessToken })
});
return await response.json();
}
async refreshToken(refreshToken) {
const response = await fetch(`${this.authServiceUrl}/api/token/refresh`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-API-Key': this.apiKey
},
body: JSON.stringify({ refresh_token: refreshToken })
});
return await response.json();
}
async logout(accessToken) {
const response = await fetch(`${this.authServiceUrl}/api/logout`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ access_token: accessToken })
});
return await response.json();
}
}
// Usage example:
const sso = new SSOClient('http://your-auth-service.com', 'your_api_key');
// Check if user is logged in
if (localStorage.getItem('accessToken')) {
const result = await sso.verifyToken(localStorage.getItem('accessToken'));
if (result.success) {
// User is authenticated
document.getElementById('user-info').textContent = `User ID: ${result.user_id}`;
} else {
// Token invalid, redirect to login
window.location.href = 'login.html';
}
}
<?php
session_start();
// Check if user is authenticated
function isAuthenticated() {
if (isset($_SESSION['user']) && isset($_SESSION['access_token'])) {
// Verify token is still valid
$sso = new SSOClient('http://your-auth-service.com', 'your_api_key');
$result = $sso->verifyToken($_SESSION['access_token']);
if ($result['success'] && $result['data']['success']) {
return true;
} else {
// Token invalid, clear session
clearSession();
return false;
}
}
return false;
}
// Refresh access token if needed
function refreshIfNeeded() {
if (isset($_SESSION['refresh_token'])) {
// Check if access token is about to expire
// In a real implementation, you'd check the actual expiration time
$sso = new SSOClient('http://your-auth-service.com', 'your_api_key');
$result = $sso->refreshAccessToken($_SESSION['refresh_token']);
if ($result['success']) {
$_SESSION['access_token'] = $result['data']['access_token'];
$_SESSION['refresh_token'] = $result['data']['refresh_token'];
}
}
}
// Clear user session
function clearSession() {
unset($_SESSION['user']);
unset($_SESSION['access_token']);
unset($_SESSION['refresh_token']);
session_destroy();
}
// Protect pages
if (!isAuthenticated()) {
header('Location: login.php');
exit;
}
// Refresh token if needed
refreshIfNeeded();
echo "Welcome, user " . $_SESSION['user']['user_id'];
?>