Repository navigation
Expand file tree
/
Copy pathtoken-generator.php
More file actions
170 lines (148 loc) · 6.62 KB
/
Copy pathtoken-generator.php
File metadata and controls
170 lines (148 loc) · 6.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
<?php
/**
* FCS API - Token Generator (PHP)
*
* Generate secure tokens for frontend JavaScript authentication
*
* Usage:
* 1. Set your accessKey and publicKey
* 2. Call generateToken()
* 3. Pass the token data to your frontend JavaScript
*
* @package FcsApi
* @author FCS API <support@fcsapi.com>
* @link https://fcsapi.com
*/
class FcsTokenGenerator {
/**
* Your API Access Key (Private Key)
* Get from: https://fcsapi.com/dashboard
*/
private string $accessKey = 'YOUR_ACCESS_KEY_HERE';
/**
* Your Public Key
* Get from: https://fcsapi.com/dashboard
*/
private string $publicKey = 'YOUR_PUBLIC_KEY_HERE';
/**
* Token expiry time in seconds
* Options: 300 (5min), 900 (15min), 1800 (30min), 3600 (1hr), 86400 (24hr)
*/
private int $tokenExpiry = 3600;
/**
* Constructor
* @param string|null $accessKey Your API access key
* @param string|null $publicKey Your public key
* @param int $tokenExpiry Token expiry in seconds
*/
public function __construct(?string $accessKey = null, ?string $publicKey = null, int $tokenExpiry = 3600) {
if ($accessKey) $this->accessKey = $accessKey;
if ($publicKey) $this->publicKey = $publicKey;
$this->tokenExpiry = $tokenExpiry;
}
/**
* Generate token for frontend authentication
* @return array Token data with _token, _expiry, _public_key
*/
public function generateToken(): array {
$expiry = time() + $this->tokenExpiry;
$message = $this->publicKey . $expiry;
$token = hash_hmac('sha256', $message, $this->accessKey);
return [
'_token' => $token,
'_expiry' => $expiry,
'_public_key' => $this->publicKey
];
}
/**
* Generate and output as JSON (for AJAX requests)
*/
public function outputJson(): void {
header('Content-Type: application/json');
echo json_encode($this->generateToken());
}
/**
* Generate meta tags for HTML head
* @return string HTML meta tags
*/
public function getMetaTags(): string {
$token = $this->generateToken();
return sprintf(
'<meta name="fcs-public-key" content="%s">' . "\n" .
'<meta name="fcs-token" content="%s">' . "\n" .
'<meta name="fcs-token-expiry" content="%s">',
htmlspecialchars($token['_public_key']),
htmlspecialchars($token['_token']),
$token['_expiry']
);
}
/**
* Generate a JWT (header.payload.signature) that the client sends alone as the parameter jwt_token.
* @param string $domain '' = plain token (works from any site), 'customer.com' = token that only works from that site
* @return string the JWT
*/
public function generateJwt(string $domain = ''): string {
return self::createJwt($this->publicKey, $this->accessKey, $this->tokenExpiry, $domain);
}
/**
* Build a JWT without an object: payload {"pub","exp"}, signed HMAC-SHA256 with the access key (plain) or with hex(HMAC-SHA256("jwt|" . domain, access key)) (bound to one site).
* @param int $seconds how long the token stays valid (30 to 86400 is the range the mint endpoint allows)
* @param string $domain must be the exact page host the browser sends as Origin (scheme, www., port and path are removed)
* @throws InvalidArgumentException when a key is empty, seconds is below 1, or a non-empty domain is not a valid host
*/
public static function createJwt(string $publicKey, string $accessKey, int $seconds = 300, string $domain = ''): string {
if ($publicKey === '' || $accessKey === '' || $seconds < 1) {
throw new InvalidArgumentException('publicKey, accessKey and seconds (1 or more) are required');
}
// The signing key is the access key itself, or a key derived from it and the domain when the token is bound.
$key = $accessKey;
if ($domain !== '') {
$host = self::normalizeDomain($domain);
if ($host === '') {
throw new InvalidArgumentException('domain is not a valid host name: ' . $domain);
}
$key = hash_hmac('sha256', 'jwt|' . $host, $accessKey);
}
$head = self::base64Url('{"alg":"HS256","typ":"JWT"}');
$body = self::base64Url(json_encode(['pub' => $publicKey, 'exp' => time() + $seconds], JSON_UNESCAPED_SLASHES));
$sig = self::base64Url(hash_hmac('sha256', $head . '.' . $body, $key, true));
return $head . '.' . $body . '.' . $sig;
}
// Base64url without padding, the JWT way.
private static function base64Url(string $bin): string {
return rtrim(strtr(base64_encode($bin), '+/', '-_'), '=');
}
// Same host normalisation as the FCS API server: lowercase, no scheme, no "www.", no port, no path.
private static function normalizeDomain(string $value): string {
$value = strtolower(trim($value));
if ($value === '' || $value === 'null') return '';
if (strpos($value, '://') !== false) {
$value = (string)parse_url($value, PHP_URL_HOST);
} else {
$value = explode('/', $value, 2)[0];
if (substr_count($value, ':') === 1) $value = explode(':', $value, 2)[0];
}
$value = trim($value, '.');
if (strncmp($value, 'www.', 4) === 0) $value = substr($value, 4);
if ($value === '' || strlen($value) > 253 || !preg_match('/^[a-z0-9._:\[\]-]+$/', $value)) return '';
return $value;
}
}
// ============================================
// USAGE EXAMPLES
// ============================================
// Example 1: Generate token and pass to frontend
// $generator = new FcsTokenGenerator('your_access_key', 'your_public_key');
// $tokenData = $generator->generateToken();
// Pass $tokenData to your JavaScript
// Example 2: Output as JSON for AJAX
// $generator = new FcsTokenGenerator('your_access_key', 'your_public_key');
// $generator->outputJson();
// Example 3: Generate meta tags for HTML
// $generator = new FcsTokenGenerator('your_access_key', 'your_public_key');
// echo $generator->getMetaTags();
// Example 4: JWT token (the client sends only this one value, as jwt_token)
// $generator = new FcsTokenGenerator('your_access_key', 'your_public_key', 300);
// $jwt = $generator->generateJwt(); // plain: works from any site (or from Allowed Domains if you saved some)
// $jwt = $generator->generateJwt('customer.com'); // bound: only works when the browser's Origin is customer.com
// https://api-v4.fcsapi.com/forex/latest?symbol=EUR/USD&jwt_token=<jwt> (or header "Authorization: Bearer <jwt>")