-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathClientCredentialsTrait.php
93 lines (77 loc) · 2.62 KB
/
ClientCredentialsTrait.php
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
<?php
/**
* Trait ClientCredentialsTrait
*
* @created 19.09.2024
* @author smiley <smiley@chillerlan.net>
* @copyright 2024 smiley
* @license MIT
*/
declare(strict_types=1);
namespace chillerlan\OAuth\Core;
use chillerlan\HTTP\Utils\QueryUtil;
use Psr\Http\Message\ResponseInterface;
use function implode;
use const PHP_QUERY_RFC1738;
/**
* Implements Client Credentials functionality
*
* @see \chillerlan\OAuth\Core\ClientCredentials
*/
trait ClientCredentialsTrait{
/**
* implements ClientCredentials::getClientCredentialsToken()
*
* @see \chillerlan\OAuth\Core\ClientCredentials::getClientCredentialsToken()
*
* @param string[]|null $scopes
* @throws \chillerlan\OAuth\Providers\ProviderException
*/
public function getClientCredentialsToken(array|null $scopes = null):AccessToken{
$body = $this->getClientCredentialsTokenRequestBodyParams($scopes);
$response = $this->sendClientCredentialsTokenRequest(($this->clientCredentialsTokenURL ?? $this->accessTokenURL), $body);
$token = $this->parseTokenResponse($response);
// provider didn't send a set of scopes with the token response, so add the given ones manually
if(empty($token->scopes)){
$token->scopes = ($scopes ?? []);
}
$this->storage->storeAccessToken($token, $this->name);
return $token;
}
/**
* prepares the request body parameters for the client credentials token request
*
* @see \chillerlan\OAuth\Core\OAuth2Provider::getClientCredentialsToken()
*
* @param string[]|null $scopes
* @return array<string, string>
*/
protected function getClientCredentialsTokenRequestBodyParams(array|null $scopes):array{
$body = ['grant_type' => 'client_credentials'];
if(!empty($scopes)){
$body['scope'] = implode($this::SCOPES_DELIMITER, $scopes);
}
return $body;
}
/**
* sends a request to the client credentials endpoint, using basic authentication
*
* @see \chillerlan\OAuth\Core\OAuth2Provider::getClientCredentialsToken()
*
* @param array<string, scalar> $body
*/
protected function sendClientCredentialsTokenRequest(string $url, array $body):ResponseInterface{
$request = $this->requestFactory
->createRequest('POST', $url)
->withHeader('Accept', 'application/json')
->withHeader('Accept-Encoding', 'identity')
->withHeader('Content-Type', 'application/x-www-form-urlencoded')
->withBody($this->streamFactory->createStream(QueryUtil::build($body, PHP_QUERY_RFC1738)))
;
foreach($this::HEADERS_AUTH as $header => $value){
$request = $request->withHeader($header, $value);
}
$request = $this->addBasicAuthHeader($request);
return $this->http->sendRequest($request);
}
}