Repository navigation
Expand file tree
/
Copy pathOAuth2ClientCredentials.php
More file actions
83 lines (64 loc) · 3.8 KB
/
Copy pathOAuth2ClientCredentials.php
File metadata and controls
83 lines (64 loc) · 3.8 KB
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
<?php
/**
* REDCap External Module: REDCap REST
* Send API calls when saving particular instruments when a trigger condition is met.
* @author Luke Stevens, Murdoch Children's Research Institute
*/
namespace MCRI\REDCapREST;
class OAuth2ClientCredentials extends OAuth2 {
public function oauth2Call(string $method, string $url, string $contentType, array $headers, array $curlOptions, string $payload, $allowRetry=true): void {
// update access token if needed (first connection or expired)
$this->updateAccessToken();
$authHeaders = $headers;
$authHeaders[] = "Authorization: Bearer ".$this->access_token;
list($this->response, $this->info) = $this->module->curlCall($method, $url, $contentType, $authHeaders, $curlOptions, $payload);
if (($this->info['http_code'] === 401 || $this->info['http_code'] === 403) && $allowRetry) {
// retry once with new token
$this->access_token = null;
$this->access_token_expiry = null;
$this->updateAccessToken();
$authHeaders = $headers;
$authHeaders[] = "Authorization: Bearer ".$this->access_token;
list($this->response, $this->info) = $this->module->curlCall($method, $url, $contentType, $authHeaders, $curlOptions, $payload);
}
}
/**
* updateAccessToken()
* If there is a cached and unexpired access token then do nothing, otherwise obtain a new token
*/
protected function updateAccessToken(): void {
// if have unexpired access token then do nothing
if (!empty($this->access_token) && !empty($this->access_token_expiry)) {
$tokenRefreshAt = $this->access_token_expiry->sub(new \DateInterval('PT5M'));
$now = new \DateTime("now");
if ($now < $tokenRefreshAt) return;
}
// obtain an access token
$payload = http_build_query(array('grant_type' => 'client_credentials'));
$curlOptions = array(array(CURLOPT_USERPWD, $this->client_id.":".$this->client_secret));
list($response, $info) = $this->module->curlCall('POST', $this->token_endpoint, 'application/x-www-form-urlencoded', array(), $curlOptions, $payload);
$httpCode = $info['http_code'] ?? 'unknown';
$tokenDetails = json_decode($response, true);
// Mask the response body before it reaches any log line or exception message.
// 1) Mask resolved [token-ref:...] values (e.g. client-id/client-secret) via
// the module's single source of truth. 2) Mask the returned access_token so
// it never appears in cleartext (also run defensively on error bodies).
$maskedBody = $this->module->maskSecrets($response);
if (isset($tokenDetails['access_token']) && $tokenDetails['access_token'] !== '') {
$maskedBody = str_replace($tokenDetails['access_token'], '|||access_token removed|||', $maskedBody);
}
// Log every token exchange attempt (success and failure).
$this->module->log('OAuth2 token exchange: POST '.$this->token_endpoint.' -> HTTP '.$httpCode.' body: '.$maskedBody);
if (!isset($info['http_code']) || $info['http_code'] !== 200) {
throw new \Exception('Unable to obtain access token (HTTP '.$httpCode.'): '.$maskedBody);
}
if (!isset($tokenDetails['access_token']) || !isset($tokenDetails['expires_in'])) {
throw new \Exception('Unexpected access token response (HTTP '.$httpCode.'): '.$maskedBody);
}
$this->access_token = $tokenDetails['access_token'];
$now = new \DateTime("now");
$this->access_token_expiry = clone $now;
$this->access_token_expiry = $this->access_token_expiry->add(new \DateInterval('PT'.intval($tokenDetails['expires_in']).'S'));
$this->saveAccessToken();
}
}