Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for authorization code grant with PKCE for distributed apps #1067

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@ test/config/test.sqlite
vendor
composer.lock
.idea
.phpunit.result.cache
56 changes: 54 additions & 2 deletions src/OAuth2/Controller/AuthorizeController.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace OAuth2\Controller;

use OAuth2\Storage\ClientCredentialsInterface;
use OAuth2\Storage\ClientInterface;
use OAuth2\ScopeInterface;
use OAuth2\RequestInterface;
Expand Down Expand Up @@ -61,6 +62,16 @@ class AuthorizeController implements AuthorizeControllerInterface
*/
protected $scopeUtil;

/**
* @var string|null
*/
protected $code_challenge;

/**
* @var string|null
*/
protected $code_challenge_method;

/**
* Constructor
*
Expand Down Expand Up @@ -88,6 +99,8 @@ public function __construct(ClientInterface $clientStorage, array $responseTypes
'require_exact_redirect_uri' => true,
'redirect_status_code' => 302,
'enforce_pkce' => false,
'enforce_pkce_for_public_clients' => false,
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ℹ️ this should probably default to true for new installs, but that could be a breaking change for existing installs. Leaving this at false allows for releasing as a minor version. Would recommend defaulting to true for the next major version.

'supported_code_challenge_methods' => ['plain', 'S256'],
), $config);

if (is_null($scopeUtil)) {
Expand Down Expand Up @@ -139,7 +152,7 @@ public function handleAuthorizeRequest(RequestInterface $request, ResponseInterf

$authResult = $this->responseTypes[$this->response_type]->getAuthorizeResponse($params, $user_id);

list($redirect_uri, $uri_params) = $authResult;
[$redirect_uri, $uri_params] = $authResult;

if (empty($redirect_uri) && !empty($registered_redirect_uri)) {
$redirect_uri = $registered_redirect_uri;
Expand Down Expand Up @@ -186,6 +199,8 @@ protected function buildAuthorizeParameters($request, $response, $user_id)
'client_id' => $this->client_id,
'redirect_uri' => $this->redirect_uri,
'response_type' => $this->response_type,
'code_challenge' => $this->code_challenge,
'code_challenge_method' => $this->code_challenge_method,
);

return $params;
Expand Down Expand Up @@ -257,7 +272,7 @@ public function validateAuthorizeRequest(RequestInterface $request, ResponseInte
$response_type = $request->query('response_type', $request->request('response_type'));

// for multiple-valued response types - make them alphabetical
if (false !== strpos($response_type, ' ')) {
if ($response_type && false !== strpos($response_type, ' ')) {
$types = explode(' ', $response_type);
sort($types);
$response_type = ltrim(implode(' ', $types));
Expand Down Expand Up @@ -334,13 +349,50 @@ public function validateAuthorizeRequest(RequestInterface $request, ResponseInte
return false;
}

$code_challenge = $request->query('code_challenge');
$code_challenge_method = $request->query('code_challenge_method');
if ($code_challenge) {
if (preg_match('/^[A-Za-z0-9-._~]{43,128}$/', $code_challenge) !== 1) {
$response->setError(400, 'invalid_code_challenge', 'The PKCE code challenge supplied is invalid');

return false;
}

$supported_challenge_methods = $this->config['supported_code_challenge_methods'] ?? ['plain', 'S256'];
if (!$code_challenge_method) {
$response->setError(400, 'missing_code_challenge_method', 'This application requires you specify a PKCE code challenge method. Supported methods: ' . implode(', ', $supported_challenge_methods)
);

return false;
}
if (!in_array($code_challenge_method, $supported_challenge_methods, true)) {
$response->setError(400, 'invalid_code_challenge_method', 'The PKCE code challenge method supplied is invalid. Supported methods: ' . implode(', ', $supported_challenge_methods)
);

return false;
}
} else {
$isPublic = false;
if ($this->clientStorage instanceof ClientCredentialsInterface) {
$isPublic = $this->clientStorage->isPublicClient($client_id);
Comment on lines +376 to +377
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ℹ️ not sure why there are two interfaces, but the property is only typed to the higher level one which doesn't have the method we need.

}

if ($this->config['enforce_pkce'] || ($this->config['enforce_pkce_for_public_clients'] && $isPublic)) {
$response->setError(400, 'missing_code_challenge', 'This application requires you provide a PKCE code challenge');

return false;
}
}

// save the input data and return true
$this->scope = $requestedScope;
$this->state = $state;
$this->client_id = $client_id;
// Only save the SUPPLIED redirect URI (@see http://tools.ietf.org/html/rfc6749#section-4.1.3)
$this->redirect_uri = $supplied_redirect_uri;
$this->response_type = $response_type;
$this->code_challenge = $code_challenge;
$this->code_challenge_method = $code_challenge_method;

return true;
}
Expand Down
2 changes: 1 addition & 1 deletion src/OAuth2/GrantType/AuthorizationCode.php
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ public function validateRequest(RequestInterface $request, ResponseInterface $re

return FALSE;
}
if ($code_verifier_hashed !== $authCode['code_challenge']) {
if (!hash_equals($authCode['code_challenge'], $code_verifier_hashed)) {
$response->setError(400, 'code_verifier_mismatch', "The PKCE code verifier parameter does not match the code challenge.");

return FALSE;
Expand Down
42 changes: 1 addition & 41 deletions src/OAuth2/OpenID/Controller/AuthorizeController.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
use OAuth2\ResponseInterface;

/**
* @see OAuth2\Controller\AuthorizeControllerInterface
* @see \OAuth2\Controller\AuthorizeControllerInterface
*/
class AuthorizeController extends BaseAuthorizeController implements AuthorizeControllerInterface
{
Expand All @@ -16,16 +16,6 @@ class AuthorizeController extends BaseAuthorizeController implements AuthorizeCo
*/
private $nonce;

/**
* @var mixed
*/
protected $code_challenge;
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ℹ️ these properties and their behavior moved to the parent class


/**
* @var mixed
*/
protected $code_challenge_method;

/**
* Set not authorized response
*
Expand Down Expand Up @@ -75,10 +65,6 @@ protected function buildAuthorizeParameters($request, $response, $user_id)
// add the nonce to return with the redirect URI
$params['nonce'] = $this->nonce;

// Add PKCE code challenge.
$params['code_challenge'] = $this->code_challenge;
$params['code_challenge_method'] = $this->code_challenge_method;

return $params;
}

Expand All @@ -104,32 +90,6 @@ public function validateAuthorizeRequest(RequestInterface $request, ResponseInte

$this->nonce = $nonce;

$code_challenge = $request->query('code_challenge');
$code_challenge_method = $request->query('code_challenge_method');

if ($this->config['enforce_pkce']) {
if (!$code_challenge) {
$response->setError(400, 'missing_code_challenge', 'This application requires you provide a PKCE code challenge');

return false;
}

if (preg_match('/^[A-Za-z0-9-._~]{43,128}$/', $code_challenge) !== 1) {
$response->setError(400, 'invalid_code_challenge', 'The PKCE code challenge supplied is invalid');

return false;
}

if (!in_array($code_challenge_method, array('plain', 'S256'), true)) {
$response->setError(400, 'missing_code_challenge_method', 'This application requires you specify a PKCE code challenge method');

return false;
}
}

$this->code_challenge = $code_challenge;
$this->code_challenge_method = $code_challenge_method;

return true;
}

Expand Down
4 changes: 3 additions & 1 deletion src/OAuth2/Server.php
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,8 @@ public function __construct($storage = array(), array $config = array(), array $
'require_exact_redirect_uri' => true,
'allow_implicit' => false,
'enforce_pkce' => false,
'enforce_pkce_for_public_clients' => false,
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ℹ️ same comment about default value

'supported_code_challenge_methods' => array('plain', 'S256'),
'allow_credentials_in_request_body' => true,
'allow_public_clients' => true,
'always_issue_new_refresh_token' => false,
Expand Down Expand Up @@ -578,7 +580,7 @@ protected function createDefaultAuthorizeController()
}
}

$config = array_intersect_key($this->config, array_flip(explode(' ', 'allow_implicit enforce_state require_exact_redirect_uri enforce_pkce')));
$config = array_intersect_key($this->config, array_flip(explode(' ', 'allow_implicit enforce_state require_exact_redirect_uri enforce_pkce enforce_pkce_for_public_clients supported_code_challenge_methods')));

if ($this->config['use_openid_connect']) {
return new OpenIDAuthorizeController($this->storages['client'], $this->responseTypes, $config, $this->getScopeUtil());
Expand Down
121 changes: 121 additions & 0 deletions test/OAuth2/Controller/AuthorizeControllerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -342,6 +342,125 @@ public function testUserDeniesAccessResponse()
$this->assertEquals($query['error_description'], 'The user denied access to your application');
}

public function testEnforcePkce()
{
$server = $this->getTestServer(array('enforce_pkce' => true));
$request = new Request(array(
'client_id' => 'Test Client ID', // valid client id
'redirect_uri' => 'http://adobe.com', // valid redirect URI
'response_type' => 'code',
'state' => 'xyz',
));
$server->handleAuthorizeRequest($request, $response = new Response(), true);

$this->assertEquals($response->getStatusCode(), 400);
$this->assertEquals('missing_code_challenge', $response->getParameter('error'));
$this->assertEquals('This application requires you provide a PKCE code challenge', $response->getParameter('error_description'));
}

public function testEnforcePkcePublicClient()
{
$server = $this->getTestServer(array('enforce_pkce_for_public_clients' => true));
$request = new Request(array(
'client_id' => 'Test Public Client ID', // valid client id
'redirect_uri' => 'http://adobe.com', // valid redirect URI
'response_type' => 'code',
'state' => 'xyz',
));
$server->handleAuthorizeRequest($request, $response = new Response(), true);

$this->assertEquals($response->getStatusCode(), 400);
$this->assertEquals('missing_code_challenge', $response->getParameter('error'));
$this->assertEquals('This application requires you provide a PKCE code challenge', $response->getParameter('error_description'));
}

public function testInvalidCodeChallenge()
{
$server = $this->getTestServer(array('enforce_pkce' => true));
$request = new Request(array(
'client_id' => 'Test Client ID', // valid client id
'redirect_uri' => 'http://adobe.com', // valid redirect URI
'response_type' => 'code',
'state' => 'xyz',
'code_challenge' => 'invalid!',
'code_challenge_method' => 'plain',
));
$server->handleAuthorizeRequest($request, $response = new Response(), true);

$this->assertEquals($response->getStatusCode(), 400);
$this->assertEquals('invalid_code_challenge', $response->getParameter('error'));
$this->assertEquals('The PKCE code challenge supplied is invalid', $response->getParameter('error_description'));
}

public function testMissingCodeChallengeMethod()
{
$server = $this->getTestServer(array('enforce_pkce' => true));
$request = new Request(array(
'client_id' => 'Test Client ID', // valid client id
'redirect_uri' => 'http://adobe.com', // valid redirect URI
'response_type' => 'code',
'state' => 'xyz',
'code_challenge' => 'E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM',
));
$server->handleAuthorizeRequest($request, $response = new Response(), true);

$this->assertEquals($response->getStatusCode(), 400);
$this->assertEquals('missing_code_challenge_method', $response->getParameter('error'));
$this->assertEquals('This application requires you specify a PKCE code challenge method. Supported methods: plain, S256', $response->getParameter('error_description'));
}

public function testInvalidCodeChallengeMethod()
{
$server = $this->getTestServer(array('enforce_pkce' => true));
$request = new Request(array(
'client_id' => 'Test Client ID', // valid client id
'redirect_uri' => 'http://adobe.com', // valid redirect URI
'response_type' => 'code',
'state' => 'xyz',
'code_challenge' => 'E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM',
'code_challenge_method' => 'invalid',
));
$server->handleAuthorizeRequest($request, $response = new Response(), true);

$this->assertEquals($response->getStatusCode(), 400);
$this->assertEquals('invalid_code_challenge_method', $response->getParameter('error'));
$this->assertEquals('The PKCE code challenge method supplied is invalid. Supported methods: plain, S256', $response->getParameter('error_description'));
}

public function testSuccessfulPkceChallenge()
{
$server = $this->getTestServer(array('enforce_pkce' => true));
$request = new Request(array(
'client_id' => 'Test Client ID', // valid client id
'redirect_uri' => 'http://adobe.com', // valid redirect URI
'response_type' => 'code',
'state' => 'xyz',
'code_challenge' => 'E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM',
'code_challenge_method' => 'S256',
));
$server->handleAuthorizeRequest($request, $response = new Response(), true);

$this->assertEquals($response->getStatusCode(), 302);
$location = $response->getHttpHeader('Location');
$parts = parse_url($location);
parse_str($parts['query'], $query);

$this->assertEquals('http', $parts['scheme']); // same as passed in to redirect_uri
$this->assertEquals('adobe.com', $parts['host']); // same as passed in to redirect_uri
$this->assertArrayHasKey('query', $parts);
$this->assertFalse(isset($parts['fragment']));

// assert fragment is in "application/x-www-form-urlencoded" format
parse_str($parts['query'], $query);
$this->assertNotNull($query);
$this->assertArrayHasKey('code', $query);

// assert code challenge is stored
$code = $server->getStorage('authorization_code')->getAuthorizationCode($query['code']);
$this->assertEquals($code['code_challenge'], 'E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM');
$this->assertEquals($code['code_challenge_method'], 'S256');
}

public function testCodeQueryParamIsSet()
{
$server = $this->getTestServer();
Expand Down Expand Up @@ -478,6 +597,8 @@ public function testCreateController()
{
$storage = Bootstrap::getInstance()->getMemoryStorage();
$controller = new AuthorizeController($storage);

$this->expectNotToPerformAssertions();
}

private function getTestServer($config = array())
Expand Down
Loading