Merge pull request #476 from juliangut/fixes

Fixes
This commit is contained in:
Alex Bilbie 2016-03-18 11:04:43 +01:00
commit c880d5c1ec
21 changed files with 391 additions and 314 deletions

View File

@ -12,7 +12,8 @@
}, },
"require-dev": { "require-dev": {
"phpunit/phpunit": "^4.8", "phpunit/phpunit": "^4.8",
"league/plates": "^3.1" "league/plates": "^3.1",
"zendframework/zend-diactoros": "^1.0"
}, },
"repositories": [ "repositories": [
{ {

View File

@ -108,7 +108,7 @@ trait CryptTrait
while ($encryptedData) { while ($encryptedData) {
$chunk = substr($encryptedData, 0, $chunkSize); $chunk = substr($encryptedData, 0, $chunkSize);
$encryptedData = substr($encryptedData, $chunkSize); $encryptedData = substr($encryptedData, $chunkSize);
if (openssl_public_decrypt($chunk, $decrypted, $publicKey, OPENSSL_PKCS1_OAEP_PADDING) === false) { if (openssl_public_decrypt($chunk, $decrypted, $publicKey/*, OPENSSL_PKCS1_OAEP_PADDING*/) === false) {
// @codeCoverageIgnoreStart // @codeCoverageIgnoreStart
throw new \LogicException('Failed to decrypt data'); throw new \LogicException('Failed to decrypt data');
// @codeCoverageIgnoreEnd // @codeCoverageIgnoreEnd

View File

@ -16,11 +16,11 @@ class AccessTokenEntity implements AccessTokenEntityInterface
/** /**
* Generate a JWT from the access token * Generate a JWT from the access token
* *
* @param string $pathToPrivateKey * @param string $privateKeyPath
* *
* @return string * @return string
*/ */
public function convertToJWT($pathToPrivateKey) public function convertToJWT($privateKeyPath)
{ {
return (new Builder()) return (new Builder())
->setAudience($this->getClient()->getIdentifier()) ->setAudience($this->getClient()->getIdentifier())
@ -30,7 +30,7 @@ class AccessTokenEntity implements AccessTokenEntityInterface
->setExpiration($this->getExpiryDateTime()->getTimestamp()) ->setExpiration($this->getExpiryDateTime()->getTimestamp())
->setSubject($this->getUserIdentifier()) ->setSubject($this->getUserIdentifier())
->set('scopes', $this->getScopes()) ->set('scopes', $this->getScopes())
->sign(new Sha256(), new Key($pathToPrivateKey)) ->sign(new Sha256(), new Key($privateKeyPath))
->getToken(); ->getToken();
} }
} }

View File

@ -7,9 +7,9 @@ interface AccessTokenEntityInterface extends TokenInterface
/** /**
* Generate a JWT from the access token * Generate a JWT from the access token
* *
* @param string $pathToPrivateKey * @param string $privateKeyPath
* *
* @return string * @return string
*/ */
public function convertToJWT($pathToPrivateKey); public function convertToJWT($privateKeyPath);
} }

View File

@ -13,7 +13,7 @@ use League\OAuth2\Server\Repositories\UserRepositoryInterface;
use League\OAuth2\Server\ResponseTypes\HtmlResponse; use League\OAuth2\Server\ResponseTypes\HtmlResponse;
use League\OAuth2\Server\ResponseTypes\RedirectResponse; use League\OAuth2\Server\ResponseTypes\RedirectResponse;
use League\OAuth2\Server\ResponseTypes\ResponseTypeInterface; use League\OAuth2\Server\ResponseTypes\ResponseTypeInterface;
use League\OAuth2\Server\TemplateRenderer\AbstractRenderer; use League\OAuth2\Server\TemplateRenderer\RendererInterface;
use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Message\ServerRequestInterface;
class AuthCodeGrant extends AbstractAuthorizeGrant class AuthCodeGrant extends AbstractAuthorizeGrant
@ -28,14 +28,14 @@ class AuthCodeGrant extends AbstractAuthorizeGrant
* @param \League\OAuth2\Server\Repositories\RefreshTokenRepositoryInterface $refreshTokenRepository * @param \League\OAuth2\Server\Repositories\RefreshTokenRepositoryInterface $refreshTokenRepository
* @param \League\OAuth2\Server\Repositories\UserRepositoryInterface $userRepository * @param \League\OAuth2\Server\Repositories\UserRepositoryInterface $userRepository
* @param \DateInterval $authCodeTTL * @param \DateInterval $authCodeTTL
* @param \League\OAuth2\Server\TemplateRenderer\AbstractRenderer|null $templateRenderer * @param \League\OAuth2\Server\TemplateRenderer\RendererInterface|null $templateRenderer
*/ */
public function __construct( public function __construct(
AuthCodeRepositoryInterface $authCodeRepository, AuthCodeRepositoryInterface $authCodeRepository,
RefreshTokenRepositoryInterface $refreshTokenRepository, RefreshTokenRepositoryInterface $refreshTokenRepository,
UserRepositoryInterface $userRepository, UserRepositoryInterface $userRepository,
\DateInterval $authCodeTTL, \DateInterval $authCodeTTL,
AbstractRenderer $templateRenderer = null RendererInterface $templateRenderer = null
) { ) {
$this->setAuthCodeRepository($authCodeRepository); $this->setAuthCodeRepository($authCodeRepository);
$this->setRefreshTokenRepository($refreshTokenRepository); $this->setRefreshTokenRepository($refreshTokenRepository);
@ -282,7 +282,9 @@ class AuthCodeGrant extends AbstractAuthorizeGrant
); );
if (!$scope) { if (!$scope) {
// @codeCoverageIgnoreStart
throw OAuthServerException::invalidScope($scopeId); throw OAuthServerException::invalidScope($scopeId);
// @codeCoverageIgnoreEnd
} }
$scopes[] = $scope; $scopes[] = $scope;

View File

@ -89,14 +89,14 @@ interface GrantTypeInterface extends EmitterAwareInterface
/** /**
* Set the path to the private key. * Set the path to the private key.
* *
* @param string $pathToPrivateKey * @param string $privateKeyPath
*/ */
public function setPrivateKeyPath($pathToPrivateKey); public function setPrivateKeyPath($privateKeyPath);
/** /**
* Set the path to the public key. * Set the path to the public key.
* *
* @param string $pathToPublicKey * @param string $publicKeyPath
*/ */
public function setPublicKeyPath($pathToPublicKey); public function setPublicKeyPath($publicKeyPath);
} }

View File

@ -10,16 +10,16 @@ use League\OAuth2\Server\Repositories\UserRepositoryInterface;
use League\OAuth2\Server\ResponseTypes\HtmlResponse; use League\OAuth2\Server\ResponseTypes\HtmlResponse;
use League\OAuth2\Server\ResponseTypes\RedirectResponse; use League\OAuth2\Server\ResponseTypes\RedirectResponse;
use League\OAuth2\Server\ResponseTypes\ResponseTypeInterface; use League\OAuth2\Server\ResponseTypes\ResponseTypeInterface;
use League\OAuth2\Server\TemplateRenderer\AbstractRenderer; use League\OAuth2\Server\TemplateRenderer\RendererInterface;
use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Message\ServerRequestInterface;
class ImplicitGrant extends AbstractAuthorizeGrant class ImplicitGrant extends AbstractAuthorizeGrant
{ {
/** /**
* @param \League\OAuth2\Server\Repositories\UserRepositoryInterface $userRepository * @param \League\OAuth2\Server\Repositories\UserRepositoryInterface $userRepository
* @param \League\OAuth2\Server\TemplateRenderer\AbstractRenderer|null $templateRenderer * @param \League\OAuth2\Server\TemplateRenderer\RendererInterface|null $templateRenderer
*/ */
public function __construct(UserRepositoryInterface $userRepository, AbstractRenderer $templateRenderer = null) public function __construct(UserRepositoryInterface $userRepository, RendererInterface $templateRenderer = null)
{ {
$this->setUserRepository($userRepository); $this->setUserRepository($userRepository);
$this->refreshTokenTTL = new \DateInterval('P1M'); $this->refreshTokenTTL = new \DateInterval('P1M');
@ -176,7 +176,7 @@ class ImplicitGrant extends AbstractAuthorizeGrant
} }
// The user has either approved or denied the client, so redirect them back // The user has either approved or denied the client, so redirect them back
$redirectUri = new Uri($client->getRedirectUri()); $redirectUri = $client->getRedirectUri();
$redirectPayload = []; $redirectPayload = [];
$stateParameter = $this->getQueryStringParameter('state', $request); $stateParameter = $this->getQueryStringParameter('state', $request);
@ -208,8 +208,6 @@ class ImplicitGrant extends AbstractAuthorizeGrant
} }
// The user denied the client, redirect them back with an error // The user denied the client, redirect them back with an error
$exception = OAuthServerException::accessDenied('The user denied the request', (string) $redirectUri); throw OAuthServerException::accessDenied('The user denied the request', (string) $redirectUri);
return $exception->generateHttpResponse(null, true);
} }
} }

View File

@ -54,7 +54,9 @@ class RefreshTokenGrant extends AbstractGrant
); );
if (!$scope) { if (!$scope) {
// @codeCoverageIgnoreStart
throw OAuthServerException::invalidScope($scopeId); throw OAuthServerException::invalidScope($scopeId);
// @codeCoverageIgnoreEnd
} }
return $scope; return $scope;

View File

@ -127,27 +127,23 @@ class Server implements EmitterAwareInterface
*/ */
public function respondToRequest(ServerRequestInterface $request, ResponseInterface $response) public function respondToRequest(ServerRequestInterface $request, ResponseInterface $response)
{ {
try { $tokenResponse = null;
$tokenResponse = null; while ($tokenResponse === null && $grantType = array_shift($this->enabledGrantTypes)) {
while ($tokenResponse === null && $grantType = array_shift($this->enabledGrantTypes)) { /** @var \League\OAuth2\Server\Grant\GrantTypeInterface $grantType */
/** @var \League\OAuth2\Server\Grant\GrantTypeInterface $grantType */ if ($grantType->canRespondToRequest($request)) {
if ($grantType->canRespondToRequest($request)) { $tokenResponse = $grantType->respondToRequest(
$tokenResponse = $grantType->respondToRequest( $request,
$request, $this->getResponseType(),
$this->getResponseType(), $this->grantTypeAccessTokenTTL[$grantType->getIdentifier()]
$this->grantTypeAccessTokenTTL[$grantType->getIdentifier()] );
);
}
} }
if ($tokenResponse instanceof ResponseTypeInterface) {
return $tokenResponse->generateHttpResponse($response);
}
throw OAuthServerException::unsupportedGrantType();
} catch (OAuthServerException $e) {
return $e->generateHttpResponse($response);
} }
if ($tokenResponse instanceof ResponseTypeInterface) {
return $tokenResponse->generateHttpResponse($response);
}
throw OAuthServerException::unsupportedGrantType();
} }
/** /**

46
tests/CryptTraitTest.php Normal file
View File

@ -0,0 +1,46 @@
<?php
namespace LeagueTests\Utils;
use LeagueTests\Stubs\CryptTraitStub;
class CryptTraitTest extends \PHPUnit_Framework_TestCase
{
/**
* CryptTrait stub
*/
protected $cryptStub;
public function setUp()
{
$this->cryptStub = new CryptTraitStub;
}
public function testEncryptDecrypt()
{
$payload = 'alex loves whisky';
$encrypted = $this->cryptStub->doEncrypt($payload);
$plainText = $this->cryptStub->doDecrypt($encrypted);
$this->assertNotEquals($payload, $encrypted);
$this->assertEquals($payload, $plainText);
}
/**
* @expectedException \LogicException
*/
public function testBadPrivateKey()
{
$this->cryptStub->setPrivateKeyPath(__DIR__ . '/Stubs/public.key');
$this->cryptStub->doEncrypt('');
}
/**
* @expectedException \LogicException
*/
public function testBadPublicKey()
{
$this->cryptStub->setPublicKeyPath(__DIR__ . '/Stubs/private.key');
$this->cryptStub->doDecrypt('');
}
}

View File

@ -23,8 +23,8 @@ class AbstractGrantTest extends \PHPUnit_Framework_TestCase
{ {
/** @var AbstractGrant $grantMock */ /** @var AbstractGrant $grantMock */
$grantMock = $this->getMockForAbstractClass(AbstractGrant::class); $grantMock = $this->getMockForAbstractClass(AbstractGrant::class);
$grantMock->setPathToPrivateKey('./private.key'); $grantMock->setPrivateKeyPath('./private.key');
$grantMock->setPathToPublicKey('./public.key'); $grantMock->setPublicKeyPath('./public.key');
$grantMock->setEmitter(new Emitter()); $grantMock->setEmitter(new Emitter());
} }

View File

@ -12,16 +12,29 @@ use League\OAuth2\Server\Repositories\ClientRepositoryInterface;
use League\OAuth2\Server\Repositories\RefreshTokenRepositoryInterface; use League\OAuth2\Server\Repositories\RefreshTokenRepositoryInterface;
use League\OAuth2\Server\Repositories\ScopeRepositoryInterface; use League\OAuth2\Server\Repositories\ScopeRepositoryInterface;
use League\OAuth2\Server\Repositories\UserRepositoryInterface; use League\OAuth2\Server\Repositories\UserRepositoryInterface;
use League\OAuth2\Server\Utils\KeyCrypt; use League\OAuth2\Server\ResponseTypes\HtmlResponse;
use League\OAuth2\Server\ResponseTypes\RedirectResponse;
use LeagueTests\Stubs\ClientEntity; use LeagueTests\Stubs\ClientEntity;
use LeagueTests\Stubs\CryptTraitStub;
use LeagueTests\Stubs\ScopeEntity; use LeagueTests\Stubs\ScopeEntity;
use LeagueTests\Stubs\StubResponseType; use LeagueTests\Stubs\StubResponseType;
use LeagueTests\Stubs\UserEntity; use LeagueTests\Stubs\UserEntity;
use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ResponseInterface;
use Zend\Diactoros\Response;
use Zend\Diactoros\ServerRequest; use Zend\Diactoros\ServerRequest;
class AuthCodeGrantTest extends \PHPUnit_Framework_TestCase class AuthCodeGrantTest extends \PHPUnit_Framework_TestCase
{ {
/**
* CryptTrait stub
*/
protected $cryptStub;
public function setUp()
{
$this->cryptStub = new CryptTraitStub;
}
public function testGetIdentifier() public function testGetIdentifier()
{ {
$grant = new AuthCodeGrant( $grant = new AuthCodeGrant(
@ -71,6 +84,9 @@ class AuthCodeGrantTest extends \PHPUnit_Framework_TestCase
$userEntity = new UserEntity(); $userEntity = new UserEntity();
$userRepositoryMock->method('getUserEntityByUserCredentials')->willReturn($userEntity); $userRepositoryMock->method('getUserEntityByUserCredentials')->willReturn($userEntity);
$accessTokenRepositoryMock = $this->getMockBuilder(AccessTokenRepositoryInterface::class)->getMock();
$accessTokenRepositoryMock->method('persistNewAccessToken')->willReturnSelf();
$grant = new AuthCodeGrant( $grant = new AuthCodeGrant(
$this->getMock(AuthCodeRepositoryInterface::class), $this->getMock(AuthCodeRepositoryInterface::class),
$this->getMock(RefreshTokenRepositoryInterface::class), $this->getMock(RefreshTokenRepositoryInterface::class),
@ -78,8 +94,9 @@ class AuthCodeGrantTest extends \PHPUnit_Framework_TestCase
new \DateInterval('PT10M') new \DateInterval('PT10M')
); );
$grant->setClientRepository($clientRepositoryMock); $grant->setClientRepository($clientRepositoryMock);
$grant->setPathToPublicKey('file://' . __DIR__ . '/../Utils/public.key'); $grant->setAccessTokenRepository($accessTokenRepositoryMock);
$grant->setPathToPrivateKey('file://' . __DIR__ . '/../Utils/private.key'); $grant->setPublicKeyPath('file://' . __DIR__ . '/../Stubs/public.key');
$grant->setPrivateKeyPath('file://' . __DIR__ . '/../Stubs/private.key');
$request = new ServerRequest( $request = new ServerRequest(
[ [
@ -92,10 +109,7 @@ class AuthCodeGrantTest extends \PHPUnit_Framework_TestCase
'php://input', 'php://input',
[], [],
[ [
'oauth_authorize_request' => KeyCrypt::encrypt( 'oauth_authorize_request' => $this->cryptStub->doEncrypt(json_encode(['user_id' => 123])),
json_encode(['user_id' => 123]),
'file://' . __DIR__ . '/../Utils/private.key'
),
], ],
[ [
'response_type' => 'code', 'response_type' => 'code',
@ -111,10 +125,16 @@ class AuthCodeGrantTest extends \PHPUnit_Framework_TestCase
$response = $grant->respondToRequest($request, new StubResponseType(), new \DateInterval('PT10M')); $response = $grant->respondToRequest($request, new StubResponseType(), new \DateInterval('PT10M'));
$this->assertTrue($response instanceof ResponseInterface); $this->assertTrue($response instanceof RedirectResponse);
$response = $response->generateHttpResponse(new Response);
$this->assertTrue(strstr($response->getHeader('location')[0], 'http://foo/bar') !== false); $this->assertTrue(strstr($response->getHeader('location')[0], 'http://foo/bar') !== false);
} }
/**
* @expectedException \League\OAuth2\Server\Exception\OAuthServerException
* @expectedExceptionCode 9
*/
public function testRespondToAuthorizationRequestUserDenied() public function testRespondToAuthorizationRequestUserDenied()
{ {
$client = new ClientEntity(); $client = new ClientEntity();
@ -126,6 +146,9 @@ class AuthCodeGrantTest extends \PHPUnit_Framework_TestCase
$userEntity = new UserEntity(); $userEntity = new UserEntity();
$userRepositoryMock->method('getUserEntityByUserCredentials')->willReturn($userEntity); $userRepositoryMock->method('getUserEntityByUserCredentials')->willReturn($userEntity);
$accessTokenRepositoryMock = $this->getMockBuilder(AccessTokenRepositoryInterface::class)->getMock();
$accessTokenRepositoryMock->method('persistNewAccessToken')->willReturnSelf();
$grant = new AuthCodeGrant( $grant = new AuthCodeGrant(
$this->getMock(AuthCodeRepositoryInterface::class), $this->getMock(AuthCodeRepositoryInterface::class),
$this->getMock(RefreshTokenRepositoryInterface::class), $this->getMock(RefreshTokenRepositoryInterface::class),
@ -133,8 +156,9 @@ class AuthCodeGrantTest extends \PHPUnit_Framework_TestCase
new \DateInterval('PT10M') new \DateInterval('PT10M')
); );
$grant->setClientRepository($clientRepositoryMock); $grant->setClientRepository($clientRepositoryMock);
$grant->setPathToPublicKey('file://' . __DIR__ . '/../Utils/public.key'); $grant->setAccessTokenRepository($accessTokenRepositoryMock);
$grant->setPathToPrivateKey('file://' . __DIR__ . '/../Utils/private.key'); $grant->setPublicKeyPath('file://' . __DIR__ . '/../Stubs/public.key');
$grant->setPrivateKeyPath('file://' . __DIR__ . '/../Stubs/private.key');
$request = new ServerRequest( $request = new ServerRequest(
[ [
@ -147,10 +171,7 @@ class AuthCodeGrantTest extends \PHPUnit_Framework_TestCase
'php://input', 'php://input',
[], [],
[ [
'oauth_authorize_request' => KeyCrypt::encrypt( 'oauth_authorize_request' => $this->cryptStub->doEncrypt(json_encode(['user_id' => 123])),
json_encode(['user_id' => 123]),
'file://' . __DIR__ . '/../Utils/private.key'
),
], ],
[ [
'response_type' => 'code', 'response_type' => 'code',
@ -164,11 +185,7 @@ class AuthCodeGrantTest extends \PHPUnit_Framework_TestCase
] ]
); );
$response = $grant->respondToRequest($request, new StubResponseType(), new \DateInterval('PT10M')); $grant->respondToRequest($request, new StubResponseType(), new \DateInterval('PT10M'));
$this->assertTrue($response instanceof ResponseInterface);
$this->assertTrue(strstr($response->getHeader('location')[0], 'http://foo/bar') !== false);
$this->assertTrue(strstr($response->getHeader('location')[0], 'access_denied') !== false);
} }
/** /**
@ -193,8 +210,8 @@ class AuthCodeGrantTest extends \PHPUnit_Framework_TestCase
new \DateInterval('PT10M') new \DateInterval('PT10M')
); );
$grant->setClientRepository($clientRepositoryMock); $grant->setClientRepository($clientRepositoryMock);
$grant->setPathToPublicKey('file://' . __DIR__ . '/../Utils/public.key'); $grant->setPublicKeyPath('file://' . __DIR__ . '/../Stubs/public.key');
$grant->setPathToPrivateKey('file://' . __DIR__ . '/../Utils/private.key'); $grant->setPrivateKeyPath('file://' . __DIR__ . '/../Stubs/private.key');
$request = new ServerRequest( $request = new ServerRequest(
[ [
@ -207,10 +224,7 @@ class AuthCodeGrantTest extends \PHPUnit_Framework_TestCase
'php://input', 'php://input',
[], [],
[ [
'oauth_authorize_request' => KeyCrypt::encrypt( 'oauth_authorize_request' => $this->cryptStub->doEncrypt(json_encode(['user_id' => 123])),
json_encode(['user_id' => 123]),
'file://' . __DIR__ . '/../Utils/private.key'
),
], ],
[ [
'response_type' => 'code', 'response_type' => 'code',
@ -222,9 +236,7 @@ class AuthCodeGrantTest extends \PHPUnit_Framework_TestCase
] ]
); );
$response = $grant->respondToRequest($request, new StubResponseType(), new \DateInterval('PT10M')); $grant->respondToRequest($request, new StubResponseType(), new \DateInterval('PT10M'));
$this->assertTrue($response instanceof ResponseInterface);
} }
public function testRespondToAuthorizationRequestBadClient() public function testRespondToAuthorizationRequestBadClient()
@ -244,8 +256,8 @@ class AuthCodeGrantTest extends \PHPUnit_Framework_TestCase
new \DateInterval('PT10M') new \DateInterval('PT10M')
); );
$grant->setClientRepository($clientRepositoryMock); $grant->setClientRepository($clientRepositoryMock);
$grant->setPathToPublicKey('file://' . __DIR__ . '/../Utils/public.key'); $grant->setPublicKeyPath('file://' . __DIR__ . '/../Stubs/public.key');
$grant->setPathToPrivateKey('file://' . __DIR__ . '/../Utils/private.key'); $grant->setPrivateKeyPath('file://' . __DIR__ . '/../Stubs/private.key');
$request = new ServerRequest( $request = new ServerRequest(
[ [
@ -258,10 +270,7 @@ class AuthCodeGrantTest extends \PHPUnit_Framework_TestCase
'php://input', 'php://input',
[], [],
[ [
'oauth_authorize_request' => KeyCrypt::encrypt( 'oauth_authorize_request' => $this->cryptStub->doEncrypt(json_encode(['user_id' => 123])),
json_encode(['user_id' => 123]),
'file://' . __DIR__ . '/../Utils/private.key'
),
], ],
[ [
'response_type' => 'code', 'response_type' => 'code',
@ -299,8 +308,8 @@ class AuthCodeGrantTest extends \PHPUnit_Framework_TestCase
new \DateInterval('PT10M') new \DateInterval('PT10M')
); );
$grant->setClientRepository($clientRepositoryMock); $grant->setClientRepository($clientRepositoryMock);
$grant->setPathToPublicKey('file://' . __DIR__ . '/../Utils/public.key'); $grant->setPublicKeyPath('file://' . __DIR__ . '/../Stubs/public.key');
$grant->setPathToPrivateKey('file://' . __DIR__ . '/../Utils/private.key'); $grant->setPrivateKeyPath('file://' . __DIR__ . '/../Stubs/private.key');
$request = new ServerRequest( $request = new ServerRequest(
[ [
@ -313,10 +322,7 @@ class AuthCodeGrantTest extends \PHPUnit_Framework_TestCase
'php://input', 'php://input',
[], [],
[ [
'oauth_authorize_request' => KeyCrypt::encrypt( 'oauth_authorize_request' => $this->cryptStub->doEncrypt(json_encode(['user_id' => 123])),
json_encode(['user_id' => 123]),
'file://' . __DIR__ . '/../Utils/private.key'
),
], ],
[ [
'response_type' => 'code', 'response_type' => 'code',
@ -360,8 +366,8 @@ class AuthCodeGrantTest extends \PHPUnit_Framework_TestCase
new \DateInterval('PT10M') new \DateInterval('PT10M')
); );
$grant->setClientRepository($clientRepositoryMock); $grant->setClientRepository($clientRepositoryMock);
$grant->setPathToPublicKey('file://' . __DIR__ . '/../Utils/public.key'); $grant->setPublicKeyPath('file://' . __DIR__ . '/../Stubs/public.key');
$grant->setPathToPrivateKey('file://' . __DIR__ . '/../Utils/private.key'); $grant->setPrivateKeyPath('file://' . __DIR__ . '/../Stubs/private.key');
$request = new ServerRequest( $request = new ServerRequest(
[ [
@ -387,9 +393,7 @@ class AuthCodeGrantTest extends \PHPUnit_Framework_TestCase
] ]
); );
$response = $grant->respondToRequest($request, new StubResponseType(), new \DateInterval('PT10M')); $grant->respondToRequest($request, new StubResponseType(), new \DateInterval('PT10M'));
$this->assertTrue($response instanceof ResponseInterface);
} }
public function testRespondToAuthorizationRequestTryLogin() public function testRespondToAuthorizationRequestTryLogin()
@ -403,6 +407,9 @@ class AuthCodeGrantTest extends \PHPUnit_Framework_TestCase
$userEntity = new UserEntity(); $userEntity = new UserEntity();
$userRepositoryMock->method('getUserEntityByUserCredentials')->willReturn($userEntity); $userRepositoryMock->method('getUserEntityByUserCredentials')->willReturn($userEntity);
$accessTokenRepositoryMock = $this->getMockBuilder(AccessTokenRepositoryInterface::class)->getMock();
$accessTokenRepositoryMock->method('persistNewAccessToken')->willReturnSelf();
$grant = new AuthCodeGrant( $grant = new AuthCodeGrant(
$this->getMock(AuthCodeRepositoryInterface::class), $this->getMock(AuthCodeRepositoryInterface::class),
$this->getMock(RefreshTokenRepositoryInterface::class), $this->getMock(RefreshTokenRepositoryInterface::class),
@ -410,8 +417,9 @@ class AuthCodeGrantTest extends \PHPUnit_Framework_TestCase
new \DateInterval('PT10M') new \DateInterval('PT10M')
); );
$grant->setClientRepository($clientRepositoryMock); $grant->setClientRepository($clientRepositoryMock);
$grant->setPathToPublicKey('file://' . __DIR__ . '/../Utils/public.key'); $grant->setAccessTokenRepository($accessTokenRepositoryMock);
$grant->setPathToPrivateKey('file://' . __DIR__ . '/../Utils/private.key'); $grant->setPublicKeyPath('file://' . __DIR__ . '/../Stubs/public.key');
$grant->setPrivateKeyPath('file://' . __DIR__ . '/../Stubs/private.key');
$request = new ServerRequest( $request = new ServerRequest(
[ [
@ -424,10 +432,7 @@ class AuthCodeGrantTest extends \PHPUnit_Framework_TestCase
'php://input', 'php://input',
[], [],
[ [
'oauth_authorize_request' => KeyCrypt::encrypt( 'oauth_authorize_request' => $this->cryptStub->doEncrypt(json_encode(['user_id' => null])),
json_encode(['user_id' => null]),
'file://' . __DIR__ . '/../Utils/private.key'
),
], ],
[ [
'response_type' => 'code', 'response_type' => 'code',
@ -442,7 +447,9 @@ class AuthCodeGrantTest extends \PHPUnit_Framework_TestCase
$response = $grant->respondToRequest($request, new StubResponseType(), new \DateInterval('PT10M')); $response = $grant->respondToRequest($request, new StubResponseType(), new \DateInterval('PT10M'));
$this->assertTrue($response instanceof ResponseInterface); $this->assertTrue($response instanceof RedirectResponse);
$response = $response->generateHttpResponse(new Response);
$this->assertTrue(strstr($response->getHeader('location')[0], 'http://foo/bar') !== false); $this->assertTrue(strstr($response->getHeader('location')[0], 'http://foo/bar') !== false);
} }
@ -457,6 +464,9 @@ class AuthCodeGrantTest extends \PHPUnit_Framework_TestCase
$userEntity = null; $userEntity = null;
$userRepositoryMock->method('getUserEntityByUserCredentials')->willReturn($userEntity); $userRepositoryMock->method('getUserEntityByUserCredentials')->willReturn($userEntity);
$accessTokenRepositoryMock = $this->getMockBuilder(AccessTokenRepositoryInterface::class)->getMock();
$accessTokenRepositoryMock->method('persistNewAccessToken')->willReturnSelf();
$grant = new AuthCodeGrant( $grant = new AuthCodeGrant(
$this->getMock(AuthCodeRepositoryInterface::class), $this->getMock(AuthCodeRepositoryInterface::class),
$this->getMock(RefreshTokenRepositoryInterface::class), $this->getMock(RefreshTokenRepositoryInterface::class),
@ -464,8 +474,9 @@ class AuthCodeGrantTest extends \PHPUnit_Framework_TestCase
new \DateInterval('PT10M') new \DateInterval('PT10M')
); );
$grant->setClientRepository($clientRepositoryMock); $grant->setClientRepository($clientRepositoryMock);
$grant->setPathToPublicKey('file://' . __DIR__ . '/../Utils/public.key'); $grant->setAccessTokenRepository($accessTokenRepositoryMock);
$grant->setPathToPrivateKey('file://' . __DIR__ . '/../Utils/private.key'); $grant->setPublicKeyPath('file://' . __DIR__ . '/../Stubs/public.key');
$grant->setPrivateKeyPath('file://' . __DIR__ . '/../Stubs/private.key');
$request = new ServerRequest( $request = new ServerRequest(
[ [
@ -478,10 +489,7 @@ class AuthCodeGrantTest extends \PHPUnit_Framework_TestCase
'php://input', 'php://input',
[], [],
[ [
'oauth_authorize_request' => KeyCrypt::encrypt( 'oauth_authorize_request' => $this->cryptStub->doEncrypt(json_encode(['user_id' => null])),
json_encode(['user_id' => null]),
'file://' . __DIR__ . '/../Utils/private.key'
),
], ],
[ [
'response_type' => 'code', 'response_type' => 'code',
@ -496,9 +504,11 @@ class AuthCodeGrantTest extends \PHPUnit_Framework_TestCase
$response = $grant->respondToRequest($request, new StubResponseType(), new \DateInterval('PT10M')); $response = $grant->respondToRequest($request, new StubResponseType(), new \DateInterval('PT10M'));
$this->assertTrue($response instanceof ResponseInterface); $this->assertTrue($response instanceof HtmlResponse);
$response = $response->generateHttpResponse(new Response);
$this->assertTrue(strstr($response->getHeader('content-type')[0], 'text/html') !== false); $this->assertTrue(strstr($response->getHeader('content-type')[0], 'text/html') !== false);
$this->assertTrue(strstr($response->getBody()->getContents(), 'Incorrect username or password') !== false); $this->assertTrue(strstr((string) $response->getBody(), 'Incorrect username or password') !== false);
} }
public function testRespondToAuthorizationRequestShowAuthorizeForm() public function testRespondToAuthorizationRequestShowAuthorizeForm()
@ -513,6 +523,9 @@ class AuthCodeGrantTest extends \PHPUnit_Framework_TestCase
$userEntity = new UserEntity(); $userEntity = new UserEntity();
$userRepositoryMock->method('getUserEntityByUserCredentials')->willReturn($userEntity); $userRepositoryMock->method('getUserEntityByUserCredentials')->willReturn($userEntity);
$accessTokenRepositoryMock = $this->getMockBuilder(AccessTokenRepositoryInterface::class)->getMock();
$accessTokenRepositoryMock->method('persistNewAccessToken')->willReturnSelf();
$grant = new AuthCodeGrant( $grant = new AuthCodeGrant(
$this->getMock(AuthCodeRepositoryInterface::class), $this->getMock(AuthCodeRepositoryInterface::class),
$this->getMock(RefreshTokenRepositoryInterface::class), $this->getMock(RefreshTokenRepositoryInterface::class),
@ -520,8 +533,9 @@ class AuthCodeGrantTest extends \PHPUnit_Framework_TestCase
new \DateInterval('PT10M') new \DateInterval('PT10M')
); );
$grant->setClientRepository($clientRepositoryMock); $grant->setClientRepository($clientRepositoryMock);
$grant->setPathToPublicKey('file://' . __DIR__ . '/../Utils/public.key'); $grant->setAccessTokenRepository($accessTokenRepositoryMock);
$grant->setPathToPrivateKey('file://' . __DIR__ . '/../Utils/private.key'); $grant->setPublicKeyPath('file://' . __DIR__ . '/../Stubs/public.key');
$grant->setPrivateKeyPath('file://' . __DIR__ . '/../Stubs/private.key');
$request = new ServerRequest( $request = new ServerRequest(
[ [
@ -534,10 +548,7 @@ class AuthCodeGrantTest extends \PHPUnit_Framework_TestCase
'php://input', 'php://input',
[], [],
[ [
'oauth_authorize_request' => KeyCrypt::encrypt( 'oauth_authorize_request' => $this->cryptStub->doEncrypt(json_encode(['user_id' => 123])),
json_encode(['user_id' => 123]),
'file://' . __DIR__ . '/../Utils/private.key'
),
], ],
[ [
'response_type' => 'code', 'response_type' => 'code',
@ -551,6 +562,7 @@ class AuthCodeGrantTest extends \PHPUnit_Framework_TestCase
$response = $grant->respondToRequest($request, new StubResponseType(), new \DateInterval('PT10M')); $response = $grant->respondToRequest($request, new StubResponseType(), new \DateInterval('PT10M'));
$response = $response->generateHttpResponse(new Response);
$this->assertTrue($response instanceof ResponseInterface); $this->assertTrue($response instanceof ResponseInterface);
$this->assertTrue(strstr($response->getHeader('set-cookie')[0], 'oauth_authorize_request') !== false); $this->assertTrue(strstr($response->getHeader('set-cookie')[0], 'oauth_authorize_request') !== false);
} }
@ -587,8 +599,8 @@ class AuthCodeGrantTest extends \PHPUnit_Framework_TestCase
$grant->setScopeRepository($scopeRepositoryMock); $grant->setScopeRepository($scopeRepositoryMock);
$grant->setAccessTokenRepository($accessTokenRepositoryMock); $grant->setAccessTokenRepository($accessTokenRepositoryMock);
$grant->setRefreshTokenRepository($refreshTokenRepositoryMock); $grant->setRefreshTokenRepository($refreshTokenRepositoryMock);
$grant->setPathToPublicKey('file://' . __DIR__ . '/../Utils/public.key'); $grant->setPublicKeyPath('file://' . __DIR__ . '/../Stubs/public.key');
$grant->setPathToPrivateKey('file://' . __DIR__ . '/../Utils/private.key'); $grant->setPrivateKeyPath('file://' . __DIR__ . '/../Stubs/private.key');
$request = new ServerRequest( $request = new ServerRequest(
[], [],
@ -603,7 +615,7 @@ class AuthCodeGrantTest extends \PHPUnit_Framework_TestCase
'grant_type' => 'authorization_code', 'grant_type' => 'authorization_code',
'client_id' => 'foo', 'client_id' => 'foo',
'redirect_uri' => 'http://foo/bar', 'redirect_uri' => 'http://foo/bar',
'code' => KeyCrypt::encrypt( 'code' => $this->cryptStub->doEncrypt(
json_encode( json_encode(
[ [
'auth_code_id' => uniqid(), 'auth_code_id' => uniqid(),
@ -613,8 +625,7 @@ class AuthCodeGrantTest extends \PHPUnit_Framework_TestCase
'scopes' => ['foo'], 'scopes' => ['foo'],
'redirect_uri' => 'http://foo/bar', 'redirect_uri' => 'http://foo/bar',
] ]
), )
'file://' . __DIR__ . '/../Utils/private.key'
), ),
] ]
); );
@ -646,8 +657,8 @@ class AuthCodeGrantTest extends \PHPUnit_Framework_TestCase
$grant->setClientRepository($clientRepositoryMock); $grant->setClientRepository($clientRepositoryMock);
$grant->setAccessTokenRepository($accessTokenRepositoryMock); $grant->setAccessTokenRepository($accessTokenRepositoryMock);
$grant->setRefreshTokenRepository($refreshTokenRepositoryMock); $grant->setRefreshTokenRepository($refreshTokenRepositoryMock);
$grant->setPathToPublicKey('file://' . __DIR__ . '/../Utils/public.key'); $grant->setPublicKeyPath('file://' . __DIR__ . '/../Stubs/public.key');
$grant->setPathToPrivateKey('file://' . __DIR__ . '/../Utils/private.key'); $grant->setPrivateKeyPath('file://' . __DIR__ . '/../Stubs/private.key');
$request = new ServerRequest( $request = new ServerRequest(
[], [],
@ -692,8 +703,8 @@ class AuthCodeGrantTest extends \PHPUnit_Framework_TestCase
$grant->setClientRepository($clientRepositoryMock); $grant->setClientRepository($clientRepositoryMock);
$grant->setAccessTokenRepository($accessTokenRepositoryMock); $grant->setAccessTokenRepository($accessTokenRepositoryMock);
$grant->setRefreshTokenRepository($refreshTokenRepositoryMock); $grant->setRefreshTokenRepository($refreshTokenRepositoryMock);
$grant->setPathToPublicKey('file://' . __DIR__ . '/../Utils/public.key'); $grant->setPublicKeyPath('file://' . __DIR__ . '/../Stubs/public.key');
$grant->setPathToPrivateKey('file://' . __DIR__ . '/../Utils/private.key'); $grant->setPrivateKeyPath('file://' . __DIR__ . '/../Stubs/private.key');
$request = new ServerRequest( $request = new ServerRequest(
[], [],
@ -743,8 +754,8 @@ class AuthCodeGrantTest extends \PHPUnit_Framework_TestCase
$grant->setClientRepository($clientRepositoryMock); $grant->setClientRepository($clientRepositoryMock);
$grant->setAccessTokenRepository($accessTokenRepositoryMock); $grant->setAccessTokenRepository($accessTokenRepositoryMock);
$grant->setRefreshTokenRepository($refreshTokenRepositoryMock); $grant->setRefreshTokenRepository($refreshTokenRepositoryMock);
$grant->setPathToPublicKey('file://' . __DIR__ . '/../Utils/public.key'); $grant->setPublicKeyPath('file://' . __DIR__ . '/../Stubs/public.key');
$grant->setPathToPrivateKey('file://' . __DIR__ . '/../Utils/private.key'); $grant->setPrivateKeyPath('file://' . __DIR__ . '/../Stubs/private.key');
$request = new ServerRequest( $request = new ServerRequest(
[], [],
@ -759,7 +770,7 @@ class AuthCodeGrantTest extends \PHPUnit_Framework_TestCase
'grant_type' => 'authorization_code', 'grant_type' => 'authorization_code',
'client_id' => 'foo', 'client_id' => 'foo',
'redirect_uri' => 'http://foo/bar', 'redirect_uri' => 'http://foo/bar',
'code' => KeyCrypt::encrypt( 'code' => $this->cryptStub->doEncrypt(
json_encode( json_encode(
[ [
'auth_code_id' => uniqid(), 'auth_code_id' => uniqid(),
@ -769,8 +780,7 @@ class AuthCodeGrantTest extends \PHPUnit_Framework_TestCase
'scopes' => ['foo'], 'scopes' => ['foo'],
'redirect_uri' => 'http://foo/bar', 'redirect_uri' => 'http://foo/bar',
] ]
), )
'file://' . __DIR__ . '/../Utils/private.key'
), ),
] ]
); );
@ -813,8 +823,8 @@ class AuthCodeGrantTest extends \PHPUnit_Framework_TestCase
$grant->setClientRepository($clientRepositoryMock); $grant->setClientRepository($clientRepositoryMock);
$grant->setAccessTokenRepository($accessTokenRepositoryMock); $grant->setAccessTokenRepository($accessTokenRepositoryMock);
$grant->setRefreshTokenRepository($refreshTokenRepositoryMock); $grant->setRefreshTokenRepository($refreshTokenRepositoryMock);
$grant->setPathToPublicKey('file://' . __DIR__ . '/../Utils/public.key'); $grant->setPublicKeyPath('file://' . __DIR__ . '/../Stubs/public.key');
$grant->setPathToPrivateKey('file://' . __DIR__ . '/../Utils/private.key'); $grant->setPrivateKeyPath('file://' . __DIR__ . '/../Stubs/private.key');
$request = new ServerRequest( $request = new ServerRequest(
[], [],
@ -829,7 +839,7 @@ class AuthCodeGrantTest extends \PHPUnit_Framework_TestCase
'grant_type' => 'authorization_code', 'grant_type' => 'authorization_code',
'client_id' => 'foo', 'client_id' => 'foo',
'redirect_uri' => 'http://foo/bar', 'redirect_uri' => 'http://foo/bar',
'code' => KeyCrypt::encrypt( 'code' => $this->cryptStub->doEncrypt(
json_encode( json_encode(
[ [
'auth_code_id' => uniqid(), 'auth_code_id' => uniqid(),
@ -839,8 +849,7 @@ class AuthCodeGrantTest extends \PHPUnit_Framework_TestCase
'scopes' => ['foo'], 'scopes' => ['foo'],
'redirect_uri' => 'http://foo/bar', 'redirect_uri' => 'http://foo/bar',
] ]
), )
'file://' . __DIR__ . '/../Utils/private.key'
), ),
] ]
); );
@ -880,8 +889,8 @@ class AuthCodeGrantTest extends \PHPUnit_Framework_TestCase
$grant->setClientRepository($clientRepositoryMock); $grant->setClientRepository($clientRepositoryMock);
$grant->setAccessTokenRepository($accessTokenRepositoryMock); $grant->setAccessTokenRepository($accessTokenRepositoryMock);
$grant->setRefreshTokenRepository($refreshTokenRepositoryMock); $grant->setRefreshTokenRepository($refreshTokenRepositoryMock);
$grant->setPathToPublicKey('file://' . __DIR__ . '/../Utils/public.key'); $grant->setPublicKeyPath('file://' . __DIR__ . '/../Stubs/public.key');
$grant->setPathToPrivateKey('file://' . __DIR__ . '/../Utils/private.key'); $grant->setPrivateKeyPath('file://' . __DIR__ . '/../Stubs/private.key');
$request = new ServerRequest( $request = new ServerRequest(
[], [],
@ -896,7 +905,7 @@ class AuthCodeGrantTest extends \PHPUnit_Framework_TestCase
'grant_type' => 'authorization_code', 'grant_type' => 'authorization_code',
'client_id' => 'foo', 'client_id' => 'foo',
'redirect_uri' => 'http://foo/bar', 'redirect_uri' => 'http://foo/bar',
'code' => KeyCrypt::encrypt( 'code' => $this->cryptStub->doEncrypt(
json_encode( json_encode(
[ [
'auth_code_id' => uniqid(), 'auth_code_id' => uniqid(),
@ -906,8 +915,7 @@ class AuthCodeGrantTest extends \PHPUnit_Framework_TestCase
'scopes' => ['foo'], 'scopes' => ['foo'],
'redirect_uri' => 'http://foo/bar', 'redirect_uri' => 'http://foo/bar',
] ]
), )
'file://' . __DIR__ . '/../Utils/private.key'
), ),
] ]
); );
@ -947,8 +955,8 @@ class AuthCodeGrantTest extends \PHPUnit_Framework_TestCase
$grant->setClientRepository($clientRepositoryMock); $grant->setClientRepository($clientRepositoryMock);
$grant->setAccessTokenRepository($accessTokenRepositoryMock); $grant->setAccessTokenRepository($accessTokenRepositoryMock);
$grant->setRefreshTokenRepository($refreshTokenRepositoryMock); $grant->setRefreshTokenRepository($refreshTokenRepositoryMock);
$grant->setPathToPublicKey('file://' . __DIR__ . '/../Utils/public.key'); $grant->setPublicKeyPath('file://' . __DIR__ . '/../Stubs/public.key');
$grant->setPathToPrivateKey('file://' . __DIR__ . '/../Utils/private.key'); $grant->setPrivateKeyPath('file://' . __DIR__ . '/../Stubs/private.key');
$request = new ServerRequest( $request = new ServerRequest(
[], [],

View File

@ -7,15 +7,26 @@ use League\OAuth2\Server\Grant\ImplicitGrant;
use League\OAuth2\Server\Repositories\AccessTokenRepositoryInterface; use League\OAuth2\Server\Repositories\AccessTokenRepositoryInterface;
use League\OAuth2\Server\Repositories\ClientRepositoryInterface; use League\OAuth2\Server\Repositories\ClientRepositoryInterface;
use League\OAuth2\Server\Repositories\UserRepositoryInterface; use League\OAuth2\Server\Repositories\UserRepositoryInterface;
use League\OAuth2\Server\Utils\KeyCrypt; use League\OAuth2\Server\ResponseTypes\HtmlResponse;
use LeagueTests\Stubs\ClientEntity; use LeagueTests\Stubs\ClientEntity;
use LeagueTests\Stubs\CryptTraitStub;
use LeagueTests\Stubs\StubResponseType; use LeagueTests\Stubs\StubResponseType;
use LeagueTests\Stubs\UserEntity; use LeagueTests\Stubs\UserEntity;
use Psr\Http\Message\ResponseInterface; use Zend\Diactoros\Response;
use Zend\Diactoros\ServerRequest; use Zend\Diactoros\ServerRequest;
class ImplicitGrantTest extends \PHPUnit_Framework_TestCase class ImplicitGrantTest extends \PHPUnit_Framework_TestCase
{ {
/**
* CryptTrait stub
*/
protected $cryptStub;
public function setUp()
{
$this->cryptStub = new CryptTraitStub();
}
public function testGetIdentifier() public function testGetIdentifier()
{ {
$grant = new ImplicitGrant($this->getMock(UserRepositoryInterface::class)); $grant = new ImplicitGrant($this->getMock(UserRepositoryInterface::class));
@ -43,6 +54,10 @@ class ImplicitGrantTest extends \PHPUnit_Framework_TestCase
$this->assertTrue($grant->canRespondToRequest($request)); $this->assertTrue($grant->canRespondToRequest($request));
} }
/**
* @expectedException \League\OAuth2\Server\Exception\OAuthServerException
* @expectedExceptionCode 9
*/
public function testRespondToAuthorizationRequest() public function testRespondToAuthorizationRequest()
{ {
$client = new ClientEntity(); $client = new ClientEntity();
@ -60,8 +75,8 @@ class ImplicitGrantTest extends \PHPUnit_Framework_TestCase
$grant = new ImplicitGrant($userRepositoryMock); $grant = new ImplicitGrant($userRepositoryMock);
$grant->setClientRepository($clientRepositoryMock); $grant->setClientRepository($clientRepositoryMock);
$grant->setAccessTokenRepository($accessTokenRepositoryMock); $grant->setAccessTokenRepository($accessTokenRepositoryMock);
$grant->setPathToPublicKey('file://' . __DIR__ . '/../Utils/public.key'); $grant->setPublicKeyPath('file://' . __DIR__ . '/../Stubs/public.key');
$grant->setPathToPrivateKey('file://' . __DIR__ . '/../Utils/private.key'); $grant->setPrivateKeyPath('file://' . __DIR__ . '/../Stubs/private.key');
$request = new ServerRequest( $request = new ServerRequest(
[ [
@ -86,10 +101,7 @@ class ImplicitGrantTest extends \PHPUnit_Framework_TestCase
] ]
); );
$response = $grant->respondToRequest($request, new StubResponseType(), new \DateInterval('PT10M')); $grant->respondToRequest($request, new StubResponseType(), new \DateInterval('PT10M'));
$this->assertTrue($response instanceof ResponseInterface);
$this->assertTrue(strstr($response->getHeader('location')[0], 'http://foo/bar') !== false);
} }
/** /**
@ -99,8 +111,8 @@ class ImplicitGrantTest extends \PHPUnit_Framework_TestCase
public function testRespondToAuthorizationRequestMissingClientId() public function testRespondToAuthorizationRequestMissingClientId()
{ {
$grant = new ImplicitGrant($this->getMock(UserRepositoryInterface::class)); $grant = new ImplicitGrant($this->getMock(UserRepositoryInterface::class));
$grant->setPathToPublicKey('file://' . __DIR__ . '/../Utils/public.key'); $grant->setPublicKeyPath('file://' . __DIR__ . '/../Stubs/public.key');
$grant->setPathToPrivateKey('file://' . __DIR__ . '/../Utils/private.key'); $grant->setPrivateKeyPath('file://' . __DIR__ . '/../Stubs/private.key');
$request = new ServerRequest( $request = new ServerRequest(
[ [
@ -113,10 +125,7 @@ class ImplicitGrantTest extends \PHPUnit_Framework_TestCase
'php://input', 'php://input',
[], [],
[ [
'oauth_authorize_request' => KeyCrypt::encrypt( 'oauth_authorize_request' => $this->cryptStub->doEncrypt(json_encode(['user_id' => 123])),
json_encode(['user_id' => 123]),
'file://' . __DIR__ . '/../Utils/private.key'
),
], ],
[ [
'response_type' => 'token', 'response_type' => 'token',
@ -128,9 +137,7 @@ class ImplicitGrantTest extends \PHPUnit_Framework_TestCase
] ]
); );
$response = $grant->respondToRequest($request, new StubResponseType(), new \DateInterval('PT10M')); $grant->respondToRequest($request, new StubResponseType(), new \DateInterval('PT10M'));
$this->assertTrue($response instanceof ResponseInterface);
} }
public function testRespondToAuthorizationRequestBadClient() public function testRespondToAuthorizationRequestBadClient()
@ -141,8 +148,8 @@ class ImplicitGrantTest extends \PHPUnit_Framework_TestCase
$grant = new ImplicitGrant($this->getMock(UserRepositoryInterface::class)); $grant = new ImplicitGrant($this->getMock(UserRepositoryInterface::class));
$grant->setClientRepository($clientRepositoryMock); $grant->setClientRepository($clientRepositoryMock);
$grant->setPathToPublicKey('file://' . __DIR__ . '/../Utils/public.key'); $grant->setPublicKeyPath('file://' . __DIR__ . '/../Stubs/public.key');
$grant->setPathToPrivateKey('file://' . __DIR__ . '/../Utils/private.key'); $grant->setPrivateKeyPath('file://' . __DIR__ . '/../Stubs/private.key');
$request = new ServerRequest( $request = new ServerRequest(
[ [
@ -155,10 +162,7 @@ class ImplicitGrantTest extends \PHPUnit_Framework_TestCase
'php://input', 'php://input',
[], [],
[ [
'oauth_authorize_request' => KeyCrypt::encrypt( 'oauth_authorize_request' => $this->cryptStub->doEncrypt(json_encode(['user_id' => 123])),
json_encode(['user_id' => 123]),
'file://' . __DIR__ . '/../Utils/private.key'
),
], ],
[ [
'response_type' => 'token', 'response_type' => 'token',
@ -191,8 +195,8 @@ class ImplicitGrantTest extends \PHPUnit_Framework_TestCase
$grant = new ImplicitGrant($this->getMock(UserRepositoryInterface::class)); $grant = new ImplicitGrant($this->getMock(UserRepositoryInterface::class));
$grant->setClientRepository($clientRepositoryMock); $grant->setClientRepository($clientRepositoryMock);
$grant->setPathToPublicKey('file://' . __DIR__ . '/../Utils/public.key'); $grant->setPublicKeyPath('file://' . __DIR__ . '/../Stubs/public.key');
$grant->setPathToPrivateKey('file://' . __DIR__ . '/../Utils/private.key'); $grant->setPrivateKeyPath('file://' . __DIR__ . '/../Stubs/private.key');
$request = new ServerRequest( $request = new ServerRequest(
[ [
@ -205,10 +209,7 @@ class ImplicitGrantTest extends \PHPUnit_Framework_TestCase
'php://input', 'php://input',
[], [],
[ [
'oauth_authorize_request' => KeyCrypt::encrypt( 'oauth_authorize_request' => $this->cryptStub->doEncrypt(json_encode(['user_id' => 123])),
json_encode(['user_id' => 123]),
'file://' . __DIR__ . '/../Utils/private.key'
),
], ],
[ [
'response_type' => 'token', 'response_type' => 'token',
@ -247,8 +248,8 @@ class ImplicitGrantTest extends \PHPUnit_Framework_TestCase
$grant = new ImplicitGrant($this->getMock(UserRepositoryInterface::class)); $grant = new ImplicitGrant($this->getMock(UserRepositoryInterface::class));
$grant->setClientRepository($clientRepositoryMock); $grant->setClientRepository($clientRepositoryMock);
$grant->setPathToPublicKey('file://' . __DIR__ . '/../Utils/public.key'); $grant->setPublicKeyPath('file://' . __DIR__ . '/../Stubs/public.key');
$grant->setPathToPrivateKey('file://' . __DIR__ . '/../Utils/private.key'); $grant->setPrivateKeyPath('file://' . __DIR__ . '/../Stubs/private.key');
$request = new ServerRequest( $request = new ServerRequest(
[ [
@ -274,9 +275,7 @@ class ImplicitGrantTest extends \PHPUnit_Framework_TestCase
] ]
); );
$response = $grant->respondToRequest($request, new StubResponseType(), new \DateInterval('PT10M')); $grant->respondToRequest($request, new StubResponseType(), new \DateInterval('PT10M'));
$this->assertTrue($response instanceof ResponseInterface);
} }
public function testRespondToAuthorizationRequestTryLogin() public function testRespondToAuthorizationRequestTryLogin()
@ -290,10 +289,14 @@ class ImplicitGrantTest extends \PHPUnit_Framework_TestCase
$userEntity = new UserEntity(); $userEntity = new UserEntity();
$userRepositoryMock->method('getUserEntityByUserCredentials')->willReturn($userEntity); $userRepositoryMock->method('getUserEntityByUserCredentials')->willReturn($userEntity);
$accessTokenRepositoryMock = $this->getMockBuilder(AccessTokenRepositoryInterface::class)->getMock();
$accessTokenRepositoryMock->method('persistNewAccessToken')->willReturnSelf();
$grant = new ImplicitGrant($this->getMock(UserRepositoryInterface::class)); $grant = new ImplicitGrant($this->getMock(UserRepositoryInterface::class));
$grant->setClientRepository($clientRepositoryMock); $grant->setClientRepository($clientRepositoryMock);
$grant->setPathToPublicKey('file://' . __DIR__ . '/../Utils/public.key'); $grant->setAccessTokenRepository($accessTokenRepositoryMock);
$grant->setPathToPrivateKey('file://' . __DIR__ . '/../Utils/private.key'); $grant->setPublicKeyPath('file://' . __DIR__ . '/../Stubs/public.key');
$grant->setPrivateKeyPath('file://' . __DIR__ . '/../Stubs/private.key');
$request = new ServerRequest( $request = new ServerRequest(
[ [
@ -306,10 +309,7 @@ class ImplicitGrantTest extends \PHPUnit_Framework_TestCase
'php://input', 'php://input',
[], [],
[ [
'oauth_authorize_request' => KeyCrypt::encrypt( 'oauth_authorize_request' => $this->cryptStub->doEncrypt(json_encode(['user_id' => null])),
json_encode(['user_id' => null]),
'file://' . __DIR__ . '/../Utils/private.key'
),
], ],
[ [
'response_type' => 'token', 'response_type' => 'token',
@ -323,9 +323,10 @@ class ImplicitGrantTest extends \PHPUnit_Framework_TestCase
); );
$response = $grant->respondToRequest($request, new StubResponseType(), new \DateInterval('PT10M')); $response = $grant->respondToRequest($request, new StubResponseType(), new \DateInterval('PT10M'));
$this->assertTrue($response instanceof ResponseInterface); $this->assertTrue($response instanceof HtmlResponse);
$this->assertTrue(strstr($response->getHeader('content-type')[0], 'text/html') !== false);
$this->assertTrue(strstr($response->getBody()->getContents(), 'Incorrect username or password') !== false); $response = $response->generateHttpResponse(new Response);
$this->assertTrue(strstr((string) $response->getBody(), 'Incorrect username or password') !== false);
} }
public function testRespondToAuthorizationRequestShowAuthorizeForm() public function testRespondToAuthorizationRequestShowAuthorizeForm()
@ -339,10 +340,14 @@ class ImplicitGrantTest extends \PHPUnit_Framework_TestCase
$userEntity = new UserEntity(); $userEntity = new UserEntity();
$userRepositoryMock->method('getUserEntityByUserCredentials')->willReturn($userEntity); $userRepositoryMock->method('getUserEntityByUserCredentials')->willReturn($userEntity);
$accessTokenRepositoryMock = $this->getMockBuilder(AccessTokenRepositoryInterface::class)->getMock();
$accessTokenRepositoryMock->method('persistNewAccessToken')->willReturnSelf();
$grant = new ImplicitGrant($this->getMock(UserRepositoryInterface::class)); $grant = new ImplicitGrant($this->getMock(UserRepositoryInterface::class));
$grant->setClientRepository($clientRepositoryMock); $grant->setClientRepository($clientRepositoryMock);
$grant->setPathToPublicKey('file://' . __DIR__ . '/../Utils/public.key'); $grant->setAccessTokenRepository($accessTokenRepositoryMock);
$grant->setPathToPrivateKey('file://' . __DIR__ . '/../Utils/private.key'); $grant->setPublicKeyPath('file://' . __DIR__ . '/../Stubs/public.key');
$grant->setPrivateKeyPath('file://' . __DIR__ . '/../Stubs/private.key');
$request = new ServerRequest( $request = new ServerRequest(
[ [
@ -355,10 +360,7 @@ class ImplicitGrantTest extends \PHPUnit_Framework_TestCase
'php://input', 'php://input',
[], [],
[ [
'oauth_authorize_request' => KeyCrypt::encrypt( 'oauth_authorize_request' => $this->cryptStub->doEncrypt(json_encode(['user_id' => 123])),
json_encode(['user_id' => 123]),
'file://' . __DIR__ . '/../Utils/private.key'
),
], ],
[ [
'response_type' => 'code', 'response_type' => 'code',
@ -372,10 +374,16 @@ class ImplicitGrantTest extends \PHPUnit_Framework_TestCase
$response = $grant->respondToRequest($request, new StubResponseType(), new \DateInterval('PT10M')); $response = $grant->respondToRequest($request, new StubResponseType(), new \DateInterval('PT10M'));
$this->assertTrue($response instanceof ResponseInterface); $this->assertTrue($response instanceof HtmlResponse);
$response = $response->generateHttpResponse(new Response);
$this->assertTrue(strstr($response->getHeader('set-cookie')[0], 'oauth_authorize_request') !== false); $this->assertTrue(strstr($response->getHeader('set-cookie')[0], 'oauth_authorize_request') !== false);
} }
/**
* @expectedException \League\OAuth2\Server\Exception\OAuthServerException
* @expectedExceptionCode 9
*/
public function testRespondToAuthorizationRequestUserDenied() public function testRespondToAuthorizationRequestUserDenied()
{ {
$client = new ClientEntity(); $client = new ClientEntity();
@ -389,8 +397,8 @@ class ImplicitGrantTest extends \PHPUnit_Framework_TestCase
$grant = new ImplicitGrant($this->getMock(UserRepositoryInterface::class)); $grant = new ImplicitGrant($this->getMock(UserRepositoryInterface::class));
$grant->setClientRepository($clientRepositoryMock); $grant->setClientRepository($clientRepositoryMock);
$grant->setPathToPublicKey('file://' . __DIR__ . '/../Utils/public.key'); $grant->setPublicKeyPath('file://' . __DIR__ . '/../Stubs/public.key');
$grant->setPathToPrivateKey('file://' . __DIR__ . '/../Utils/private.key'); $grant->setPrivateKeyPath('file://' . __DIR__ . '/../Stubs/private.key');
$request = new ServerRequest( $request = new ServerRequest(
[ [
@ -403,10 +411,7 @@ class ImplicitGrantTest extends \PHPUnit_Framework_TestCase
'php://input', 'php://input',
[], [],
[ [
'oauth_authorize_request' => KeyCrypt::encrypt( 'oauth_authorize_request' => $this->cryptStub->doEncrypt(json_encode(['user_id' => 123])),
json_encode(['user_id' => 123]),
'file://' . __DIR__ . '/../Utils/private.key'
),
], ],
[ [
'response_type' => 'code', 'response_type' => 'code',
@ -420,10 +425,6 @@ class ImplicitGrantTest extends \PHPUnit_Framework_TestCase
] ]
); );
$response = $grant->respondToRequest($request, new StubResponseType(), new \DateInterval('PT10M')); $grant->respondToRequest($request, new StubResponseType(), new \DateInterval('PT10M'));
$this->assertTrue($response instanceof ResponseInterface);
$this->assertTrue(strstr($response->getHeader('location')[0], 'http://foo/bar') !== false);
$this->assertTrue(strstr($response->getHeader('location')[0], 'access_denied') !== false);
} }
} }

View File

@ -9,14 +9,24 @@ use League\OAuth2\Server\Repositories\AccessTokenRepositoryInterface;
use League\OAuth2\Server\Repositories\ClientRepositoryInterface; use League\OAuth2\Server\Repositories\ClientRepositoryInterface;
use League\OAuth2\Server\Repositories\RefreshTokenRepositoryInterface; use League\OAuth2\Server\Repositories\RefreshTokenRepositoryInterface;
use League\OAuth2\Server\Repositories\ScopeRepositoryInterface; use League\OAuth2\Server\Repositories\ScopeRepositoryInterface;
use League\OAuth2\Server\Utils\KeyCrypt;
use LeagueTests\Stubs\ClientEntity; use LeagueTests\Stubs\ClientEntity;
use LeagueTests\Stubs\CryptTraitStub;
use LeagueTests\Stubs\ScopeEntity; use LeagueTests\Stubs\ScopeEntity;
use LeagueTests\Stubs\StubResponseType; use LeagueTests\Stubs\StubResponseType;
use Zend\Diactoros\ServerRequest; use Zend\Diactoros\ServerRequest;
class RefreshTokenGrantTest extends \PHPUnit_Framework_TestCase class RefreshTokenGrantTest extends \PHPUnit_Framework_TestCase
{ {
/**
* CryptTrait stub
*/
protected $cryptStub;
public function setUp()
{
$this->cryptStub = new CryptTraitStub();
}
public function testGetIdentifier() public function testGetIdentifier()
{ {
$refreshTokenRepositoryMock = $this->getMock(RefreshTokenRepositoryInterface::class); $refreshTokenRepositoryMock = $this->getMock(RefreshTokenRepositoryInterface::class);
@ -47,10 +57,10 @@ class RefreshTokenGrantTest extends \PHPUnit_Framework_TestCase
$grant->setClientRepository($clientRepositoryMock); $grant->setClientRepository($clientRepositoryMock);
$grant->setScopeRepository($scopeRepositoryMock); $grant->setScopeRepository($scopeRepositoryMock);
$grant->setAccessTokenRepository($accessTokenRepositoryMock); $grant->setAccessTokenRepository($accessTokenRepositoryMock);
$grant->setPathToPublicKey('file://' . __DIR__ . '/../Utils/public.key'); $grant->setPublicKeyPath('file://' . __DIR__ . '/../Stubs/public.key');
$grant->setPathToPrivateKey('file://' . __DIR__ . '/../Utils/private.key'); $grant->setPrivateKeyPath('file://' . __DIR__ . '/../Stubs/private.key');
$oldRefreshToken = KeyCrypt::encrypt( $oldRefreshToken = $this->cryptStub->doEncrypt(
json_encode( json_encode(
[ [
'client_id' => 'foo', 'client_id' => 'foo',
@ -60,8 +70,7 @@ class RefreshTokenGrantTest extends \PHPUnit_Framework_TestCase
'user_id' => 123, 'user_id' => 123,
'expire_time' => time() + 3600, 'expire_time' => time() + 3600,
] ]
), )
'file://' . __DIR__ . '/../Utils/private.key'
); );
$serverRequest = new ServerRequest(); $serverRequest = new ServerRequest();
@ -103,10 +112,10 @@ class RefreshTokenGrantTest extends \PHPUnit_Framework_TestCase
$grant->setClientRepository($clientRepositoryMock); $grant->setClientRepository($clientRepositoryMock);
$grant->setAccessTokenRepository($accessTokenRepositoryMock); $grant->setAccessTokenRepository($accessTokenRepositoryMock);
$grant->setScopeRepository($scopeRepositoryMock); $grant->setScopeRepository($scopeRepositoryMock);
$grant->setPathToPublicKey('file://' . __DIR__ . '/../Utils/public.key'); $grant->setPublicKeyPath('file://' . __DIR__ . '/../Stubs/public.key');
$grant->setPathToPrivateKey('file://' . __DIR__ . '/../Utils/private.key'); $grant->setPrivateKeyPath('file://' . __DIR__ . '/../Stubs/private.key');
$oldRefreshToken = KeyCrypt::encrypt( $oldRefreshToken = $this->cryptStub->doEncrypt(
json_encode( json_encode(
[ [
'client_id' => 'foo', 'client_id' => 'foo',
@ -116,8 +125,7 @@ class RefreshTokenGrantTest extends \PHPUnit_Framework_TestCase
'user_id' => 123, 'user_id' => 123,
'expire_time' => time() + 3600, 'expire_time' => time() + 3600,
] ]
), )
'file://' . __DIR__ . '/../Utils/private.key'
); );
$serverRequest = new ServerRequest(); $serverRequest = new ServerRequest();
@ -164,10 +172,10 @@ class RefreshTokenGrantTest extends \PHPUnit_Framework_TestCase
$grant->setClientRepository($clientRepositoryMock); $grant->setClientRepository($clientRepositoryMock);
$grant->setAccessTokenRepository($accessTokenRepositoryMock); $grant->setAccessTokenRepository($accessTokenRepositoryMock);
$grant->setScopeRepository($scopeRepositoryMock); $grant->setScopeRepository($scopeRepositoryMock);
$grant->setPathToPublicKey('file://' . __DIR__ . '/../Utils/public.key'); $grant->setPublicKeyPath('file://' . __DIR__ . '/../Stubs/public.key');
$grant->setPathToPrivateKey('file://' . __DIR__ . '/../Utils/private.key'); $grant->setPrivateKeyPath('file://' . __DIR__ . '/../Stubs/private.key');
$oldRefreshToken = KeyCrypt::encrypt( $oldRefreshToken = $this->cryptStub->doEncrypt(
json_encode( json_encode(
[ [
'client_id' => 'foo', 'client_id' => 'foo',
@ -177,8 +185,7 @@ class RefreshTokenGrantTest extends \PHPUnit_Framework_TestCase
'user_id' => 123, 'user_id' => 123,
'expire_time' => time() + 3600, 'expire_time' => time() + 3600,
] ]
), )
'file://' . __DIR__ . '/../Utils/private.key'
); );
$serverRequest = new ServerRequest(); $serverRequest = new ServerRequest();
@ -213,8 +220,8 @@ class RefreshTokenGrantTest extends \PHPUnit_Framework_TestCase
$grant = new RefreshTokenGrant($refreshTokenRepositoryMock); $grant = new RefreshTokenGrant($refreshTokenRepositoryMock);
$grant->setClientRepository($clientRepositoryMock); $grant->setClientRepository($clientRepositoryMock);
$grant->setAccessTokenRepository($accessTokenRepositoryMock); $grant->setAccessTokenRepository($accessTokenRepositoryMock);
$grant->setPathToPublicKey('file://' . __DIR__ . '/../Utils/public.key'); $grant->setPublicKeyPath('file://' . __DIR__ . '/../Stubs/public.key');
$grant->setPathToPrivateKey('file://' . __DIR__ . '/../Utils/private.key'); $grant->setPrivateKeyPath('file://' . __DIR__ . '/../Stubs/private.key');
$serverRequest = new ServerRequest(); $serverRequest = new ServerRequest();
$serverRequest = $serverRequest->withParsedBody( $serverRequest = $serverRequest->withParsedBody(
@ -246,8 +253,8 @@ class RefreshTokenGrantTest extends \PHPUnit_Framework_TestCase
$grant = new RefreshTokenGrant($refreshTokenRepositoryMock); $grant = new RefreshTokenGrant($refreshTokenRepositoryMock);
$grant->setClientRepository($clientRepositoryMock); $grant->setClientRepository($clientRepositoryMock);
$grant->setAccessTokenRepository($accessTokenRepositoryMock); $grant->setAccessTokenRepository($accessTokenRepositoryMock);
$grant->setPathToPublicKey('file://' . __DIR__ . '/../Utils/public.key'); $grant->setPublicKeyPath('file://' . __DIR__ . '/../Stubs/public.key');
$grant->setPathToPrivateKey('file://' . __DIR__ . '/../Utils/private.key'); $grant->setPrivateKeyPath('file://' . __DIR__ . '/../Stubs/private.key');
$oldRefreshToken = 'foobar'; $oldRefreshToken = 'foobar';
@ -286,10 +293,10 @@ class RefreshTokenGrantTest extends \PHPUnit_Framework_TestCase
$grant = new RefreshTokenGrant($refreshTokenRepositoryMock); $grant = new RefreshTokenGrant($refreshTokenRepositoryMock);
$grant->setClientRepository($clientRepositoryMock); $grant->setClientRepository($clientRepositoryMock);
$grant->setAccessTokenRepository($accessTokenRepositoryMock); $grant->setAccessTokenRepository($accessTokenRepositoryMock);
$grant->setPathToPublicKey('file://' . __DIR__ . '/../Utils/public.key'); $grant->setPublicKeyPath('file://' . __DIR__ . '/../Stubs/public.key');
$grant->setPathToPrivateKey('file://' . __DIR__ . '/../Utils/private.key'); $grant->setPrivateKeyPath('file://' . __DIR__ . '/../Stubs/private.key');
$oldRefreshToken = KeyCrypt::encrypt( $oldRefreshToken = $this->cryptStub->doEncrypt(
json_encode( json_encode(
[ [
'client_id' => 'bar', 'client_id' => 'bar',
@ -299,8 +306,7 @@ class RefreshTokenGrantTest extends \PHPUnit_Framework_TestCase
'user_id' => 123, 'user_id' => 123,
'expire_time' => time() + 3600, 'expire_time' => time() + 3600,
] ]
), )
'file://' . __DIR__ . '/../Utils/private.key'
); );
$serverRequest = new ServerRequest(); $serverRequest = new ServerRequest();
@ -334,10 +340,10 @@ class RefreshTokenGrantTest extends \PHPUnit_Framework_TestCase
$grant = new RefreshTokenGrant($refreshTokenRepositoryMock); $grant = new RefreshTokenGrant($refreshTokenRepositoryMock);
$grant->setClientRepository($clientRepositoryMock); $grant->setClientRepository($clientRepositoryMock);
$grant->setAccessTokenRepository($accessTokenRepositoryMock); $grant->setAccessTokenRepository($accessTokenRepositoryMock);
$grant->setPathToPublicKey('file://' . __DIR__ . '/../Utils/public.key'); $grant->setPublicKeyPath('file://' . __DIR__ . '/../Stubs/public.key');
$grant->setPathToPrivateKey('file://' . __DIR__ . '/../Utils/private.key'); $grant->setPrivateKeyPath('file://' . __DIR__ . '/../Stubs/private.key');
$oldRefreshToken = KeyCrypt::encrypt( $oldRefreshToken = $this->cryptStub->doEncrypt(
json_encode( json_encode(
[ [
'client_id' => 'foo', 'client_id' => 'foo',
@ -347,8 +353,7 @@ class RefreshTokenGrantTest extends \PHPUnit_Framework_TestCase
'user_id' => 123, 'user_id' => 123,
'expire_time' => time() - 3600, 'expire_time' => time() - 3600,
] ]
), )
'file://' . __DIR__ . '/../Utils/private.key'
); );
$serverRequest = new ServerRequest(); $serverRequest = new ServerRequest();
@ -383,10 +388,10 @@ class RefreshTokenGrantTest extends \PHPUnit_Framework_TestCase
$grant = new RefreshTokenGrant($refreshTokenRepositoryMock); $grant = new RefreshTokenGrant($refreshTokenRepositoryMock);
$grant->setClientRepository($clientRepositoryMock); $grant->setClientRepository($clientRepositoryMock);
$grant->setAccessTokenRepository($accessTokenRepositoryMock); $grant->setAccessTokenRepository($accessTokenRepositoryMock);
$grant->setPathToPublicKey('file://' . __DIR__ . '/../Utils/public.key'); $grant->setPublicKeyPath('file://' . __DIR__ . '/../Stubs/public.key');
$grant->setPathToPrivateKey('file://' . __DIR__ . '/../Utils/private.key'); $grant->setPrivateKeyPath('file://' . __DIR__ . '/../Stubs/private.key');
$oldRefreshToken = KeyCrypt::encrypt( $oldRefreshToken = $this->cryptStub->doEncrypt(
json_encode( json_encode(
[ [
'client_id' => 'foo', 'client_id' => 'foo',
@ -396,8 +401,7 @@ class RefreshTokenGrantTest extends \PHPUnit_Framework_TestCase
'user_id' => 123, 'user_id' => 123,
'expire_time' => time() + 3600, 'expire_time' => time() + 3600,
] ]
), )
'file://' . __DIR__ . '/../Utils/private.key'
); );
$serverRequest = new ServerRequest(); $serverRequest = new ServerRequest();

View File

@ -2,11 +2,13 @@
namespace LeagueTests\Middleware; namespace LeagueTests\Middleware;
use League\OAuth2\Server\Entities\AccessTokenEntity;
use League\OAuth2\Server\Middleware\ResourceServerMiddleware; use League\OAuth2\Server\Middleware\ResourceServerMiddleware;
use League\OAuth2\Server\Repositories\AccessTokenRepositoryInterface; use League\OAuth2\Server\Repositories\AccessTokenRepositoryInterface;
use League\OAuth2\Server\Repositories\ClientRepositoryInterface; use League\OAuth2\Server\Repositories\ClientRepositoryInterface;
use League\OAuth2\Server\Repositories\ScopeRepositoryInterface; use League\OAuth2\Server\Repositories\ScopeRepositoryInterface;
use League\OAuth2\Server\Server; use League\OAuth2\Server\Server;
use LeagueTests\Stubs\ClientEntity;
use LeagueTests\Stubs\StubResponseType; use LeagueTests\Stubs\StubResponseType;
use Zend\Diactoros\Response; use Zend\Diactoros\Response;
use Zend\Diactoros\ServerRequest; use Zend\Diactoros\ServerRequest;
@ -21,13 +23,24 @@ class ResourceServerMiddlewareTest extends \PHPUnit_Framework_TestCase
$clientRepository, $clientRepository,
$this->getMock(AccessTokenRepositoryInterface::class), $this->getMock(AccessTokenRepositoryInterface::class),
$this->getMock(ScopeRepositoryInterface::class), $this->getMock(ScopeRepositoryInterface::class),
'', 'file://' . __DIR__ . '/../Stubs/private.key',
'', 'file://' . __DIR__ . '/../Stubs/public.key',
new StubResponseType() new StubResponseType()
); );
$client = new ClientEntity();
$client->setIdentifier('clientName');
$accessToken = new AccessTokenEntity();
$accessToken->setIdentifier('test');
$accessToken->setUserIdentifier(123);
$accessToken->setExpiryDateTime((new \DateTime())->add(new \DateInterval('PT1H')));
$accessToken->setClient($client);
$token = $accessToken->convertToJWT('file://' . __DIR__ . '/../Stubs/private.key');
$request = new ServerRequest(); $request = new ServerRequest();
$request = $request->withHeader('authorization', 'Basic test'); $request = $request->withHeader('authorization', sprintf('Bearer %s', $token));
$middleware = new ResourceServerMiddleware($server); $middleware = new ResourceServerMiddleware($server);
$response = $middleware->__invoke( $response = $middleware->__invoke(

View File

@ -2,6 +2,7 @@
namespace LeagueTests\ResponseTypes; namespace LeagueTests\ResponseTypes;
use League\OAuth2\Server\AuthorizationValidators\BearerTokenValidator;
use League\OAuth2\Server\Entities\AccessTokenEntity; use League\OAuth2\Server\Entities\AccessTokenEntity;
use League\OAuth2\Server\Entities\RefreshTokenEntity; use League\OAuth2\Server\Entities\RefreshTokenEntity;
use League\OAuth2\Server\Exception\OAuthServerException; use League\OAuth2\Server\Exception\OAuthServerException;
@ -19,11 +20,9 @@ class BearerResponseTypeTest extends \PHPUnit_Framework_TestCase
{ {
$accessTokenRepositoryMock = $this->getMockBuilder(AccessTokenRepositoryInterface::class)->getMock(); $accessTokenRepositoryMock = $this->getMockBuilder(AccessTokenRepositoryInterface::class)->getMock();
$responseType = new BearerTokenResponse( $responseType = new BearerTokenResponse($accessTokenRepositoryMock);
'file://' . __DIR__ . '/../Utils/private.key', $responseType->setPrivateKeyPath('file://' . __DIR__ . '/../Stubs/private.key');
'file://' . __DIR__ . '/../Utils/public.key', $responseType->setPublicKeyPath('file://' . __DIR__ . '/../Stubs/public.key');
$accessTokenRepositoryMock
);
$client = new ClientEntity(); $client = new ClientEntity();
$client->setIdentifier('clientName'); $client->setIdentifier('clientName');
@ -64,12 +63,11 @@ class BearerResponseTypeTest extends \PHPUnit_Framework_TestCase
public function testDetermineAccessTokenInHeaderValidToken() public function testDetermineAccessTokenInHeaderValidToken()
{ {
$accessTokenRepositoryMock = $this->getMockBuilder(AccessTokenRepositoryInterface::class)->getMock(); $accessTokenRepositoryMock = $this->getMockBuilder(AccessTokenRepositoryInterface::class)->getMock();
$accessTokenRepositoryMock->method('isAccessTokenRevoked')->willReturn(false);
$responseType = new BearerTokenResponse( $responseType = new BearerTokenResponse($accessTokenRepositoryMock);
'file://' . __DIR__ . '/../Utils/private.key', $responseType->setPrivateKeyPath('file://' . __DIR__ . '/../Stubs/private.key');
'file://' . __DIR__ . '/../Utils/public.key', $responseType->setPublicKeyPath('file://' . __DIR__ . '/../Stubs/public.key');
$accessTokenRepositoryMock
);
$client = new ClientEntity(); $client = new ClientEntity();
$client->setIdentifier('clientName'); $client->setIdentifier('clientName');
@ -89,13 +87,16 @@ class BearerResponseTypeTest extends \PHPUnit_Framework_TestCase
$responseType->setRefreshToken($refreshToken); $responseType->setRefreshToken($refreshToken);
$response = $responseType->generateHttpResponse(new Response()); $response = $responseType->generateHttpResponse(new Response());
$response->getBody()->rewind(); $json = json_decode((string) $response->getBody());
$json = json_decode($response->getBody()->getContents());
$authorizationValidator = new BearerTokenValidator($accessTokenRepositoryMock);
$authorizationValidator->setPrivateKeyPath('file://' . __DIR__ . '/../Stubs/private.key');
$authorizationValidator->setPublicKeyPath('file://' . __DIR__ . '/../Stubs/public.key');
$request = new ServerRequest(); $request = new ServerRequest();
$request = $request->withHeader('authorization', sprintf('Bearer %s', $json->access_token)); $request = $request->withHeader('authorization', sprintf('Bearer %s', $json->access_token));
$request = $responseType->validateAccessToken($request); $request = $authorizationValidator->validateAuthorization($request);
$this->assertEquals('abcdef', $request->getAttribute('oauth_access_token_id')); $this->assertEquals('abcdef', $request->getAttribute('oauth_access_token_id'));
$this->assertEquals('clientName', $request->getAttribute('oauth_client_id')); $this->assertEquals('clientName', $request->getAttribute('oauth_client_id'));
@ -106,12 +107,11 @@ class BearerResponseTypeTest extends \PHPUnit_Framework_TestCase
public function testDetermineAccessTokenInHeaderInvalidJWT() public function testDetermineAccessTokenInHeaderInvalidJWT()
{ {
$accessTokenRepositoryMock = $this->getMockBuilder(AccessTokenRepositoryInterface::class)->getMock(); $accessTokenRepositoryMock = $this->getMockBuilder(AccessTokenRepositoryInterface::class)->getMock();
$accessTokenRepositoryMock->method('isAccessTokenRevoked')->willReturn(false);
$responseType = new BearerTokenResponse( $responseType = new BearerTokenResponse($accessTokenRepositoryMock);
'file://' . __DIR__ . '/../Utils/private.key', $responseType->setPrivateKeyPath('file://' . __DIR__ . '/../Stubs/private.key');
'file://' . __DIR__ . '/../Utils/public.key', $responseType->setPublicKeyPath('file://' . __DIR__ . '/../Stubs/public.key');
$accessTokenRepositoryMock
);
$client = new ClientEntity(); $client = new ClientEntity();
$client->setIdentifier('clientName'); $client->setIdentifier('clientName');
@ -131,14 +131,17 @@ class BearerResponseTypeTest extends \PHPUnit_Framework_TestCase
$responseType->setRefreshToken($refreshToken); $responseType->setRefreshToken($refreshToken);
$response = $responseType->generateHttpResponse(new Response()); $response = $responseType->generateHttpResponse(new Response());
$response->getBody()->rewind(); $json = json_decode((string) $response->getBody());
$json = json_decode($response->getBody()->getContents());
$authorizationValidator = new BearerTokenValidator($accessTokenRepositoryMock);
$authorizationValidator->setPrivateKeyPath('file://' . __DIR__ . '/../Stubs/private.key');
$authorizationValidator->setPublicKeyPath('file://' . __DIR__ . '/../Stubs/public.key');
$request = new ServerRequest(); $request = new ServerRequest();
$request = $request->withHeader('authorization', sprintf('Bearer %s', $json->access_token . 'foo')); $request = $request->withHeader('authorization', sprintf('Bearer %s', $json->access_token . 'foo'));
try { try {
$responseType->validateAccessToken($request); $authorizationValidator->validateAuthorization($request);
} catch (OAuthServerException $e) { } catch (OAuthServerException $e) {
$this->assertEquals( $this->assertEquals(
'Access token could not be verified', 'Access token could not be verified',
@ -150,14 +153,11 @@ class BearerResponseTypeTest extends \PHPUnit_Framework_TestCase
public function testDetermineAccessTokenInHeaderRevokedToken() public function testDetermineAccessTokenInHeaderRevokedToken()
{ {
$accessTokenRepositoryMock = $this->getMockBuilder(AccessTokenRepositoryInterface::class)->getMock(); $accessTokenRepositoryMock = $this->getMockBuilder(AccessTokenRepositoryInterface::class)->getMock();
$accessTokenRepositoryMock->expects($this->once())->method('isAccessTokenRevoked')->willReturn(true); $accessTokenRepositoryMock->method('isAccessTokenRevoked')->willReturn(true);
$responseType = new BearerTokenResponse($accessTokenRepositoryMock);
$responseType = new BearerTokenResponse( $responseType->setPrivateKeyPath('file://' . __DIR__ . '/../Stubs/private.key');
'file://' . __DIR__ . '/../Utils/private.key', $responseType->setPublicKeyPath('file://' . __DIR__ . '/../Stubs/public.key');
'file://' . __DIR__ . '/../Utils/public.key',
$accessTokenRepositoryMock
);
$client = new ClientEntity(); $client = new ClientEntity();
$client->setIdentifier('clientName'); $client->setIdentifier('clientName');
@ -177,14 +177,17 @@ class BearerResponseTypeTest extends \PHPUnit_Framework_TestCase
$responseType->setRefreshToken($refreshToken); $responseType->setRefreshToken($refreshToken);
$response = $responseType->generateHttpResponse(new Response()); $response = $responseType->generateHttpResponse(new Response());
$response->getBody()->rewind(); $json = json_decode((string) $response->getBody());
$json = json_decode($response->getBody()->getContents());
$authorizationValidator = new BearerTokenValidator($accessTokenRepositoryMock);
$authorizationValidator->setPrivateKeyPath('file://' . __DIR__ . '/../Stubs/private.key');
$authorizationValidator->setPublicKeyPath('file://' . __DIR__ . '/../Stubs/public.key');
$request = new ServerRequest(); $request = new ServerRequest();
$request = $request->withHeader('authorization', sprintf('Bearer %s', $json->access_token)); $request = $request->withHeader('authorization', sprintf('Bearer %s', $json->access_token));
try { try {
$responseType->validateAccessToken($request); $authorizationValidator->validateAuthorization($request);
} catch (OAuthServerException $e) { } catch (OAuthServerException $e) {
$this->assertEquals( $this->assertEquals(
'Access token has been revoked', 'Access token has been revoked',
@ -197,17 +200,19 @@ class BearerResponseTypeTest extends \PHPUnit_Framework_TestCase
{ {
$accessTokenRepositoryMock = $this->getMockBuilder(AccessTokenRepositoryInterface::class)->getMock(); $accessTokenRepositoryMock = $this->getMockBuilder(AccessTokenRepositoryInterface::class)->getMock();
$responseType = new BearerTokenResponse( $responseType = new BearerTokenResponse($accessTokenRepositoryMock);
'file://' . __DIR__ . '/../Utils/private.key', $responseType->setPrivateKeyPath('file://' . __DIR__ . '/../Stubs/private.key');
'file://' . __DIR__ . '/../Utils/public.key', $responseType->setPublicKeyPath('file://' . __DIR__ . '/../Stubs/public.key');
$accessTokenRepositoryMock
); $authorizationValidator = new BearerTokenValidator($accessTokenRepositoryMock);
$authorizationValidator->setPrivateKeyPath('file://' . __DIR__ . '/../Stubs/private.key');
$authorizationValidator->setPublicKeyPath('file://' . __DIR__ . '/../Stubs/public.key');
$request = new ServerRequest(); $request = new ServerRequest();
$request = $request->withHeader('authorization', 'Bearer blah'); $request = $request->withHeader('authorization', 'Bearer blah');
try { try {
$responseType->validateAccessToken($request); $authorizationValidator->validateAuthorization($request);
} catch (OAuthServerException $e) { } catch (OAuthServerException $e) {
$this->assertEquals( $this->assertEquals(
'The JWT string must have two dots', 'The JWT string must have two dots',

View File

@ -15,8 +15,10 @@ use League\OAuth2\Server\ResponseTypes\BearerTokenResponse;
use League\OAuth2\Server\Server; use League\OAuth2\Server\Server;
use LeagueTests\Stubs\ClientEntity; use LeagueTests\Stubs\ClientEntity;
use LeagueTests\Stubs\StubResponseType; use LeagueTests\Stubs\StubResponseType;
use LeagueTests\Stubs\UserEntity;
use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ResponseInterface;
use Zend\Diactoros\ServerRequest; use Zend\Diactoros\Response;
use Zend\Diactoros\ServerRequestFactory;
class ServerTest extends \PHPUnit_Framework_TestCase class ServerTest extends \PHPUnit_Framework_TestCase
{ {
@ -34,7 +36,7 @@ class ServerTest extends \PHPUnit_Framework_TestCase
$server->enableGrantType(new ClientCredentialsGrant(), new \DateInterval('PT1M')); $server->enableGrantType(new ClientCredentialsGrant(), new \DateInterval('PT1M'));
try { try {
$server->respondToRequest(); $server->respondToRequest(ServerRequestFactory::fromGlobals(), new Response);
} catch (OAuthServerException $e) { } catch (OAuthServerException $e) {
$this->assertEquals('unsupported_grant_type', $e->getErrorType()); $this->assertEquals('unsupported_grant_type', $e->getErrorType());
$this->assertEquals(400, $e->getHttpStatusCode()); $this->assertEquals(400, $e->getHttpStatusCode());
@ -60,7 +62,7 @@ class ServerTest extends \PHPUnit_Framework_TestCase
$_POST['grant_type'] = 'client_credentials'; $_POST['grant_type'] = 'client_credentials';
$_POST['client_id'] = 'foo'; $_POST['client_id'] = 'foo';
$_POST['client_secret'] = 'bar'; $_POST['client_secret'] = 'bar';
$response = $server->respondToRequest(); $response = $server->respondToRequest(ServerRequestFactory::fromGlobals(), new Response);
$this->assertEquals(200, $response->getStatusCode()); $this->assertEquals(200, $response->getStatusCode());
} }
@ -77,16 +79,19 @@ class ServerTest extends \PHPUnit_Framework_TestCase
$clientRepository, $clientRepository,
$this->getMock(AccessTokenRepositoryInterface::class), $this->getMock(AccessTokenRepositoryInterface::class),
$this->getMock(ScopeRepositoryInterface::class), $this->getMock(ScopeRepositoryInterface::class),
'', 'file://' . __DIR__ . '/Stubs/private.key',
'', 'file://' . __DIR__ . '/Stubs/public.key',
new StubResponseType() new StubResponseType()
); );
$userRepository = $this->getMock(UserRepositoryInterface::class);
$userRepository->method('getUserEntityByUserCredentials')->willReturn(new UserEntity());
$server->enableGrantType( $server->enableGrantType(
new AuthCodeGrant( new AuthCodeGrant(
$this->getMock(AuthCodeRepositoryInterface::class), $this->getMock(AuthCodeRepositoryInterface::class),
$this->getMock(RefreshTokenRepositoryInterface::class), $this->getMock(RefreshTokenRepositoryInterface::class),
$this->getMock(UserRepositoryInterface::class), $userRepository,
new \DateInterval('PT1H') new \DateInterval('PT1H')
), ),
new \DateInterval('PT1M') new \DateInterval('PT1M')
@ -97,9 +102,13 @@ class ServerTest extends \PHPUnit_Framework_TestCase
$_GET['response_type'] = 'code'; $_GET['response_type'] = 'code';
$_GET['client_id'] = $client->getIdentifier(); $_GET['client_id'] = $client->getIdentifier();
$_GET['redirect_uri'] = $client->getRedirectUri(); $_GET['redirect_uri'] = $client->getRedirectUri();
$response = $server->respondToRequest(); $_POST['action'] = 'approve';
$this->assertEquals(200, $response->getStatusCode()); $_POST['username'] = 'user';
$_POST['password'] = 'pass';
$response = $server->respondToRequest(ServerRequestFactory::fromGlobals(), new Response);
$this->assertTrue($response instanceof ResponseInterface); $this->assertTrue($response instanceof ResponseInterface);
$this->assertEquals(302, $response->getStatusCode());
$this->assertTrue(strstr($response->getHeaderLine('location'), 'code=') !== false);
} }
public function testGetResponseType() public function testGetResponseType()
@ -134,7 +143,7 @@ class ServerTest extends \PHPUnit_Framework_TestCase
); );
try { try {
$server->validateAuthenticatedRequest(new ServerRequest()); $server->validateAuthenticatedRequest(ServerRequestFactory::fromGlobals());
} catch (OAuthServerException $e) { } catch (OAuthServerException $e) {
$this->assertEquals('Missing "Authorization" header', $e->getHint()); $this->assertEquals('Missing "Authorization" header', $e->getHint());
} }

View File

@ -0,0 +1,26 @@
<?php
namespace LeagueTests\Stubs;
use League\OAuth2\Server\CryptTrait;
class CryptTraitStub
{
use CryptTrait;
public function __construct()
{
$this->setPrivateKeyPath('file://' . __DIR__ . '/private.key');
$this->setPublicKeyPath('file://' . __DIR__ . '/public.key');
}
public function doEncrypt($unencryptedData)
{
return $this->encrypt($unencryptedData);
}
public function doDecrypt($encryptedData)
{
return $this->decrypt($encryptedData);
}
}

View File

@ -1,34 +0,0 @@
<?php
namespace LeagueTests\Utils;
use League\OAuth2\Server\Utils\KeyCrypt;
class KeyCryptTest extends \PHPUnit_Framework_TestCase
{
public function testEncryptDecrypt()
{
$payload = 'alex loves whisky';
$encrypted = KeyCrypt::encrypt($payload, 'file://' . __DIR__ . '/private.key');
$plainText = KeyCrypt::decrypt($encrypted, 'file://' . __DIR__ . '/public.key');
$this->assertNotEquals($payload, $encrypted);
$this->assertEquals($payload, $plainText);
}
/**
* @expectedException \LogicException
*/
public function testBadPrivateKey()
{
KeyCrypt::encrypt('', 'file://' . __DIR__ . '/public.key');
}
/**
* @expectedException \LogicException
*/
public function testBadPublicKey()
{
KeyCrypt::decrypt('', 'file://' . __DIR__ . '/private.key');
}
}