1
|
|
|
<?php declare(strict_types = 1); |
2
|
|
|
|
3
|
|
|
namespace AtlassianConnectBundle\Service; |
4
|
|
|
|
5
|
|
|
use GuzzleHttp\Client; |
6
|
|
|
use GuzzleHttp\Middleware; |
7
|
|
|
use GuzzleHttp\Psr7\Request; |
8
|
|
|
use Psr\Http\Message\RequestInterface; |
9
|
|
|
|
10
|
|
|
/** |
11
|
|
|
* Class GuzzleJWTMiddleware |
12
|
|
|
*/ |
13
|
|
|
class GuzzleJWTMiddleware |
14
|
|
|
{ |
15
|
|
|
/** |
16
|
|
|
* JWT Authentication middleware for Guzzle |
17
|
|
|
* |
18
|
|
|
* @param string $issuer Add-on key in most cases |
19
|
|
|
* @param string $secret Shared secret |
20
|
|
|
* |
21
|
|
|
* @return callable |
22
|
|
|
*/ |
23
|
|
|
public static function authTokenMiddleware(string $issuer, string $secret): callable |
24
|
|
|
{ |
25
|
|
|
return Middleware::mapRequest( |
26
|
|
|
function (RequestInterface $request) use ($issuer, $secret) { |
27
|
|
|
return new Request( |
28
|
|
|
$request->getMethod(), |
29
|
|
|
$request->getUri(), |
30
|
|
|
\array_merge($request->getHeaders(), ['Authorization' => 'JWT '.JWTGenerator::generate($request, $issuer, $secret)]), |
31
|
|
|
$request->getBody() |
32
|
|
|
); |
33
|
|
|
} |
34
|
|
|
); |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* @param string $oauthClientId |
39
|
|
|
* @param string $secret |
40
|
|
|
* @param string $baseUrl |
41
|
|
|
* @param string $username |
42
|
|
|
* |
43
|
|
|
* @return callable |
44
|
|
|
*/ |
45
|
|
|
public static function authUserTokenMiddleware(string $oauthClientId, string $secret, string $baseUrl, string $username): callable |
46
|
|
|
{ |
47
|
|
|
return Middleware::mapRequest( |
48
|
|
|
function (RequestInterface $request) use ($oauthClientId, $secret, $baseUrl, $username) { |
49
|
|
|
return new Request( |
50
|
|
|
$request->getMethod(), |
51
|
|
|
$request->getUri(), |
52
|
|
|
\array_merge($request->getHeaders(), [ |
53
|
|
|
'Authorization' => 'Bearer '.self::getAuthToken($oauthClientId, $secret, $baseUrl, $username), |
54
|
|
|
'Accept' => 'application/json', |
55
|
|
|
]), |
56
|
|
|
$request->getBody() |
57
|
|
|
); |
58
|
|
|
} |
59
|
|
|
); |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
/** |
63
|
|
|
* @param string $oauthClientId |
64
|
|
|
* @param string $secret |
65
|
|
|
* @param string $baseUrl |
66
|
|
|
* @param string $username |
67
|
|
|
* |
68
|
|
|
* @return string |
69
|
|
|
*/ |
70
|
|
|
private static function getAuthToken(string $oauthClientId, string $secret, string $baseUrl, string $username): string |
71
|
|
|
{ |
72
|
|
|
$result = (new Client())->post('https://auth.atlassian.io/oauth2/token', [ |
73
|
|
|
'form_params' => [ |
74
|
|
|
'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer', |
75
|
|
|
'assertion' => JWTGenerator::generateAssertion($secret, $oauthClientId, $baseUrl, $username), |
76
|
|
|
'scope' => 'READ WRITE', |
77
|
|
|
], |
78
|
|
|
]); |
79
|
|
|
|
80
|
|
|
return \json_decode($result->getBody()->getContents(), true)['access_token']; |
81
|
|
|
} |
82
|
|
|
} |
83
|
|
|
|