Skip to content

Commit

Permalink
Add test for authenticate function
Browse files Browse the repository at this point in the history
  • Loading branch information
ricklambrechts committed Sep 30, 2024
1 parent 144f855 commit 2dde092
Showing 1 changed file with 64 additions and 0 deletions.
64 changes: 64 additions & 0 deletions tests/OpenIDConnectClientTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,70 @@ public function testAuthenticateDoesNotThrowExceptionIfClaimsIsMissingNonce()
}
}

public function testAuthenticateWithCodeThrowsExceptionIfStateDoesNotMatch()
{
$_REQUEST['code'] = 'some-code';
$_REQUEST['state'] = "incorrect-state-from-user";
$_SESSION['openid_connect_state'] = "random-generated-state";

$client = new OpenIDConnectClient();

try {
$client->authenticate();
} catch ( OpenIDConnectClientException $e ) {
$this->assertEquals('Unable to determine state', $e->getMessage());
return;
}

$this->fail('OpenIDConnectClientException was not thrown when it should have been.');
}

public function testAuthenticateWithCodeMockedVerify()
{
$mockCode = 'some-code';

$_REQUEST['code'] = $mockCode;
$_REQUEST['state'] = "random-generated-state";
$_SESSION['openid_connect_state'] = "random-generated-state";

$mockClaims = (object)['email' => '[email protected]'];
$mockIdToken = implode('.', [base64_encode('{}'), base64_encode(json_encode($mockClaims)), '']);
$mockAccessToken = 'some-access-token';
$mockRefreshToken = 'some-access-token';

$mockTokenResponse = (object)[
'id_token' => $mockIdToken,
'access_token' => $mockAccessToken,
'refresh_token' => $mockRefreshToken,
];

$client = $this->getMockBuilder(OpenIDConnectClient::class)
->setMethods(['requestTokens', 'verifySignatures', 'verifyJWTClaims'])
->getMock();
$client->method('requestTokens')
->with($mockCode)
->willReturn($mockTokenResponse);
$client->method('verifySignatures')
->with($mockIdToken);
$client->method('verifyJWTClaims')
->with($mockClaims, $mockAccessToken)
->willReturn(true);

try {
// In this mocked case we should be authenticated
// because we are not actually verifying the JWT
$authenticated = $client->authenticate();
$this->assertTrue($authenticated);
$this->assertEquals($mockIdToken, $client->getIdToken());
$this->assertEquals($mockAccessToken, $client->getAccessToken());
$this->assertEquals($mockTokenResponse, $client->getTokenResponse());
$this->assertEquals($mockClaims, $client->getVerifiedClaims());
$this->assertEquals($mockRefreshToken, $client->getRefreshToken());
} catch ( OpenIDConnectClientException $e ) {
$this->fail('OpenIDConnectClientException was thrown when it should not have been.');
}
}

public function testSerialize()
{
$client = new OpenIDConnectClient('https://example.com', 'foo', 'bar', 'baz');
Expand Down

0 comments on commit 2dde092

Please sign in to comment.