summaryrefslogtreecommitdiffstats
path: root/tests/JWTTest.php
blob: 21498623a348409e4d53bc8fb199c9bac1598f60 (plain)
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
<?php

class JWTTest extends PHPUnit_Framework_TestCase {
	function testEncodeDecode() {
		$msg = JWT::encode('abc', 'my_key');
		$this->assertEquals(JWT::decode($msg, 'my_key'), 'abc');
	}

	function testDecodeFromPython() {
		$msg = 'eyJhbGciOiAiSFMyNTYiLCAidHlwIjogIkpXVCJ9.Iio6aHR0cDovL2FwcGxpY2F0aW9uL2NsaWNreT9ibGFoPTEuMjMmZi5vbz00NTYgQUMwMDAgMTIzIg.E_U8X2YpMT5K1cEiT_3-IvBYfrdIFIeVYeOqre_Z5Cg';
		$this->assertEquals(
			JWT::decode($msg, 'my_key'),
			'*:http://application/clicky?blah=1.23&f.oo=456 AC000 123'
		);
	}

	function testUrlSafeCharacters() {
		$encoded = JWT::encode('f?', 'a');
		$this->assertEquals('f?', JWT::decode($encoded, 'a'));
	}

	function testMalformedUtf8StringsFail() {
		$this->setExpectedException('DomainException');
		JWT::encode(pack('c', 128), 'a');
	}

	function testMalformedJsonThrowsException() {
		$this->setExpectedException('DomainException');
		JWT::jsonDecode('this is not valid JSON string');
	}

	function testExpiredToken() {
		$this->setExpectedException('UnexpectedValueException');
		$payload = array(
			"message" => "abc",
			"exp" => time() - 20); // time in the past
		$encoded = JWT::encode($payload, 'my_key');
		JWT::decode($encoded);
	}

	function testValidToken() {
		$payload = array(
			"message" => "abc",
			"exp" => time() + 20); // time in the future
		$encoded = JWT::encode($payload, 'my_key');
		$decoded = JWT::decode($encoded, 'my_key');
		$this->assertEquals($decoded->message, 'abc');
	}

	function testInvalidToken() {
		$payload = array(
			"message" => "abc",
			"exp" => time() + 20); // time in the future
		$encoded = JWT::encode($payload, 'my_key');
		$this->setExpectedException('UnexpectedValueException');
		$decoded = JWT::decode($encoded, 'my_key2');
	}

	function testRSEncodeDecode() {
		$privKey = openssl_pkey_new(array('digest_alg' => 'sha256',
			'private_key_bits' => 1024,
			'private_key_type' => OPENSSL_KEYTYPE_RSA));
		$msg = JWT::encode('abc', $privKey, 'RS256');
		$pubKey = openssl_pkey_get_details($privKey);
		$pubKey = $pubKey['key'];
		$decoded = JWT::decode($msg, $pubKey, true);
		$this->assertEquals($decoded, 'abc');
	}

	function testKIDChooser() {
		$keys = array('1' => 'my_key', '2' => 'my_key2');
		$msg = JWT::encode('abc', $keys['1'], 'HS256', '1');
		$decoded = JWT::decode($msg, $keys, true);
		$this->assertEquals($decoded, 'abc');
	}

}

?>