1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace AtlassianConnectBundle\Service; |
6
|
|
|
|
7
|
|
|
use AtlassianConnectBundle\Entity\TenantInterface; |
8
|
|
|
use GuzzleHttp\ClientInterface; |
9
|
|
|
use GuzzleHttp\RequestOptions; |
10
|
|
|
use Psr\Http\Message\RequestInterface; |
11
|
|
|
|
12
|
|
|
class GuzzleJWTMiddleware |
13
|
|
|
{ |
14
|
|
|
public static function middleware(ClientInterface $client): callable |
15
|
|
|
{ |
16
|
|
|
return static function (callable $handler) use ($client): callable { |
17
|
|
|
return static function (RequestInterface $request, array $options) use ($handler, $client) { |
18
|
|
|
if (!\array_key_exists('tenant', $options) || !$options['tenant'] instanceof TenantInterface) { |
19
|
|
|
throw new \RuntimeException('Tenant not provided!'); |
20
|
|
|
} |
21
|
|
|
|
22
|
|
|
$tenant = $options['tenant']; |
23
|
|
|
|
24
|
|
|
if (\array_key_exists('user_id', $options) && null !== $options['user_id']) { |
25
|
|
|
if (!$tenant->getOauthClientId()) { |
26
|
|
|
throw new \RuntimeException('Tenant is not set up as oath application. Install the app with "ACT_AS_USER" scope.'); |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
return $handler($request |
30
|
|
|
->withHeader('Accept', 'application/json') |
31
|
|
|
->withHeader( |
32
|
|
|
'Authorization', |
33
|
|
|
'Bearer '.self::getAuthToken($client, $tenant->getOauthClientId(), $tenant->getSharedSecret(), $tenant->getBaseUrl(), $options['user_id']), |
|
|
|
|
34
|
|
|
), $options); |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
return $handler($request->withHeader( |
38
|
|
|
'Authorization', |
39
|
|
|
'JWT '.JWTGenerator::generate($request, $tenant->getAddonKey(), $tenant->getSharedSecret()), |
|
|
|
|
40
|
|
|
), $options); |
41
|
|
|
}; |
42
|
|
|
}; |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
private static function getAuthToken( |
46
|
|
|
ClientInterface $client, |
47
|
|
|
string $oauthClientId, |
48
|
|
|
string $secret, |
49
|
|
|
string $baseUrl, |
50
|
|
|
string $username |
51
|
|
|
): string { |
52
|
|
|
$result = $client->request('POST', 'https://oauth-2-authorization-server.services.atlassian.com/oauth2/token', [ |
53
|
|
|
RequestOptions::FORM_PARAMS => [ |
54
|
|
|
'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer', |
55
|
|
|
'assertion' => JWTGenerator::generateAssertion($secret, $oauthClientId, $baseUrl, $username), |
56
|
|
|
], |
57
|
|
|
]); |
58
|
|
|
|
59
|
|
|
return json_decode($result->getBody()->getContents(), true)['access_token']; |
60
|
|
|
} |
61
|
|
|
} |
62
|
|
|
|