Skip to content

Commit ec8a123

Browse files
authored
Merge pull request #94 from docusign/DEVDOCS-15094
DEVDOCS-15094: adding PKCE
2 parents 6fafaeb + df27017 commit ec8a123

File tree

1 file changed

+47
-2
lines changed

1 file changed

+47
-2
lines changed

OAuth/code_grant.php

Lines changed: 47 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,13 +30,29 @@
3030
$scope = "signature aow_manage";
3131
endif;
3232

33+
function generateCodeVerifier() {
34+
return bin2hex(random_bytes(32));
35+
}
36+
37+
function generateCodeChallenge($code_verifier) {
38+
return rtrim(strtr(base64_encode(hash('sha256', $code_verifier, true)), '+/', '-_'), '=');
39+
}
40+
41+
$use_pkce = true;
42+
$code_verifier = generateCodeVerifier();
43+
$code_challenge = generateCodeChallenge($code_verifier);
44+
45+
$_SESSION['code_verifier'] = $code_verifier;
46+
3347
$authorizationURL = $authorizationEndpoint . 'auth?' . http_build_query(
3448
[
3549
'redirect_uri' => $redirectURI,
3650
'scope' => $scope,
3751
'client_id' => $clientID,
3852
'state' => $state,
39-
'response_type' => 'code'
53+
'response_type' => 'code',
54+
'code_challenge' => $code_challenge,
55+
'code_challenge_method' => 'S256'
4056
]
4157
);
4258

@@ -64,17 +80,46 @@
6480
$authorizationEndpoint . 'token', [
6581
'grant_type' => 'authorization_code',
6682
'redirect_uri' => $redirectURI,
67-
'code' => $code
83+
'code' => $code,
84+
'code_verifier' => $code_verifier
6885
], [
6986
'Authorization: Basic ' . base64_encode($clientID . ':' .$clientSecret),
7087
], true
7188
);
7289

7390
if (!isset($response->access_token)) {
7491
echo "\nError fetching access token\n";
92+
$use_pkce = false;
93+
echo "\nPKCE failed\n";
7594
exit(2);
7695
}
7796

97+
if (!$use_pkce) {
98+
// Start Authorization Code Grant flow without PKCE
99+
$authorizationURL = $authorizationEndpoint . 'auth?' . http_build_query([
100+
'redirect_uri' => $redirectURI,
101+
'scope' => $scope,
102+
'client_id' => $clientID,
103+
'state' => $state,
104+
'response_type' => 'code'
105+
]);}
106+
107+
if (!$use_pkce){
108+
$code = $auth['code'];
109+
echo "\nGetting an access token...\n";
110+
111+
$response = http(
112+
$authorizationEndpoint . 'token', [
113+
'grant_type' => 'authorization_code',
114+
'redirect_uri' => $redirectURI,
115+
'code' => $code
116+
], [
117+
'Authorization: Basic ' . base64_encode($clientID . ':' .$clientSecret),
118+
], true
119+
);
120+
121+
}
122+
78123
$accessToken = $response->access_token;
79124
file_put_contents($outputFile, $accessToken);
80125
echo "\nAccess token has been written to " . $outputFile . "\n\n";

0 commit comments

Comments
 (0)