|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Eljam\GuzzleJwt\Tests; |
|
4
|
|
|
|
|
5
|
|
|
use Eljam\GuzzleJwt\JwtMiddleware; |
|
6
|
|
|
use Eljam\GuzzleJwt\Manager\JwtManager; |
|
7
|
|
|
use Eljam\GuzzleJwt\Strategy\Auth\HttpBasicAuthStrategy; |
|
8
|
|
|
use GuzzleHttp\Client; |
|
9
|
|
|
use GuzzleHttp\HandlerStack; |
|
10
|
|
|
use GuzzleHttp\Handler\MockHandler; |
|
11
|
|
|
use GuzzleHttp\Promise\FulfilledPromise; |
|
12
|
|
|
use GuzzleHttp\Psr7\Response; |
|
13
|
|
|
use Psr\Http\Message\RequestInterface; |
|
14
|
|
|
|
|
15
|
|
|
/** |
|
16
|
|
|
* @author Guillaume Cavavana <[email protected]> |
|
17
|
|
|
*/ |
|
18
|
|
|
class JwtMiddlewareTest extends \PHPUnit_Framework_TestCase |
|
19
|
|
|
{ |
|
20
|
|
|
/** |
|
21
|
|
|
* testJwtAuthorizationHeader. |
|
22
|
|
|
*/ |
|
23
|
|
|
public function testJwtAuthorizationHeader() |
|
24
|
|
|
{ |
|
25
|
|
|
$authMockHandler = new MockHandler([ |
|
26
|
|
|
new Response( |
|
27
|
|
|
200, |
|
28
|
|
|
['Content-Type' => 'application/json'], |
|
29
|
|
|
json_encode(['token' => 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9']) |
|
30
|
|
|
) |
|
31
|
|
|
]); |
|
32
|
|
|
|
|
33
|
|
|
$authClient = new Client(['handler' => $authMockHandler]); |
|
34
|
|
|
$jwtManager = new JwtManager( |
|
35
|
|
|
$authClient, |
|
36
|
|
|
(new HttpBasicAuthStrategy(['username' => 'test', 'password' => 'test'])) |
|
37
|
|
|
); |
|
38
|
|
|
|
|
39
|
|
|
$mockHandler = new MockHandler([ |
|
40
|
|
|
function (RequestInterface $request) { |
|
41
|
|
|
$this->assertTrue($request->hasHeader('Authorization')); |
|
42
|
|
|
$this->assertSame( |
|
43
|
|
|
sprintf(JwtMiddleware::AUTH_BEARER, 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9'), |
|
44
|
|
|
$request->getHeader('Authorization')[0] |
|
45
|
|
|
); |
|
46
|
|
|
|
|
47
|
|
|
return new Response(200, [], json_encode(['data' => 'pong'])); |
|
48
|
|
|
} |
|
49
|
|
|
]); |
|
50
|
|
|
|
|
51
|
|
|
$handler = HandlerStack::create($mockHandler); |
|
52
|
|
|
$handler->push(new JwtMiddleware($jwtManager)); |
|
53
|
|
|
|
|
54
|
|
|
$client = new Client(['handler' => $handler]); |
|
55
|
|
|
$client->get('http://api.example.com/api/ping'); |
|
56
|
|
|
} |
|
57
|
|
|
} |
|
58
|
|
|
|