From 1b692e22982d0972905d393e19a9e0855cc8eb81 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sergio=20G=C3=B3mez?= Date: Thu, 18 Jan 2018 05:31:44 +0100 Subject: [PATCH] Fix S256 code challenge method According to [RFC7636#section-4.3](https://tools.ietf.org/html/rfc7636#section-4.3): If the "code_challenge_method" from Section 4.3 was "S256", the received "code_verifier" is hashed by SHA-256, base64url-encoded, and then compared to the "code_challenge", i.e.: BASE64URL-ENCODE(SHA256(ASCII(code_verifier))) == code_challenge So, the hash must be done before the base64_encode. The tests are modified to use example data from the [RFC7636#appendix-B](https://tools.ietf.org/html/rfc7636#appendix-B). --- src/Grant/AuthCodeGrant.php | 2 +- tests/Grant/AuthCodeGrantTest.php | 8 ++++++-- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/src/Grant/AuthCodeGrant.php b/src/Grant/AuthCodeGrant.php index 6f2b6ff8..18720f45 100644 --- a/src/Grant/AuthCodeGrant.php +++ b/src/Grant/AuthCodeGrant.php @@ -144,7 +144,7 @@ class AuthCodeGrant extends AbstractAuthorizeGrant case 'S256': if ( hash_equals( - hash('sha256', strtr(rtrim(base64_encode($codeVerifier), '='), '+/', '-_')), + strtr(rtrim(base64_encode(hash('sha256', $codeVerifier, true)), '='), '+/', '-_'), $authCodePayload->code_challenge ) === false ) { diff --git a/tests/Grant/AuthCodeGrantTest.php b/tests/Grant/AuthCodeGrantTest.php index 6d0e801e..97206a76 100644 --- a/tests/Grant/AuthCodeGrantTest.php +++ b/tests/Grant/AuthCodeGrantTest.php @@ -744,6 +744,10 @@ class AuthCodeGrantTest extends TestCase $grant->setRefreshTokenRepository($refreshTokenRepositoryMock); $grant->setEncryptionKey($this->cryptStub->getKey()); + // [RFC 7636] Appendix B. Example for the S256 code_challenge_method + $codeVerifier = 'dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk'; + $codeChallenge = 'E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM'; + $request = new ServerRequest( [], [], @@ -757,7 +761,7 @@ class AuthCodeGrantTest extends TestCase 'grant_type' => 'authorization_code', 'client_id' => 'foo', 'redirect_uri' => 'http://foo/bar', - 'code_verifier' => 'foobar', + 'code_verifier' => $codeVerifier, 'code' => $this->cryptStub->doEncrypt( json_encode( [ @@ -767,7 +771,7 @@ class AuthCodeGrantTest extends TestCase 'user_id' => 123, 'scopes' => ['foo'], 'redirect_uri' => 'http://foo/bar', - 'code_challenge' => hash('sha256', strtr(rtrim(base64_encode('foobar'), '='), '+/', '-_')), + 'code_challenge' => $codeChallenge, 'code_challenge_method' => 'S256', ] )