Skip to content

Commit 24e0322

Browse files
author
Neuman Vong
committed
Start tracking project
0 parents  commit 24e0322

File tree

7 files changed

+367
-0
lines changed

7 files changed

+367
-0
lines changed

JWT.php

Lines changed: 164 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,164 @@
1+
<?php
2+
3+
/**
4+
* JSON Web Token implementation
5+
*
6+
* Minimum implementation used by Realtime auth, based on this spec:
7+
* http://self-issued.info/docs/draft-jones-json-web-token-01.html.
8+
*
9+
* @author Neuman Vong <[email protected]>
10+
*/
11+
class JWT
12+
{
13+
/**
14+
* @param string $jwt The JWT
15+
* @param string|null $key The secret key
16+
* @param bool $verify Don't skip verification process
17+
*
18+
* @return object The JWT's payload as a PHP object
19+
*/
20+
public static function decode($jwt, $key = null, $verify = true)
21+
{
22+
$tks = explode('.', $jwt);
23+
if (count($tks) != 3) {
24+
throw new UnexpectedValueException('Wrong number of segments');
25+
}
26+
list($headb64, $payloadb64, $cryptob64) = $tks;
27+
if (null === ($header = JWT::jsonDecode(JWT::urlsafeB64Decode($headb64)))
28+
) {
29+
throw new UnexpectedValueException('Invalid segment encoding');
30+
}
31+
if (null === $payload = JWT::jsonDecode(JWT::urlsafeB64Decode($payloadb64))
32+
) {
33+
throw new UnexpectedValueException('Invalid segment encoding');
34+
}
35+
$sig = JWT::urlsafeB64Decode($cryptob64);
36+
if ($verify) {
37+
if (empty($header->alg)) {
38+
throw new DomainException('Empty algorithm');
39+
}
40+
if ($sig != JWT::sign("$headb64.$payloadb64", $key, $header->alg)) {
41+
throw new UnexpectedValueException('Signature verification failed');
42+
}
43+
}
44+
return $payload;
45+
}
46+
47+
/**
48+
* @param object|array $payload PHP object or array
49+
* @param string $key The secret key
50+
* @param string $algo The signing algorithm
51+
*
52+
* @return string A JWT
53+
*/
54+
public static function encode($payload, $key, $algo = 'HS256')
55+
{
56+
$header = array('typ' => 'jwt', 'alg' => $algo);
57+
58+
$segments = array();
59+
$segments[] = JWT::urlsafeB64Encode(JWT::jsonEncode($header));
60+
$segments[] = JWT::urlsafeB64Encode(JWT::jsonEncode($payload));
61+
$signing_input = implode('.', $segments);
62+
63+
$signature = JWT::sign($signing_input, $key, $algo);
64+
$segments[] = JWT::urlsafeB64Encode($signature);
65+
66+
return implode('.', $segments);
67+
}
68+
69+
/**
70+
* @param string $msg The message to sign
71+
* @param string $key The secret key
72+
* @param string $method The signing algorithm
73+
*
74+
* @return string An encrypted message
75+
*/
76+
public static function sign($msg, $key, $method = 'HS256')
77+
{
78+
$methods = array(
79+
'HS256' => 'sha256',
80+
'HS384' => 'sha384',
81+
'HS512' => 'sha512',
82+
);
83+
if (empty($methods[$method])) {
84+
throw new DomainException('Algorithm not supported');
85+
}
86+
return hash_hmac($methods[$method], $msg, $key, true);
87+
}
88+
89+
/**
90+
* @param string $input JSON string
91+
*
92+
* @return object Object representation of JSON string
93+
*/
94+
public static function jsonDecode($input)
95+
{
96+
$obj = json_decode($input);
97+
if (function_exists('json_last_error') && $errno = json_last_error()) {
98+
JWT::handleJsonError($errno);
99+
}
100+
else if ($obj === null && $input !== 'null') {
101+
throw new DomainException('Null result with non-null input');
102+
}
103+
return $obj;
104+
}
105+
106+
/**
107+
* @param object|array $input A PHP object or array
108+
*
109+
* @return string JSON representation of the PHP object or array
110+
*/
111+
public static function jsonEncode($input)
112+
{
113+
$json = json_encode($input);
114+
if (function_exists('json_last_error') && $errno = json_last_error()) {
115+
JWT::handleJsonError($errno);
116+
}
117+
else if ($json === 'null' && $input !== null) {
118+
throw new DomainException('Null result with non-null input');
119+
}
120+
return $json;
121+
}
122+
123+
/**
124+
* @param string $input A base64 encoded string
125+
*
126+
* @return string A decoded string
127+
*/
128+
public static function urlsafeB64Decode($input)
129+
{
130+
$padlen = 4 - strlen($input) % 4;
131+
$input .= str_repeat('=', $padlen);
132+
return base64_decode(strtr($input, '-_', '+/'));
133+
}
134+
135+
/**
136+
* @param string $input Anything really
137+
*
138+
* @return string The base64 encode of what you passed in
139+
*/
140+
public static function urlsafeB64Encode($input)
141+
{
142+
return str_replace('=', '', strtr(base64_encode($input), '+/', '-_'));
143+
}
144+
145+
/**
146+
* @param int $errno An error number from json_last_error()
147+
*
148+
* @return void
149+
*/
150+
private static function handleJsonError($errno)
151+
{
152+
$messages = array(
153+
JSON_ERROR_DEPTH => 'Maximum stack depth exceeded',
154+
JSON_ERROR_CTRL_CHAR => 'Unexpected control character found',
155+
JSON_ERROR_SYNTAX => 'Syntax error, malformed JSON'
156+
);
157+
throw new DomainException(isset($messages[$errno])
158+
? $messages[$errno]
159+
: 'Unknown JSON error: ' . $errno
160+
);
161+
}
162+
163+
}
164+

Makefile

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
all: test
2+
test:
3+
@echo running tests
4+
@phpunit --configuration tests/phpunit.xml
5+
6+
.PHONY: all test

package.php

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
<?php
2+
3+
require_once 'PEAR/PackageFileManager2.php';
4+
PEAR::setErrorHandling(PEAR_ERROR_DIE);
5+
6+
$api_version = '0.0.0';
7+
$api_state = 'alpha';
8+
9+
$release_version = '0.0.0';
10+
$release_state = 'alpha';
11+
$release_notes = "No release notes.";
12+
13+
$description = <<<DESC
14+
A JWT encoder/decoder.
15+
DESC;
16+
17+
$package = new PEAR_PackageFileManager2();
18+
19+
$package->setOptions(
20+
array(
21+
'filelistgenerator' => 'file',
22+
'simpleoutput' => true,
23+
'baseinstalldir' => '/',
24+
'packagedirectory' => './',
25+
'dir_roles' => array(
26+
'tests' => 'test'
27+
),
28+
'ignore' => array(
29+
'package.php',
30+
'*.tgz'
31+
)
32+
)
33+
);
34+
35+
$package->setPackage('JWT');
36+
$package->setSummary('A JWT encoder/decoder.');
37+
$package->setDescription($description);
38+
$package->setChannel('pear.php.net');
39+
$package->setPackageType('php');
40+
$package->setLicense(
41+
'MIT License',
42+
'http://creativecommons.org/licenses/MIT/'
43+
);
44+
45+
$package->setNotes($release_notes);
46+
$package->setReleaseVersion($release_version);
47+
$package->setReleaseStability($release_state);
48+
$package->setAPIVersion($api_version);
49+
$package->setAPIStability($api_state);
50+
51+
$package->addMaintainer(
52+
'lead',
53+
'lcfrs',
54+
'Neuman Vong',
55+
56+
);
57+
58+
$package->addExtensionDep('required', 'json');
59+
$package->addExtensionDep('required', 'hash_hmac');
60+
61+
$package->setPhpDep('5.1');
62+
63+
$package->setPearInstallerDep('1.7.0');
64+
$package->generateContents();
65+
$package->addRelease();
66+
67+
if ( isset($_GET['make'])
68+
|| (isset($_SERVER['argv']) && @$_SERVER['argv'][1] == 'make')
69+
) {
70+
$package->writePackageFile();
71+
} else {
72+
$package->debugPackageFile();
73+
}
74+
75+
?>

package.xml

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<package packagerversion="1.9.2" version="2.0" xmlns="http://pear.php.net/dtd/package-2.0" xmlns:tasks="http://pear.php.net/dtd/tasks-1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://pear.php.net/dtd/tasks-1.0
3+
http://pear.php.net/dtd/tasks-1.0.xsd
4+
http://pear.php.net/dtd/package-2.0
5+
http://pear.php.net/dtd/package-2.0.xsd">
6+
<name>JWT</name>
7+
<channel>pear.php.net</channel>
8+
<summary>A JWT encoder/decoder.</summary>
9+
<description>A JWT encoder/decoder.</description>
10+
<lead>
11+
<name>Neuman Vong</name>
12+
<user>lcfrs</user>
13+
<email>[email protected]</email>
14+
<active>yes</active>
15+
</lead>
16+
<date>2011-03-25</date>
17+
<time>16:09:40</time>
18+
<version>
19+
<release>0.0.0</release>
20+
<api>0.0.0</api>
21+
</version>
22+
<stability>
23+
<release>alpha</release>
24+
<api>alpha</api>
25+
</stability>
26+
<license uri="http://creativecommons.org/licenses/MIT/">MIT License</license>
27+
<notes>
28+
No release notes.
29+
</notes>
30+
<contents>
31+
<dir baseinstalldir="/" name="/">
32+
<dir name="tests">
33+
<file name="Bootstrap.php" role="test" />
34+
<file name="JWTTest.php" role="test" />
35+
<file name="phpunit.xml" role="test" />
36+
</dir> <!-- //tests -->
37+
<file name="JWT.php" role="php" />
38+
<file name="Makefile" role="data" />
39+
</dir> <!-- / -->
40+
</contents>
41+
<dependencies>
42+
<required>
43+
<php>
44+
<min>5.1</min>
45+
</php>
46+
<pearinstaller>
47+
<min>1.7.0</min>
48+
</pearinstaller>
49+
<extension>
50+
<name>json</name>
51+
</extension>
52+
<extension>
53+
<name>hash_hmac</name>
54+
</extension>
55+
</required>
56+
</dependencies>
57+
<phprelease />
58+
<changelog>
59+
<release>
60+
<version>
61+
<release>0.0.0</release>
62+
<api>0.0.0</api>
63+
</version>
64+
<stability>
65+
<release>alpha</release>
66+
<api>alpha</api>
67+
</stability>
68+
<date>2011-03-25</date>
69+
<license uri="http://creativecommons.org/licenses/MIT/">MIT License</license>
70+
<notes>
71+
No release notes.
72+
</notes>
73+
</release>
74+
</changelog>
75+
</package>

tests/Bootstrap.php

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
<?php
2+
3+
error_reporting(E_ALL | E_STRICT);
4+
ini_set('display_errors', 1);
5+
6+
$root = realpath(dirname(dirname(__FILE__)));
7+
require_once $root . '/JWT.php';
8+
9+
unset($root);

tests/JWTTest.php

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
<?php
2+
3+
class JWTTests extends PHPUnit_Framework_TestCase {
4+
function testEncodeDecode() {
5+
$msg = JWT::encode('abc', 'my_key');
6+
$this->assertEquals(JWT::decode($msg, 'my_key'), 'abc');
7+
}
8+
9+
function testDecodeFromPython() {
10+
$msg = 'eyJhbGciOiAiSFMyNTYiLCAidHlwIjogIkpXVCJ9.Iio6aHR0cDovL2FwcGxpY2F0aW9uL2NsaWNreT9ibGFoPTEuMjMmZi5vbz00NTYgQUMwMDAgMTIzIg.E_U8X2YpMT5K1cEiT_3-IvBYfrdIFIeVYeOqre_Z5Cg';
11+
$this->assertEquals(
12+
JWT::decode($msg, 'my_key'),
13+
'*:http://application/clicky?blah=1.23&f.oo=456 AC000 123'
14+
);
15+
}
16+
17+
function testUrlSafeCharacters() {
18+
$encoded = JWT::encode('f?', 'a');
19+
$this->assertEquals('f?', JWT::decode($encoded, 'a'));
20+
}
21+
22+
function testMalformedUtf8StringsFail() {
23+
$this->setExpectedException('DomainException');
24+
JWT::encode(pack('c', 128), 'a');
25+
}
26+
27+
function testMalformedJsonThrowsException() {
28+
$this->setExpectedException('DomainException');
29+
JWT::jsonDecode('this is not valid JSON string');
30+
}
31+
}

tests/phpunit.xml

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
<phpunit bootstrap="./Bootstrap.php">
2+
<testsuites>
3+
<testsuite name="Services Twilio Test Suite">
4+
<directory>./</directory>
5+
</testsuite>
6+
</testsuites>
7+
</phpunit>

0 commit comments

Comments
 (0)