Merge branch 'V5-WIP' into move_identifier_generation

This commit is contained in:
Julián Gutiérrez 2016-02-13 14:11:38 +01:00
commit 5d6634aa9f
52 changed files with 443 additions and 3561 deletions

1
.gitattributes vendored
View File

@ -7,7 +7,6 @@
/.travis.yml export-ignore /.travis.yml export-ignore
.travis.yml export-ignore .travis.yml export-ignore
.scrutinizer.yml export-ignore .scrutinizer.yml export-ignore
/codeception.yml export-ignore
/phpunit.xml.dist export-ignore /phpunit.xml.dist export-ignore
/CHANGELOG.md export-ignore /CHANGELOG.md export-ignore
/CONTRIBUTING.md export-ignore /CONTRIBUTING.md export-ignore

2
.gitignore vendored
View File

@ -3,6 +3,6 @@
phpunit.xml phpunit.xml
.idea .idea
/examples/vendor /examples/vendor
/tests/_output
examples/public.key examples/public.key
examples/private.key examples/private.key
build

View File

@ -15,37 +15,10 @@ php:
install: install:
- travis_retry composer install --no-interaction --prefer-source - travis_retry composer install --no-interaction --prefer-source
before_script:
- cd examples/
- composer install
- cd public/
- php -S localhost:7777 &
- cd ../..
script: script:
- vendor/bin/codecept build && vendor/bin/codecept run - vendor/bin/phpunit
after_script:
- wget https://scrutinizer-ci.com/ocular.phar
- php ocular.phar code-coverage:upload --format=php-clover coverage.clover
- git config --global user.email "travis@travis-ci.org"
- git config --global user.name "TravisCI"
- cp -R coverage ${HOME}/coverage
- cd ${HOME}
- git clone --quiet --branch=gh-pages https://${GITHUBTOKEN}@github.com/thephpleague/oauth2-server.git gh-pages > /dev/null
- cd gh-pages
- mkdir ${TRAVIS_BRANCH}
- cd ${TRAVIS_BRANCH}
- cp -Rf $HOME/coverage/* .
- git add -f .
- git commit -m "Travis pushed coverage of ${TRAVIS_COMMIT}@${TRAVIS_BRANCH} to gh-pages"
- git push -fq origin gh-pages > /dev/null
branches: branches:
only: only:
- master - master
- v5 - V5-WIP
env:
global:
secure: "C4wD/BQefKSu9W594iyLp+IBCjlM8kKlmp+nXKXnZGi0L8IkV3m4mmNOb8PExxGMhZ3mlev5DnU4Uoh4oJaUxnkR1FpX4dSEpyzU3VknUzSE2yZOlL+bdCw3o85TGoCcp/+ReJCOw5sncxTskJKHlW1YMa33FznaXwLNoImpjTg="

View File

@ -1,10 +0,0 @@
actor: Tester
paths:
tests: tests
log: tests/_output
data: tests/_data
helpers: tests/_support
settings:
bootstrap: _bootstrap.php
colors: true
memory_limit: 1024M

View File

@ -11,10 +11,7 @@
"paragonie/random_compat": "^1.1" "paragonie/random_compat": "^1.1"
}, },
"require-dev": { "require-dev": {
"phpunit/phpunit": "4.8.*", "phpunit/phpunit": "4.8.*"
"mockery/mockery": "0.9.*",
"codeception/codeception": "~2.0",
"flow/jsonpath": "0.2.*"
}, },
"repositories": [ "repositories": [
{ {
@ -57,7 +54,7 @@
}, },
"autoload-dev": { "autoload-dev": {
"psr-4": { "psr-4": {
"LeagueTests\\": "tests/unit/" "LeagueTests\\": "tests/"
} }
}, },
"extra": { "extra": {

View File

@ -1,17 +1,23 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<phpunit colors="true" convertNoticesToExceptions="true" convertWarningsToExceptions="true" stopOnError="true" stopOnFailure="true" stopOnIncomplete="false" stopOnSkipped="false" bootstrap="tests/unit/Bootstrap.php"> <phpunit colors="true" convertNoticesToExceptions="true" convertWarningsToExceptions="true" stopOnError="true"
stopOnFailure="true" stopOnIncomplete="false" stopOnSkipped="false" bootstrap="tests/Bootstrap.php">
<testsuites> <testsuites>
<testsuite name="Tests"> <testsuite name="Tests">
<directory>./tests/unit/</directory> <directory>./tests/</directory>
</testsuite> </testsuite>
</testsuites> </testsuites>
<filter> <filter>
<whitelist addUncoveredFilesFromWhitelist="true"> <whitelist addUncoveredFilesFromWhitelist="true">
<directory suffix=".php">src</directory> <directory suffix=".php">src</directory>
<exclude>
<directory suffix=".php">src/ResponseTypes/DefaultTemplates</directory>
</exclude>
</whitelist> </whitelist>
</filter> </filter>
<logging> <logging>
<!-- <log type="coverage-text" target="php://stdout" title="thephpleague/oauth2-server" charset="UTF-8" yui="true" highlight="true" lowUpperBound="60" highLowerBound="90"/> --> <log type="coverage-text" target="php://stdout" title="thephpleague/oauth2-server" charset="UTF-8" yui="true"
<log type="coverage-html" target="build/coverage" title="thephpleague/oauth2-server" charset="UTF-8" yui="true" highlight="true" lowUpperBound="60" highLowerBound="90"/> highlight="true" lowUpperBound="60" highLowerBound="90"/>
<log type="coverage-html" target="build/coverage" title="thephpleague/oauth2-server" charset="UTF-8" yui="true"
highlight="true" lowUpperBound="60" highLowerBound="90"/>
</logging> </logging>
</phpunit> </phpunit>

View File

@ -1,79 +0,0 @@
<?php
namespace League\OAuth2\Server\Entities;
class AuthorizationCodeRequestEntity
{
/**
* @var string
*/
private $clientId;
/**
* @var null|string
*/
private $redirectUri;
/**
* @var null|string
*/
private $scope;
/**
* @var null|string
*/
private $state;
/**
* @return string
*/
public function getClientId()
{
return $this->clientId;
}
/**
* @return null|string
*/
public function getRedirectUri()
{
return $this->redirectUri;
}
/**
* @return null|string
*/
public function getScope()
{
return $this->scope;
}
/**
* @return null|string
*/
public function getState()
{
return $this->state;
}
/**
* AuthorizationCodeRequestEntity constructor.
*
* @param string $clientId
* @param string|null $redirectUri
* @param string|null $scope
* @param string|null $state
*/
public function __construct($clientId, $redirectUri = null, $scope = null, $state = null)
{
$this->clientId = $clientId;
$this->redirectUri = $redirectUri;
$this->scope = $scope;
$this->state = $state;
}
public function __sleep()
{
return ['clientId', 'redirectUri', 'scope', 'state'];
}
}

View File

@ -39,4 +39,10 @@ interface RefreshTokenEntityInterface
* @return \League\OAuth2\Server\Entities\Interfaces\AccessTokenEntityInterface * @return \League\OAuth2\Server\Entities\Interfaces\AccessTokenEntityInterface
*/ */
public function getAccessToken(); public function getAccessToken();
/**
* Has the token expired?
* @return bool
*/
public function isExpired();
} }

View File

@ -50,4 +50,13 @@ trait RefreshTokenTrait
{ {
$this->expiryDateTime = $dateTime; $this->expiryDateTime = $dateTime;
} }
/**
* Has the token expired?
* @return bool
*/
public function isExpired()
{
return (new DateTime()) > $this->getExpiryDateTime();
}
} }

View File

@ -34,13 +34,6 @@ abstract class AbstractGrant implements GrantTypeInterface
const SCOPE_DELIMITER_STRING = ' '; const SCOPE_DELIMITER_STRING = ' ';
/**
* Grant responds with
*
* @var string
*/
protected $respondsWith = 'token';
/** /**
* @var ServerRequestInterface * @var ServerRequestInterface
*/ */
@ -132,14 +125,6 @@ abstract class AbstractGrant implements GrantTypeInterface
$this->refreshTokenTTL = $refreshTokenTTL; $this->refreshTokenTTL = $refreshTokenTTL;
} }
/**
* {@inheritdoc}
*/
public function respondsWith()
{
return $this->respondsWith;
}
/** /**
* Validate the client * Validate the client
* *
@ -382,13 +367,16 @@ abstract class AbstractGrant implements GrantTypeInterface
{ {
try { try {
return bin2hex(random_bytes($length)); return bin2hex(random_bytes($length));
// @codeCoverageIgnoreStart
} catch (\TypeError $e) { } catch (\TypeError $e) {
throw OAuthServerException::serverError('An unexpected error has occurred'); throw OAuthServerException::serverError('An unexpected error has occurred');
} catch (\Error $e) { } catch (\Error $e) {
throw OAuthServerException::serverError('An unexpected error has occurred'); throw OAuthServerException::serverError('An unexpected error has occurred');
} catch (\Exception $e) { } catch (\Exception $e) {
// If you get this message, the CSPRNG failed hard.
throw OAuthServerException::serverError('Could not generate a random string'); throw OAuthServerException::serverError('Could not generate a random string');
} }
// @codeCoverageIgnoreEnd
} }
/** /**

View File

@ -37,13 +37,6 @@ interface GrantTypeInterface extends EmitterAwareInterface
*/ */
public function getIdentifier(); public function getIdentifier();
/**
* Details what the grant responds with
*
* @return string
*/
public function respondsWith();
/** /**
* Respond to an incoming request * Respond to an incoming request
* *

View File

@ -36,7 +36,9 @@ class KeyCrypt
$chunk = substr($unencryptedData, 0, $chunkSize); $chunk = substr($unencryptedData, 0, $chunkSize);
$unencryptedData = substr($unencryptedData, $chunkSize); $unencryptedData = substr($unencryptedData, $chunkSize);
if (openssl_private_encrypt($chunk, $encrypted, $privateKey) === false) { if (openssl_private_encrypt($chunk, $encrypted, $privateKey) === false) {
// @codeCoverageIgnoreStart
throw new \LogicException('Failed to encrypt data'); throw new \LogicException('Failed to encrypt data');
// @codeCoverageIgnoreEnd
} }
$output .= $encrypted; $output .= $encrypted;
} }
@ -72,7 +74,9 @@ class KeyCrypt
$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) === false) { if (openssl_public_decrypt($chunk, $decrypted, $publicKey) === false) {
// @codeCoverageIgnoreStart
throw new \LogicException('Failed to decrypt data'); throw new \LogicException('Failed to decrypt data');
// @codeCoverageIgnoreEnd
} }
$output .= $decrypted; $output .= $decrypted;
} }

49
src/Utils/SecureKey.php Normal file
View File

@ -0,0 +1,49 @@
<?php
/**
* OAuth 2.0 Secure key generator
*
* @package php-loep/oauth2-server
* @author Alex Bilbie <hello@alexbilbie.com>
* @copyright Copyright (c) 2013 PHP League of Extraordinary Packages
* @license http://mit-license.org/
* @link http://github.com/php-loep/oauth2-server
*/
namespace League\OAuth2\Server\Utils;
use League\OAuth2\Server\Exception\OAuthServerException;
/**
* SecureKey class
*/
class SecureKey
{
/**
* Generate a new unique code
*
* @param integer $len Length of the generated code
*
* @return string
* @throws \League\OAuth2\Server\Exception\OAuthServerException
*/
public static function generate($len = 40)
{
try {
$string = random_bytes($len);
// @codeCoverageIgnoreStart
} catch (\TypeError $e) {
// Well, it's an integer, so this IS unexpected.
throw OAuthServerException::serverError("An unexpected error has occurred");
} catch (\Error $e) {
// This is also unexpected because 32 is a reasonable integer.
throw OAuthServerException::serverError("An unexpected error has occurred");
} catch (\Exception $e) {
// If you get this message, the CSPRNG failed hard.
throw OAuthServerException::serverError("Could not generate a random string. Is our OS secure?");
}
// @codeCoverageIgnoreEnd
return bin2hex($string);
}
}

View File

@ -1,5 +1,5 @@
<?php <?php
if (! @include_once __DIR__.'/../../vendor/autoload.php') { if (! @include_once __DIR__ . '/../vendor/autoload.php') {
exit("You must set up the project dependencies, run the following commands:\n> wget http://getcomposer.org/composer.phar\n> php composer.phar install\n"); exit("You must set up the project dependencies, run the following commands:\n> wget http://getcomposer.org/composer.phar\n> php composer.phar install\n");
} }

View File

@ -0,0 +1,289 @@
<?php
namespace LeagueTests\Grant;
use League\Event\Emitter;
use League\OAuth2\Server\Entities\AccessTokenEntity;
use League\OAuth2\Server\Entities\ClientEntity;
use League\OAuth2\Server\Entities\Interfaces\AccessTokenEntityInterface;
use League\OAuth2\Server\Entities\Interfaces\AuthCodeEntityInterface;
use League\OAuth2\Server\Entities\Interfaces\RefreshTokenEntityInterface;
use League\OAuth2\Server\Entities\ScopeEntity;
use League\OAuth2\Server\Grant\AbstractGrant;
use League\OAuth2\Server\Repositories\AccessTokenRepositoryInterface;
use League\OAuth2\Server\Repositories\ClientRepositoryInterface;
use League\OAuth2\Server\Repositories\ScopeRepositoryInterface;
use Zend\Diactoros\ServerRequest;
class AbstractGrantTest extends \PHPUnit_Framework_TestCase
{
public function testGetSet()
{
$clientRepositoryMock = $this->getMock(ClientRepositoryInterface::class);
$accessTokenRepositoryMock = $this->getMock(AccessTokenRepositoryInterface::class);
$scopeRepositoryMock = $this->getMock(ScopeRepositoryInterface::class);
/** @var AbstractGrant $grantMock */
$grantMock = $this->getMockForAbstractClass(AbstractGrant::class);
$grantMock->setClientRepository($clientRepositoryMock);
$grantMock->setAccessTokenRepository($accessTokenRepositoryMock);
$grantMock->setScopeRepository($scopeRepositoryMock);
$grantMock->setPathToPrivateKey('./private.key');
$grantMock->setPathToPublicKey('./public.key');
$grantMock->setEmitter(new Emitter());
$grantMock->setRefreshTokenTTL(new \DateInterval('PT1H'));
}
public function testValidateClient()
{
$client = new ClientEntity();
$clientRepositoryMock = $this->getMockBuilder(ClientRepositoryInterface::class)->getMock();
$clientRepositoryMock->method('getClientEntity')->willReturn($client);
/** @var AbstractGrant $grantMock */
$grantMock = $this->getMockForAbstractClass(AbstractGrant::class);
$grantMock->setClientRepository($clientRepositoryMock);
$abstractGrantReflection = new \ReflectionClass($grantMock);
$serverRequest = new ServerRequest();
$serverRequest = $serverRequest->withParsedBody(
[
'client_id' => 'foo',
'client_secret' => 'bar',
'redirect_uri' => 'http://foo/bar',
]
);
$validateClientMethod = $abstractGrantReflection->getMethod('validateClient');
$validateClientMethod->setAccessible(true);
$result = $validateClientMethod->invoke($grantMock, $serverRequest, true, true);
$this->assertEquals($client, $result);
}
/**
* @expectedException \League\OAuth2\Server\Exception\OAuthServerException
*/
public function testValidateClientMissingClientId()
{
$client = new ClientEntity();
$clientRepositoryMock = $this->getMockBuilder(ClientRepositoryInterface::class)->getMock();
$clientRepositoryMock->method('getClientEntity')->willReturn($client);
/** @var AbstractGrant $grantMock */
$grantMock = $this->getMockForAbstractClass(AbstractGrant::class);
$grantMock->setClientRepository($clientRepositoryMock);
$abstractGrantReflection = new \ReflectionClass($grantMock);
$serverRequest = new ServerRequest();
$validateClientMethod = $abstractGrantReflection->getMethod('validateClient');
$validateClientMethod->setAccessible(true);
$validateClientMethod->invoke($grantMock, $serverRequest, true, true);
}
/**
* @expectedException \League\OAuth2\Server\Exception\OAuthServerException
*/
public function testValidateClientMissingClientSecret()
{
$client = new ClientEntity();
$clientRepositoryMock = $this->getMockBuilder(ClientRepositoryInterface::class)->getMock();
$clientRepositoryMock->method('getClientEntity')->willReturn($client);
/** @var AbstractGrant $grantMock */
$grantMock = $this->getMockForAbstractClass(AbstractGrant::class);
$grantMock->setClientRepository($clientRepositoryMock);
$abstractGrantReflection = new \ReflectionClass($grantMock);
$serverRequest = new ServerRequest();
$serverRequest = $serverRequest->withParsedBody([
'client_id' => 'foo',
]);
$validateClientMethod = $abstractGrantReflection->getMethod('validateClient');
$validateClientMethod->setAccessible(true);
$validateClientMethod->invoke($grantMock, $serverRequest, true, true);
}
/**
* @expectedException \League\OAuth2\Server\Exception\OAuthServerException
*/
public function testValidateClientMissingRedirectUri()
{
$client = new ClientEntity();
$clientRepositoryMock = $this->getMockBuilder(ClientRepositoryInterface::class)->getMock();
$clientRepositoryMock->method('getClientEntity')->willReturn($client);
/** @var AbstractGrant $grantMock */
$grantMock = $this->getMockForAbstractClass(AbstractGrant::class);
$grantMock->setClientRepository($clientRepositoryMock);
$abstractGrantReflection = new \ReflectionClass($grantMock);
$serverRequest = new ServerRequest();
$serverRequest = $serverRequest->withParsedBody([
'client_id' => 'foo',
'client_secret' => 'bar',
]);
$validateClientMethod = $abstractGrantReflection->getMethod('validateClient');
$validateClientMethod->setAccessible(true);
$validateClientMethod->invoke($grantMock, $serverRequest, true, true);
}
public function testCanRespondToRequest()
{
$grantMock = $this->getMockForAbstractClass(AbstractGrant::class);
$grantMock->method('getIdentifier')->willReturn('foobar');
$serverRequest = new ServerRequest();
$serverRequest = $serverRequest->withParsedBody([
'grant_type' => 'foobar',
]);
$this->assertTrue($grantMock->canRespondToRequest($serverRequest));
}
public function testIssueRefreshToken()
{
/** @var AbstractGrant $grantMock */
$grantMock = $this->getMockForAbstractClass(AbstractGrant::class);
$grantMock->setRefreshTokenTTL(new \DateInterval('PT1M'));
$abstractGrantReflection = new \ReflectionClass($grantMock);
$issueRefreshTokenMethod = $abstractGrantReflection->getMethod('issueRefreshToken');
$issueRefreshTokenMethod->setAccessible(true);
$accessToken = new AccessTokenEntity();
/** @var RefreshTokenEntityInterface $refreshToken */
$refreshToken = $issueRefreshTokenMethod->invoke($grantMock, $accessToken);
$this->assertTrue($refreshToken instanceof RefreshTokenEntityInterface);
$this->assertFalse($refreshToken->isExpired());
$this->assertEquals($accessToken, $refreshToken->getAccessToken());
}
public function testIssueAccessToken()
{
/** @var AbstractGrant $grantMock */
$grantMock = $this->getMockForAbstractClass(AbstractGrant::class);
$abstractGrantReflection = new \ReflectionClass($grantMock);
$issueAccessTokenMethod = $abstractGrantReflection->getMethod('issueAccessToken');
$issueAccessTokenMethod->setAccessible(true);
/** @var AccessTokenEntityInterface $accessToken */
$accessToken = $issueAccessTokenMethod->invoke(
$grantMock,
new \DateInterval('PT1H'),
new ClientEntity(),
123,
[new ScopeEntity()]
);
$this->assertTrue($accessToken instanceof AccessTokenEntityInterface);
$this->assertFalse($accessToken->isExpired());
}
public function testIssueAuthCode()
{
/** @var AbstractGrant $grantMock */
$grantMock = $this->getMockForAbstractClass(AbstractGrant::class);
$abstractGrantReflection = new \ReflectionClass($grantMock);
$issueAuthCodeMethod = $abstractGrantReflection->getMethod('issueAuthCode');
$issueAuthCodeMethod->setAccessible(true);
$this->assertTrue(
$issueAuthCodeMethod->invoke(
$grantMock,
new \DateInterval('PT1H'),
new ClientEntity(),
123,
'http://foo/bar',
[new ScopeEntity()]
) instanceof AuthCodeEntityInterface
);
}
public function testGetCookieParameter()
{
$grantMock = $this->getMockForAbstractClass(AbstractGrant::class);
$grantMock->method('getIdentifier')->willReturn('foobar');
$abstractGrantReflection = new \ReflectionClass($grantMock);
$method = $abstractGrantReflection->getMethod('getCookieParameter');
$method->setAccessible(true);
$serverRequest = new ServerRequest();
$serverRequest = $serverRequest->withCookieParams([
'foo' => 'bar',
]);
$this->assertEquals('bar', $method->invoke($grantMock, 'foo', $serverRequest));
$this->assertEquals('foo', $method->invoke($grantMock, 'bar', $serverRequest, 'foo'));
}
public function testGetQueryStringParameter()
{
$grantMock = $this->getMockForAbstractClass(AbstractGrant::class);
$grantMock->method('getIdentifier')->willReturn('foobar');
$abstractGrantReflection = new \ReflectionClass($grantMock);
$method = $abstractGrantReflection->getMethod('getQueryStringParameter');
$method->setAccessible(true);
$serverRequest = new ServerRequest();
$serverRequest = $serverRequest->withQueryParams([
'foo' => 'bar',
]);
$this->assertEquals('bar', $method->invoke($grantMock, 'foo', $serverRequest));
$this->assertEquals('foo', $method->invoke($grantMock, 'bar', $serverRequest, 'foo'));
}
public function testValidateScopes()
{
$scope = new ScopeEntity();
$scopeRepositoryMock = $this->getMockBuilder(ScopeRepositoryInterface::class)->getMock();
$scopeRepositoryMock->method('getScopeEntityByIdentifier')->willReturn($scope);
/** @var AbstractGrant $grantMock */
$grantMock = $this->getMockForAbstractClass(AbstractGrant::class);
$grantMock->setScopeRepository($scopeRepositoryMock);
$serverRequest = new ServerRequest();
$serverRequest = $serverRequest->withParsedBody(
[
'scope' => 'basic ',
]
);
$this->assertEquals([$scope], $grantMock->validateScopes($serverRequest, new ClientEntity()));
}
/**
* @expectedException \League\OAuth2\Server\Exception\OAuthServerException
*/
public function testValidateScopesBadScope()
{
$scopeRepositoryMock = $this->getMockBuilder(ScopeRepositoryInterface::class)->getMock();
$scopeRepositoryMock->method('getScopeEntityByIdentifier')->willReturn(null);
/** @var AbstractGrant $grantMock */
$grantMock = $this->getMockForAbstractClass(AbstractGrant::class);
$grantMock->setScopeRepository($scopeRepositoryMock);
$serverRequest = new ServerRequest();
$serverRequest = $serverRequest->withParsedBody(
[
'scope' => 'basic ',
]
);
$grantMock->validateScopes($serverRequest, new ClientEntity());
}
}

View File

@ -0,0 +1,34 @@
<?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');
}
}

15
tests/Utils/private.key Normal file
View File

@ -0,0 +1,15 @@
-----BEGIN RSA PRIVATE KEY-----
MIICXgIBAAKBgQDOBcFjGUlo3BJ9zjwQLgAHn6Oy5Si0uB7MublTiPob8rWTiCE4
weAFqzPoAB07vB0t0f8c1R8rmwHMD5ljWPBgJ8FewtwAUzprOBcau6DWukd/TKxX
WeVLAl/NZxijI+jR5QDBYLNBtj1G4LBVHMmINd3ryCycbf9ac3rcC8zhrQIDAQAB
AoGADfOJ0wIlXHp6rhZHLvlOezWuSjEGfqZxP3/cMvH1rerTrPfs+AD5AKlFTJKl
aCQm/bFYy0ULZVKL3pu30Wh2bo1nh/wLuLSI9Nz3O8jqAP3z0i07SoRoQmb8fRnn
dwoDFqnk3uGqcOenheSqheIgl9vdW/3avhD6nkMKZGxPYwECQQDoSj/xHogEzMqB
1Z2E5H/exeE9GQ7+dGITRR2MSgo9WvcKdRhGaQ44dsnTmqiZWAfqAPJjTQIIA/Cn
YRRTeBbNAkEA4w0iEvCIygGQOAnWuvVzlh+pxIB+BTeGkbiBG7nkYYc9b6B/Tw1B
GWGRddBr/FIfPvy1X2ip/TBpH+9bHnE2YQJBAIbZw/EYhmIy+UUSW9WwSUNsoOu1
Rm0V53HEZ/jvaq5fxpa9j5AgoO7KlzROzp3m6wE/93cKV6mLkAO7ae9jAekCQQCf
B6DZIS6+RrAMACAt3SOzf8P6BYG/B7Ayusd7cw2ang4S9JiW9xKkw2kN2wj3t1F5
XalwBTAjTdgj7ROmU+ehAkEAkOyXKONGBoVfaixRHgBP6jIBSSPbB2Aosi0QAURX
6GOY7wOS1pCSntTOBQxV7wVjqFwYAR10MSxFSNfpJ7RkzA==
-----END RSA PRIVATE KEY-----

6
tests/Utils/public.key Normal file
View File

@ -0,0 +1,6 @@
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDOBcFjGUlo3BJ9zjwQLgAHn6Oy
5Si0uB7MublTiPob8rWTiCE4weAFqzPoAB07vB0t0f8c1R8rmwHMD5ljWPBgJ8Fe
wtwAUzprOBcau6DWukd/TKxXWeVLAl/NZxijI+jR5QDBYLNBtj1G4LBVHMmINd3r
yCycbf9ac3rcC8zhrQIDAQAB
-----END PUBLIC KEY-----

View File

@ -1,2 +0,0 @@
<?php
// This is global bootstrap for autoloading

View File

View File

@ -1,10 +0,0 @@
<?php
namespace Codeception\Module;
// here you can define custom actions
// all public methods declared in helper class will be available in $I
class ApiHelper extends \Codeception\Module
{
}

View File

@ -1,8 +0,0 @@
class_name: ApiTester
modules:
enabled: [PhpBrowser, REST]
config:
PhpBrowser:
url: 'http://localhost:7777/'
REST:
url: 'http://localhost:7777/'

View File

@ -1,17 +0,0 @@
<?php
$I = new ApiTester($scenario);
$I->wantTo('get an access token using the client credentials grant');
$I->sendPOST(
'client_credentials.php/access_token',
[
'grant_type' => 'client_credentials',
'client_id' => 'myawesomeapp',
'client_secret' => 'abc123',
'scope' => 'basic'
]
);
$I->canSeeResponseCodeIs(200);
$I->canSeeResponseIsJson();
$I->seeResponseJsonMatchesJsonPath('$.token_type');
$I->seeResponseJsonMatchesJsonPath('$.expires_in');
$I->seeResponseJsonMatchesJsonPath('$.access_token');

View File

@ -1,17 +0,0 @@
<?php
$I = new ApiTester($scenario);
$I->wantTo('get an access token using the client credentials grant, invalid client id');
$I->sendPOST(
'client_credentials.php/access_token',
[
'grant_type' => 'client_credentials',
'client_id' => 'myawesomeapp-wrong',
'client_secret' => 'foobar'
]
);
$I->canSeeResponseCodeIs(401);
$I->canSeeResponseIsJson();
$I->seeResponseContainsJson([
'error' => 'invalid_client',
'message' => 'Client authentication failed.'
]);

View File

@ -1,17 +0,0 @@
<?php
$I = new ApiTester($scenario);
$I->wantTo('get an access token using the client credentials grant, invalid client secret');
$I->sendPOST(
'client_credentials.php/access_token',
[
'grant_type' => 'client_credentials',
'client_id' => 'myawesomeapp',
'client_secret' => 'foobar'
]
);
$I->canSeeResponseCodeIs(401);
$I->canSeeResponseIsJson();
$I->seeResponseContainsJson([
'error' => 'invalid_client',
'message' => 'Client authentication failed.'
]);

View File

@ -1,15 +0,0 @@
<?php
$I = new ApiTester($scenario);
$I->wantTo('get an access token using the client credentials grant, missing client id');
$I->sendPOST(
'client_credentials.php/access_token',
[
'grant_type' => 'client_credentials'
]
);
$I->canSeeResponseCodeIs(400);
$I->canSeeResponseIsJson();
$I->seeResponseContainsJson([
'error' => 'invalid_request',
'message' => 'The request is missing a required parameter, includes an invalid parameter value, includes a parameter more than once, or is otherwise malformed. Check the "client_id" parameter.'
]);

View File

@ -1,16 +0,0 @@
<?php
$I = new ApiTester($scenario);
$I->wantTo('get an access token using the client credentials grant, missing client secret');
$I->sendPOST(
'client_credentials.php/access_token',
[
'grant_type' => 'client_credentials',
'client_id' => 'myawesomeapp'
]
);
$I->canSeeResponseCodeIs(400);
$I->canSeeResponseIsJson();
$I->seeResponseContainsJson([
'error' => 'invalid_request',
'message' => 'The request is missing a required parameter, includes an invalid parameter value, includes a parameter more than once, or is otherwise malformed. Check the "client_secret" parameter.'
]);

View File

@ -1,2 +0,0 @@
<?php
// Here you can initialize variables that will be available to your tests

View File

@ -1,26 +0,0 @@
<?php
namespace LeagueTests;
use LeagueTests\Stubs\StubAbstractServer;
class AbstractServerTest extends \PHPUnit_Framework_TestCase
{
public function testSetGet()
{
$server = new StubAbstractServer();
$var = 0;
$server->addEventListener('event.name', function () use ($var) {
$var++;
$this->assertSame(1, $var);
});
$server->getEventEmitter()->emit('event.name');
$this->assertTrue($server->getRequest() instanceof \Symfony\Component\HttpFoundation\Request);
$this->assertTrue($server->getEventEmitter() instanceof \League\Event\Emitter);
$server2 = new StubAbstractServer();
$server2->setRequest((new \Symfony\Component\HttpFoundation\Request()));
$server2->setEventEmitter(1);
$this->assertTrue($server2->getRequest() instanceof \Symfony\Component\HttpFoundation\Request);
}
}

View File

@ -1,82 +0,0 @@
<?php
namespace LeagueTests;
use League\OAuth2\Server\AuthorizationServer;
use League\OAuth2\Server\Grant\GrantTypeInterface;
use League\OAuth2\Server\Storage\ScopeInterface;
use Mockery as M;
class AuthorizationServerTest extends \PHPUnit_Framework_TestCase
{
public function testSetGet()
{
$server = new AuthorizationServer();
$server->requireScopeParam(true);
$server->requireStateParam(true);
$server->setDefaultScope('foobar');
$server->setScopeDelimiter(',');
$server->setAccessTokenTTL(1);
$grant = M::mock('League\OAuth2\Server\Grant\GrantTypeInterface');
$grant->shouldReceive('getIdentifier')->andReturn('foobar');
$grant->shouldReceive('getResponseType')->andReturn('foobar');
$grant->shouldReceive('setAuthorizationServer');
$scopeStorage = M::mock('League\OAuth2\Server\Storage\ScopeInterface');
$scopeStorage->shouldReceive('setServer');
$server->addGrantType($grant);
$server->setScopeStorage($scopeStorage);
$this->assertTrue($server->hasGrantType('foobar'));
$this->assertTrue($server->getGrantType('foobar') instanceof GrantTypeInterface);
$this->assertSame($server->getResponseTypes(), ['foobar']);
$this->assertTrue($server->scopeParamRequired());
$this->assertTrue($server->stateParamRequired());
$this->assertTrue($server->getScopeStorage() instanceof ScopeInterface);
$this->assertEquals('foobar', $server->getDefaultScope());
$this->assertEquals(',', $server->getScopeDelimiter());
$this->assertEquals(1, $server->getAccessTokenTTL());
}
public function testInvalidGrantType()
{
$this->setExpectedException('League\OAuth2\Server\Exception\InvalidGrantException');
$server = new AuthorizationServer();
$server->getGrantType('foobar');
}
public function testIssueAccessToken()
{
$grant = M::mock('League\OAuth2\Server\Grant\GrantTypeInterface');
$grant->shouldReceive('getIdentifier')->andReturn('foobar');
$grant->shouldReceive('getResponseType')->andReturn('foobar');
$grant->shouldReceive('setAuthorizationServer');
$grant->shouldReceive('completeFlow')->andReturn(true);
$_POST['grant_type'] = 'foobar';
$server = new AuthorizationServer();
$server->addGrantType($grant);
$this->assertTrue($server->issueAccessToken());
}
public function testIssueAccessTokenEmptyGrantType()
{
$this->setExpectedException('League\OAuth2\Server\Exception\InvalidRequestException');
$server = new AuthorizationServer();
$this->assertTrue($server->issueAccessToken());
}
public function testIssueAccessTokenInvalidGrantType()
{
$this->setExpectedException('League\OAuth2\Server\Exception\UnsupportedGrantTypeException');
$_POST['grant_type'] = 'foobar';
$server = new AuthorizationServer();
$this->assertTrue($server->issueAccessToken());
}
}

View File

@ -1,116 +0,0 @@
<?php
namespace LeagueTests\Entity;
use League\OAuth2\Server\AuthorizationServer;
use League\OAuth2\Server\Entity\ScopeEntity;
use League\OAuth2\Server\Entity\SessionEntity;
use LeagueTests\Stubs\StubAbstractTokenEntity;
use Mockery as M;
class AbstractTokenEntityTest extends \PHPUnit_Framework_TestCase
{
public function testSetGet()
{
$server = M::mock('League\OAuth2\Server\AbstractServer');
$time = time();
$entity = new StubAbstractTokenEntity($server);
$entity->setId('foobar');
$entity->setExpireTime($time);
$entity->setSession((new SessionEntity($server)));
$entity->associateScope((new ScopeEntity($server))->hydrate(['id' => 'foo']));
$this->assertEquals('foobar', $entity->getId());
$this->assertEquals($time, $entity->getExpireTime());
// $this->assertTrue($entity->getSession() instanceof SessionEntity);
// $this->assertTrue($entity->hasScope('foo'));
// $result = $entity->getScopes();
// $this->assertTrue(isset($result['foo']));
}
/*public function testGetSession()
{
$server = M::mock('League\OAuth2\Server\AuthorizationServer');
$server->shouldReceive('setSessionStorage');
$sessionStorage = M::mock('League\OAuth2\Server\Storage\SessionInterface');
$sessionStorage->shouldReceive('getByAccessToken')->andReturn(
(new SessionEntity($server))
);
$sessionStorage->shouldReceive('setServer');
$server->shouldReceive('getStorage')->andReturn($sessionStorage);
$server->setSessionStorage($sessionStorage);
$entity = new StubAbstractTokenEntity($server);
$this->assertTrue($entity->getSession() instanceof SessionEntity);
}*/
/*public function testGetScopes()
{
$server = M::mock('League\OAuth2\Server\AuthorizationServer');
$server->shouldReceive('setAccessTokenStorage');
$accessTokenStorage = M::mock('League\OAuth2\Server\Storage\AccessTokenInterface');
$accessTokenStorage->shouldReceive('getScopes')->andReturn(
[]
);
$accessTokenStorage->shouldReceive('setServer');
$server->setAccessTokenStorage($accessTokenStorage);
$entity = new StubAbstractTokenEntity($server);
$this->assertEquals($entity->getScopes(), []);
}*/
/*public function testHasScopes()
{
$server = M::mock('League\OAuth2\Server\AuthorizationServer');
$accessTokenStorage = M::mock('League\OAuth2\Server\Storage\AccessTokenInterface');
$accessTokenStorage->shouldReceive('getScopes')->andReturn(
[]
);
$accessTokenStorage''>shouldReceive('setServer');
$server->setAccessTokenStorage($accessTokenStorage);
$entity = new StubAbstractTokenEntity($server);
$this->assertFalse($entity->hasScope('foo'));
}*/
public function testFormatScopes()
{
$server = M::mock('League\OAuth2\Server\AbstractServer');
$entity = new StubAbstractTokenEntity($server);
$reflectedEntity = new \ReflectionClass('LeagueTests\Stubs\StubAbstractTokenEntity');
$method = $reflectedEntity->getMethod('formatScopes');
$method->setAccessible(true);
$scopes = [
(new ScopeEntity($server))->hydrate(['id' => 'scope1', 'description' => 'foo']),
(new ScopeEntity($server))->hydrate(['id' => 'scope2', 'description' => 'bar']),
];
$result = $method->invokeArgs($entity, [$scopes]);
$this->assertTrue(isset($result['scope1']));
$this->assertTrue(isset($result['scope2']));
$this->assertTrue($result['scope1'] instanceof ScopeEntity);
$this->assertTrue($result['scope2'] instanceof ScopeEntity);
}
public function test__toString()
{
$server = M::mock('League\OAuth2\Server\AbstractServer');
$entity = new StubAbstractTokenEntity($server);
$this->assertEquals('', (string) $entity);
$entity->setId('foobar');
$this->assertEquals('foobar', (string) $entity);
}
}

View File

@ -1,59 +0,0 @@
<?php
namespace LeagueTests\Entity;
use League\OAuth2\Server\Entity\AccessTokenEntity;
use League\OAuth2\Server\Entity\ScopeEntity;
use League\OAuth2\Server\Entity\SessionEntity;
use Mockery as M;
class AccessTokenEntityTest extends \PHPUnit_Framework_TestCase
{
public function testSave()
{
$server = M::mock('League\OAuth2\Server\AbstractServer');
$server->shouldReceive('setAccessTokenStorage');
$server->shouldReceive('setSessionStorage');
$accessTokenStorage = M::mock('League\OAuth2\Server\Storage\AccessTokenInterface');
$accessTokenStorage->shouldReceive('create');
$accessTokenStorage->shouldReceive('associateScope');
$accessTokenStorage->shouldReceive('setServer');
$accessTokenStorage->shouldReceive('getScopes')->andReturn([
(new ScopeEntity($server))->hydrate(['id' => 'foo']),
]);
$sessionStorage = M::mock('League\OAuth2\Server\Storage\SessionInterface');
$sessionStorage->shouldReceive('getByAccessToken')->andReturn(
(new SessionEntity($server))
);
$sessionStorage->shouldReceive('setServer');
$server->shouldReceive('getSessionStorage')->andReturn($sessionStorage);
$server->shouldReceive('getAccessTokenStorage')->andReturn($accessTokenStorage);
$server->setAccessTokenStorage($accessTokenStorage);
$server->setSessionStorage($sessionStorage);
$entity = new AccessTokenEntity($server);
$this->assertTrue($entity->save() instanceof AccessTokenEntity);
}
public function testExpire()
{
$server = M::mock('League\OAuth2\Server\AbstractServer');
$server->shouldReceive('setAccessTokenStorage');
$accessTokenStorage = M::mock('League\OAuth2\Server\Storage\AccessTokenInterface');
$accessTokenStorage->shouldReceive('delete');
$accessTokenStorage->shouldReceive('setServer');
$server->shouldReceive('getAccessTokenStorage')->andReturn($accessTokenStorage);
$server->setAccessTokenStorage($accessTokenStorage);
$entity = new AccessTokenEntity($server);
$this->assertSame($entity->expire(), null);
}
}

View File

@ -1,73 +0,0 @@
<?php
namespace LeagueTests\Entity;
use League\OAuth2\Server\AuthorizationServer;
use League\OAuth2\Server\Entity\AuthCodeEntity;
use League\OAuth2\Server\Entity\ScopeEntity;
use League\OAuth2\Server\Entity\SessionEntity;
use Mockery as M;
class AuthCodeEntityTest extends \PHPUnit_Framework_TestCase
{
public function testSetGet()
{
$server = M::mock('League\OAuth2\Server\AbstractServer');
$session = M::mock('League\OAuth2\Server\Entity\SessionEntity');
$code = new AuthCodeEntity($server);
$code->setRedirectUri('http://foo/bar');
$code->setId('foobar');
$code->setSession($session);
$this->assertEquals('http://foo/bar', $code->getRedirectUri());
$this->assertEquals('http://foo/bar?code=foobar', $code->generateRedirectUri());
$this->assertTrue($code->getSession() instanceof \League\OAuth2\Server\Entity\SessionEntity);
}
public function testSave()
{
$server = M::mock('League\OAuth2\Server\AbstractServer');
$server->shouldReceive('setAuthCodeStorage');
$server->shouldReceive('setSessionStorage');
$authCodeStorage = M::mock('League\OAuth2\Server\Storage\AuthCodeInterface');
$authCodeStorage->shouldReceive('create');
$authCodeStorage->shouldReceive('associateScope');
$authCodeStorage->shouldReceive('setServer');
$authCodeStorage->shouldReceive('getScopes')->andReturn([
(new ScopeEntity($server))->hydrate(['id' => 'foo']),
]);
$server->shouldReceive('getAuthCodeStorage')->andReturn($authCodeStorage);
$sessionStorage = M::mock('League\OAuth2\Server\Storage\SessionInterface');
$sessionStorage->shouldReceive('getByAuthCode')->andReturn(
(new SessionEntity($server))
);
$sessionStorage->shouldReceive('setServer');
$server->shouldReceive('getSessionStorage')->andReturn($sessionStorage);
$server->setAuthCodeStorage($authCodeStorage);
$server->setSessionStorage($sessionStorage);
$entity = new AuthCodeEntity($server);
$this->assertTrue($entity->save() instanceof AuthCodeEntity);
}
public function testExpire()
{
$server = new AuthorizationServer();
$authCodeStorage = M::mock('League\OAuth2\Server\Storage\AuthCodeInterface');
$authCodeStorage->shouldReceive('delete');
$authCodeStorage->shouldReceive('setServer');
$server->setAuthCodeStorage($authCodeStorage);
$entity = new AuthCodeEntity($server);
$this->assertSame($entity->expire(), null);
}
}

View File

@ -1,25 +0,0 @@
<?php
namespace LeagueTests\Entity;
use League\OAuth2\Server\Entity\ClientEntity;
use Mockery as M;
class ClientEntityTest extends \PHPUnit_Framework_TestCase
{
public function testSetGet()
{
$server = M::mock('League\OAuth2\Server\AbstractServer');
$client = (new ClientEntity($server))->hydrate([
'id' => 'foobar',
'secret' => 'barfoo',
'name' => 'Test Client',
'redirectUri' => 'http://foo/bar',
]);
$this->assertEquals('foobar', $client->getId());
$this->assertEquals('barfoo', $client->getSecret());
$this->assertEquals('Test Client', $client->getName());
$this->assertEquals('http://foo/bar', $client->getRedirectUri());
}
}

View File

@ -1,94 +0,0 @@
<?php
namespace LeagueTests\Entity;
use League\OAuth2\Server\Entity\AccessTokenEntity;
use League\OAuth2\Server\Entity\RefreshTokenEntity;
use League\OAuth2\Server\Entity\ScopeEntity;
use League\OAuth2\Server\Entity\SessionEntity;
use Mockery as M;
class RefreshTokenEntityTest extends \PHPUnit_Framework_TestCase
{
public function testSetAccessTokenId()
{
$server = M::mock('League\OAuth2\Server\AbstractServer');
$entity = new RefreshTokenEntity($server);
$entity->setAccessTokenId('foobar');
$reflector = new \ReflectionClass($entity);
$accessTokenProperty = $reflector->getProperty('accessTokenId');
$accessTokenProperty->setAccessible(true);
$this->assertSame($accessTokenProperty->getValue($entity), 'foobar');
}
public function testSetAccessToken()
{
$server = M::mock('League\OAuth2\Server\AbstractServer');
$entity = new RefreshTokenEntity($server);
$entity->setAccessToken((new AccessTokenEntity($server)));
$reflector = new \ReflectionClass($entity);
$accessTokenProperty = $reflector->getProperty('accessTokenEntity');
$accessTokenProperty->setAccessible(true);
$this->assertTrue($accessTokenProperty->getValue($entity) instanceof AccessTokenEntity);
}
public function testSave()
{
$server = M::mock('League\OAuth2\Server\AbstractServer');
$server->shouldReceive('setAccessTokenStorage');
$server->shouldReceive('setRefreshTokenStorage');
$refreshTokenStorage = M::mock('League\OAuth2\Server\Storage\RefreshTokenInterface');
$refreshTokenStorage->shouldReceive('create');
$refreshTokenStorage->shouldReceive('setServer');
$refreshTokenStorage->shouldReceive('associateScope');
$server->shouldReceive('getRefreshTokenStorage')->andReturn($refreshTokenStorage);
$accessTokenStorage = M::mock('League\OAuth2\Server\Storage\AccessTokenInterface');
$accessTokenStorage->shouldReceive('setServer');
$accessTokenStorage->shouldReceive('get')->andReturn(
(new AccessTokenEntity($server))->setId('foobar')
);
$accessTokenStorage->shouldReceive('getScopes')->andReturn([
(new ScopeEntity($server))->hydrate(['id' => 'foo']),
]);
$server->shouldReceive('getAccessTokenStorage')->andReturn($accessTokenStorage);
$sessionStorage = M::mock('League\OAuth2\Server\Storage\SessionInterface');
$sessionStorage->shouldReceive('getByAccessToken')->andReturn(
(new SessionEntity($server))
);
$sessionStorage->shouldReceive('setServer');
$server->shouldReceive('getSessionStorage')->andReturn($sessionStorage);
$server->setAccessTokenStorage($accessTokenStorage);
$server->setRefreshTokenStorage($refreshTokenStorage);
$entity = new RefreshTokenEntity($server);
$this->assertSame(null, $entity->save());
}
public function testExpire()
{
$server = M::mock('League\OAuth2\Server\AbstractServer');
$server->shouldReceive('setRefreshTokenStorage');
$refreshTokenStorage = M::mock('League\OAuth2\Server\Storage\RefreshTokenInterface');
$refreshTokenStorage->shouldReceive('delete');
$refreshTokenStorage->shouldReceive('setServer');
$server->shouldReceive('getRefreshTokenStorage')->andReturn($refreshTokenStorage);
$server->setRefreshTokenStorage($refreshTokenStorage);
$entity = new RefreshTokenEntity($server);
$this->assertSame($entity->expire(), null);
}
}

View File

@ -1,23 +0,0 @@
<?php
namespace LeagueTests\Entity;
use League\OAuth2\Server\Entity\ScopeEntity;
use Mockery as M;
class ScopeEntityTest extends \PHPUnit_Framework_TestCase
{
public function testSetGet()
{
$server = M::mock('League\OAuth2\Server\AbstractServer');
$scope = (new ScopeEntity($server))->hydrate([
'id' => 'foobar',
'description' => 'barfoo',
]);
$this->assertEquals('foobar', $scope->getId());
$this->assertEquals('barfoo', $scope->getDescription());
$this->assertTrue(is_array($scope->jsonSerialize()));
}
}

View File

@ -1,154 +0,0 @@
<?php
namespace LeagueTests\Entity;
use League\OAuth2\Server\AuthorizationServer;
use League\OAuth2\Server\Entity\AccessTokenEntity;
use League\OAuth2\Server\Entity\ClientEntity;
use League\OAuth2\Server\Entity\RefreshTokenEntity;
use League\OAuth2\Server\Entity\ScopeEntity;
use League\OAuth2\Server\Entity\SessionEntity;
use Mockery as M;
class SessionEntityTest extends \PHPUnit_Framework_TestCase
{
public function testSetGet()
{
$emitter = M::mock('League\Event\Emitter');
$emitter->shouldReceive('emit');
$server = M::mock('League\OAuth2\Server\AbstractServer');
$server->shouldReceive('setEventEmitter');
$server->shouldReceive('getEventEmitter')->andReturn($emitter);
$server->setEventEmitter($emitter);
$entity = new SessionEntity($server);
$entity->setId('foobar');
$entity->setOwner('user', 123);
$entity->associateAccessToken((new AccessTokenEntity($server)));
$entity->associateRefreshToken((new RefreshTokenEntity($server)));
$entity->associateClient((new ClientEntity($server)));
$entity->associateScope(
(new ScopeEntity($server))->hydrate(['id' => 'foo'])
);
// $entity->associateAuthCode((new AuthCode($server)));
$this->assertEquals('foobar', $entity->getId());
$this->assertEquals('user', $entity->getOwnerType());
$this->assertEquals(123, $entity->getOwnerId());
$this->assertTrue($entity->getClient() instanceof ClientEntity);
$this->assertTrue($entity->hasScope('foo'));
$reflector = new \ReflectionClass($entity);
$accessTokenProperty = $reflector->getProperty('accessToken');
$accessTokenProperty->setAccessible(true);
$refreshTokenProperty = $reflector->getProperty('refreshToken');
$refreshTokenProperty->setAccessible(true);
$this->assertTrue($accessTokenProperty->getValue($entity) instanceof AccessTokenEntity);
$this->assertTrue($refreshTokenProperty->getValue($entity) instanceof RefreshTokenEntity);
// $this->assertTrue($reader($entity, 'authCode') instanceof AuthCode);
}
public function testFormatScopes()
{
$server = M::mock('League\OAuth2\Server\AbstractServer');
$entity = new SessionEntity($server);
$reflectedEntity = new \ReflectionClass('League\OAuth2\Server\Entity\SessionEntity');
$method = $reflectedEntity->getMethod('formatScopes');
$method->setAccessible(true);
$scopes = [
(new ScopeEntity($server))->hydrate(['id' => 'scope1']),
(new ScopeEntity($server))->hydrate(['id' => 'scope2']),
];
$result = $method->invokeArgs($entity, [$scopes]);
$this->assertTrue(isset($result['scope1']));
$this->assertTrue(isset($result['scope2']));
$this->assertTrue($result['scope1'] instanceof ScopeEntity);
$this->assertTrue($result['scope2'] instanceof ScopeEntity);
}
public function testGetScopes()
{
$server = M::mock('League\OAuth2\Server\AuthorizationServer');
$server->shouldReceive('setAccessTokenStorage');
$server->shouldReceive('setSessionStorage');
$accessTokenStorage = M::mock('League\OAuth2\Server\Storage\AccessTokenInterface');
$accessTokenStorage->shouldReceive('setServer');
$server->setAccessTokenStorage($accessTokenStorage);
$server->shouldReceive('getAccessTokenStorage')->andReturn($accessTokenStorage);
$sessionStorage = M::mock('League\OAuth2\Server\Storage\SessionInterface');
$sessionStorage->shouldReceive('getScopes')->andReturn(
[]
);
$sessionStorage->shouldReceive('setServer');
$server->setSessionStorage($sessionStorage);
$server->shouldReceive('getSessionStorage')->andReturn($sessionStorage);
$entity = new SessionEntity($server);
$this->assertEquals($entity->getScopes(), []);
}
public function testHasScopes()
{
$server = M::mock('League\OAuth2\Server\AuthorizationServer');
$server->shouldReceive('setAccessTokenStorage');
$server->shouldReceive('setSessionStorage');
$accessTokenStorage = M::mock('League\OAuth2\Server\Storage\AccessTokenInterface');
$accessTokenStorage->shouldReceive('setServer');
$server->setAccessTokenStorage($accessTokenStorage);
$server->shouldReceive('getAccessTokenStorage')->andReturn($accessTokenStorage);
$sessionStorage = M::mock('League\OAuth2\Server\Storage\SessionInterface');
$sessionStorage->shouldReceive('getScopes')->andReturn(
[]
);
$sessionStorage->shouldReceive('setServer');
$server->setSessionStorage($sessionStorage);
$server->shouldReceive('getSessionStorage')->andReturn($sessionStorage);
$entity = new SessionEntity($server);
$this->assertFalse($entity->hasScope('foo'));
}
public function testSave()
{
$server = M::mock('League\OAuth2\Server\AuthorizationServer');
$server->shouldReceive('setSessionStorage');
$server->shouldReceive('setClientStorage');
$sessionStorage = M::mock('League\OAuth2\Server\Storage\SessionInterface');
$sessionStorage->shouldReceive('create');
$sessionStorage->shouldReceive('associateScope');
$sessionStorage->shouldReceive('setServer');
$sessionStorage->shouldReceive('getScopes')->andReturn([
(new ScopeEntity($server))->hydrate(['id' => 'foo']),
]);
$server->shouldReceive('getSessionStorage')->andReturn($sessionStorage);
$clientStorage = M::mock('League\OAuth2\Server\Storage\ClientInterface');
$clientStorage->shouldReceive('getBySession')->andReturn(
(new ClientEntity($server))->hydrate(['id' => 'foo'])
);
$clientStorage->shouldReceive('setServer');
$server->shouldReceive('getClientStorage')->andReturn($clientStorage);
$server->setSessionStorage($sessionStorage);
$server->setClientStorage($clientStorage);
$entity = new SessionEntity($server);
$this->assertEquals(null, $entity->save());
}
}

View File

@ -1,34 +0,0 @@
<?php
namespace LeagueTests;
use League\OAuth2\Server\Exception\OAuthException;
class OAuthExceptionTest extends \PHPUnit_Framework_TestCase
{
public function testGetHttpHeaders()
{
$exception = new OAuthException();
$exception->httpStatusCode = 400;
$this->assertSame($exception->getHttpHeaders(), ['HTTP/1.1 400 Bad Request']);
$exception->httpStatusCode = 401;
$this->assertSame($exception->getHttpHeaders(), ['HTTP/1.1 401 Unauthorized']);
$exception->httpStatusCode = 500;
$this->assertSame($exception->getHttpHeaders(), ['HTTP/1.1 500 Internal Server Error']);
$exception->httpStatusCode = 501;
$this->assertSame($exception->getHttpHeaders(), ['HTTP/1.1 501 Not Implemented']);
}
public function testShouldRedirect()
{
$exception = new OAuthException();
$exception->redirectUri = 'http://example.com/';
$exception->errorType = 'Error';
$this->assertTrue($exception->shouldRedirect());
$this->assertEquals('http://example.com/?error=Error&message=An+error+occured', $exception->getRedirectUri());
}
}

View File

@ -1,160 +0,0 @@
<?php
namespace LeagueTests\Grant;
use League\OAuth2\Server\AuthorizationServer;
use League\OAuth2\Server\Entity\ClientEntity;
use League\OAuth2\Server\Entity\ScopeEntity;
use League\OAuth2\Server\Exception\InvalidRequestException;
use League\OAuth2\Server\Grant;
use LeagueTests\Stubs\StubAbstractGrant;
use Mockery as M;
class AbstractGrantTest extends \PHPUnit_Framework_TestCase
{
public function testSetGet()
{
$server = new AuthorizationServer();
$grant = new StubAbstractGrant();
$grant->setIdentifier('foobar');
$grant->setAccessTokenTTL(300);
$grant->setAuthorizationServer($server);
$this->assertEquals('foobar', $grant->getIdentifier());
$this->assertEquals('foobar', $grant->getResponseType());
$this->assertEquals(300, $grant->getAccessTokenTTL());
$this->assertTrue($grant->getAuthorizationServer() instanceof AuthorizationServer);
}
public function testFormatScopes()
{
$server = M::mock('League\OAuth2\Server\AbstractServer');
$grant = new StubAbstractGrant();
$reflectedGrant = new \ReflectionClass('LeagueTests\Stubs\StubAbstractGrant');
$method = $reflectedGrant->getMethod('formatScopes');
$method->setAccessible(true);
$scopes = [
(new ScopeEntity($server))->hydrate(['id' => 'scope1', 'description' => 'foo']),
(new ScopeEntity($server))->hydrate(['id' => 'scope2', 'description' => 'bar']),
];
$result = $method->invokeArgs($grant, [$scopes]);
$this->assertTrue(isset($result['scope1']));
$this->assertTrue(isset($result['scope2']));
$this->assertTrue($result['scope1'] instanceof ScopeEntity);
$this->assertTrue($result['scope2'] instanceof ScopeEntity);
}
public function testValidateScopes()
{
$server = new AuthorizationServer();
$scopeStorage = M::mock('League\OAuth2\Server\Storage\ScopeInterface');
$scopeStorage->shouldReceive('setServer');
$scopeStorage->shouldReceive('get')->andReturn(
(new ScopeEntity($server))->hydrate(['id' => 'foo'])
);
$server->setScopeStorage($scopeStorage);
$grant = new StubAbstractGrant();
$grant->setAuthorizationServer($server);
$client = (new ClientEntity($server))->hydrate(['id' => 'testapp']);
$this->assertEquals(
[
'foo' => (new ScopeEntity($server))->hydrate(['id' => 'foo']),
],
$grant->validateScopes('foo', $client)
);
}
public function testValidateScopesMissingScope()
{
$this->setExpectedException('League\OAuth2\Server\Exception\InvalidRequestException');
$scopeStorage = M::mock('League\OAuth2\Server\Storage\ScopeInterface');
$scopeStorage->shouldReceive('setServer');
$server = new AuthorizationServer();
$server->requireScopeParam(true);
$server->setScopeStorage($scopeStorage);
$grant = new StubAbstractGrant();
$grant->setAuthorizationServer($server);
$client = (new ClientEntity($server))->hydrate(['id' => 'testapp']);
$grant->validateScopes(null, $client);
}
public function testValidateScopesInvalidScope()
{
$this->setExpectedException('League\OAuth2\Server\Exception\InvalidScopeException');
$scopeStorage = M::mock('League\OAuth2\Server\Storage\ScopeInterface');
$scopeStorage->shouldReceive('setServer');
$scopeStorage->shouldReceive('get')->andReturn(null);
$server = new AuthorizationServer();
$server->setScopeStorage($scopeStorage);
$grant = new StubAbstractGrant();
$grant->setAuthorizationServer($server);
$client = (new ClientEntity($server))->hydrate(['id' => 'testapp']);
$grant->validateScopes('blah', $client);
}
public function testValidateScopesDefaultScope()
{
$server = new AuthorizationServer();
$scopeStorage = M::mock('League\OAuth2\Server\Storage\ScopeInterface');
$scopeStorage->shouldReceive('setServer');
$scopeStorage->shouldReceive('get')->andReturn(
(new ScopeEntity($server))->hydrate(['id' => 'foo'])
);
$server->setScopeStorage($scopeStorage);
$server->requireScopeParam(true);
$server->setScopeStorage($scopeStorage);
$server->setDefaultScope('foo');
$grant = new StubAbstractGrant();
$grant->setAuthorizationServer($server);
$client = (new ClientEntity($server))->hydrate(['id' => 'testapp']);
$grant->validateScopes(null, $client);
}
public function testValidateScopesDefaultScopeArray()
{
$server = new AuthorizationServer();
$scopeStorage = M::mock('League\OAuth2\Server\Storage\ScopeInterface');
$scopeStorage->shouldReceive('setServer');
$scopeStorage->shouldReceive('get')->andReturn(
(new ScopeEntity($server))->hydrate(['id' => 'foo'])
);
$server->setScopeStorage($scopeStorage);
$server->requireScopeParam(true);
$server->setScopeStorage($scopeStorage);
$server->setDefaultScope(['foo', 'bar']);
$grant = new StubAbstractGrant();
$grant->setAuthorizationServer($server);
$client = (new ClientEntity($server))->hydrate(['id' => 'testapp']);
$grant->validateScopes(null, $client);
}
}

View File

@ -1,696 +0,0 @@
<?php
namespace LeagueTests\Grant;
use League\OAuth2\Server\AuthorizationServer;
use League\OAuth2\Server\Entity\AuthCodeEntity;
use League\OAuth2\Server\Entity\ClientEntity;
use League\OAuth2\Server\Entity\ScopeEntity;
use League\OAuth2\Server\Entity\SessionEntity;
use League\OAuth2\Server\Exception\InvalidRequestException;
use League\OAuth2\Server\Grant\AuthCodeGrant;
use League\OAuth2\Server\Grant\RefreshTokenGrant;
use Mockery as M;
class AuthCodeGrantTest extends \PHPUnit_Framework_TestCase
{
public function testSetAuthTokenTTL()
{
$grant = new AuthCodeGrant();
$grant->setAuthTokenTTL(100);
$class = new \ReflectionClass($grant);
$property = $class->getProperty('authTokenTTL');
$property->setAccessible(true);
$this->assertEquals(100, $property->getValue($grant));
}
public function testCheckAuthoriseParamsMissingClientId()
{
$this->setExpectedException('League\OAuth2\Server\Exception\InvalidRequestException');
$_GET = [];
$server = new AuthorizationServer();
$grant = new AuthCodeGrant();
$server->addGrantType($grant);
$grant->checkAuthorizeParams();
}
public function testCheckAuthoriseParamsMissingRedirectUri()
{
$this->setExpectedException('League\OAuth2\Server\Exception\InvalidRequestException');
$server = new AuthorizationServer();
$_GET = [
'client_id' => 'testapp',
];
$grant = new AuthCodeGrant();
$server->addGrantType($grant);
$grant->checkAuthorizeParams();
}
public function testCheckAuthoriseParamsInvalidClient()
{
$this->setExpectedException('League\OAuth2\Server\Exception\InvalidClientException');
$_GET = [
'client_id' => 'testapp',
'redirect_uri' => 'http://foo/bar',
'response_type' => 'code',
];
$server = new AuthorizationServer();
$grant = new AuthCodeGrant();
$clientStorage = M::mock('League\OAuth2\Server\Storage\ClientInterface');
$clientStorage->shouldReceive('setServer');
$clientStorage->shouldReceive('get')->andReturn(null);
$server->setClientStorage($clientStorage);
$server->addGrantType($grant);
$grant->checkAuthorizeParams();
}
public function testCheckAuthoriseParamsMissingStateParam()
{
$this->setExpectedException('League\OAuth2\Server\Exception\InvalidRequestException');
$_GET = [
'client_id' => 'testapp',
'redirect_uri' => 'http://foo/bar',
];
$server = new AuthorizationServer();
$clientStorage = M::mock('League\OAuth2\Server\Storage\ClientInterface');
$clientStorage->shouldReceive('setServer');
$clientStorage->shouldReceive('get')->andReturn(
(new ClientEntity($server))->hydrate(['id' => 'testapp'])
);
$server->setClientStorage($clientStorage);
$grant = new AuthCodeGrant();
$server->requireStateParam(true);
$server->addGrantType($grant);
$grant->checkAuthorizeParams();
}
public function testCheckAuthoriseParamsMissingResponseType()
{
$this->setExpectedException('League\OAuth2\Server\Exception\InvalidRequestException');
$_GET = [
'client_id' => 'testapp',
'redirect_uri' => 'http://foo/bar',
];
$server = new AuthorizationServer();
$clientStorage = M::mock('League\OAuth2\Server\Storage\ClientInterface');
$clientStorage->shouldReceive('setServer');
$clientStorage->shouldReceive('get')->andReturn(
(new ClientEntity($server))->hydrate(['id' => 'testapp'])
);
$server->setClientStorage($clientStorage);
$grant = new AuthCodeGrant();
$server->addGrantType($grant);
$grant->checkAuthorizeParams();
}
public function testCheckAuthoriseParamsInvalidResponseType()
{
$this->setExpectedException('League\OAuth2\Server\Exception\UnsupportedResponseTypeException');
$_GET = [
'client_id' => 'testapp',
'redirect_uri' => 'http://foo/bar',
'response_type' => 'foobar',
];
$server = new AuthorizationServer();
$clientStorage = M::mock('League\OAuth2\Server\Storage\ClientInterface');
$clientStorage->shouldReceive('setServer');
$clientStorage->shouldReceive('get')->andReturn(
(new ClientEntity($server))->hydrate(['id' => 'testapp'])
);
$server->setClientStorage($clientStorage);
$grant = new AuthCodeGrant();
$server->addGrantType($grant);
$grant->checkAuthorizeParams();
}
public function testCheckAuthoriseParamsInvalidScope()
{
$this->setExpectedException('League\OAuth2\Server\Exception\InvalidScopeException');
$_GET = [
'response_type' => 'code',
'client_id' => 'testapp',
'redirect_uri' => 'http://foo/bar',
'scope' => 'foo',
];
$server = new AuthorizationServer();
$grant = new AuthCodeGrant();
$clientStorage = M::mock('League\OAuth2\Server\Storage\ClientInterface');
$clientStorage->shouldReceive('setServer');
$clientStorage->shouldReceive('get')->andReturn(
(new ClientEntity($server))->hydrate(['id' => 'testapp'])
);
$sessionStorage = M::mock('League\OAuth2\Server\Storage\SessionInterface');
$sessionStorage->shouldReceive('setServer');
$sessionStorage->shouldReceive('create');
$sessionStorage->shouldReceive('getScopes')->andReturn([]);
$accessTokenStorage = M::mock('League\OAuth2\Server\Storage\AccessTokenInterface');
$accessTokenStorage->shouldReceive('setServer');
$accessTokenStorage->shouldReceive('create');
$accessTokenStorage->shouldReceive('getScopes')->andReturn([]);
$scopeStorage = M::mock('League\OAuth2\Server\Storage\ScopeInterface');
$scopeStorage->shouldReceive('setServer');
$scopeStorage->shouldReceive('get')->andReturn(null);
$server->setClientStorage($clientStorage);
$server->setScopeStorage($scopeStorage);
$server->setSessionStorage($sessionStorage);
$server->setAccessTokenStorage($accessTokenStorage);
$server->addGrantType($grant);
$grant->checkAuthorizeParams();
}
public function testCheckAuthoriseParams()
{
$_GET = [
'response_type' => 'code',
'client_id' => 'testapp',
'redirect_uri' => 'http://foo/bar',
'scope' => 'foo',
];
$server = new AuthorizationServer();
$grant = new AuthCodeGrant();
$clientStorage = M::mock('League\OAuth2\Server\Storage\ClientInterface');
$clientStorage->shouldReceive('setServer');
$clientStorage->shouldReceive('get')->andReturn(
(new ClientEntity($server))->hydrate(['id' => 'testapp'])
);
$sessionStorage = M::mock('League\OAuth2\Server\Storage\SessionInterface');
$sessionStorage->shouldReceive('setServer');
$sessionStorage->shouldReceive('create')->andreturn(123);
$sessionStorage->shouldReceive('getScopes')->shouldReceive('getScopes')->andReturn([
(new ScopeEntity($server))->hydrate(['id' => 'foo']),
]);
$sessionStorage->shouldReceive('associateScope');
$accessTokenStorage = M::mock('League\OAuth2\Server\Storage\AccessTokenInterface');
$accessTokenStorage->shouldReceive('setServer');
$accessTokenStorage->shouldReceive('create');
$accessTokenStorage->shouldReceive('getScopes')->andReturn([
(new ScopeEntity($server))->hydrate(['id' => 'foo']),
]);
$accessTokenStorage->shouldReceive('associateScope');
$scopeStorage = M::mock('League\OAuth2\Server\Storage\ScopeInterface');
$scopeStorage->shouldReceive('setServer');
$scopeStorage->shouldReceive('get')->andReturn(
(new ScopeEntity($server))->hydrate(['id' => 'foo'])
);
$server->setClientStorage($clientStorage);
$server->setScopeStorage($scopeStorage);
$server->setSessionStorage($sessionStorage);
$server->setAccessTokenStorage($accessTokenStorage);
$server->addGrantType($grant);
$result = $grant->checkAuthorizeParams();
$this->assertTrue($result['client'] instanceof ClientEntity);
$this->assertTrue($result['redirect_uri'] === $_GET['redirect_uri']);
$this->assertTrue($result['state'] === null);
$this->assertTrue($result['response_type'] === 'code');
$this->assertTrue($result['scopes']['foo'] instanceof ScopeEntity);
}
public function testNewAuthoriseRequest()
{
$server = new AuthorizationServer();
$client = (new ClientEntity($server))->hydrate(['id' => 'testapp']);
$scope = (new ScopeEntity($server))->hydrate(['id' => 'foo']);
$grant = new AuthCodeGrant();
$server->addGrantType($grant);
$sessionStorage = M::mock('League\OAuth2\Server\Storage\SessionInterface');
$sessionStorage->shouldReceive('setServer');
$sessionStorage->shouldReceive('create')->andreturn(123);
$sessionStorage->shouldReceive('getScopes')->shouldReceive('getScopes')->andReturn([$scope]);
$sessionStorage->shouldReceive('associateScope');
$server->setSessionStorage($sessionStorage);
$authCodeStorage = M::mock('League\OAuth2\Server\Storage\AuthCodeInterface');
$authCodeStorage->shouldReceive('setServer');
$authCodeStorage->shouldReceive('get');
$authCodeStorage->shouldReceive('create');
$authCodeStorage->shouldReceive('associateScope');
$server->setAuthCodeStorage($authCodeStorage);
$grant->newAuthorizeRequest('user', 123, [
'client' => $client,
'redirect_uri' => 'http://foo/bar',
'scopes' => [$scope],
'state' => 'foobar'
]);
}
public function testCompleteFlowMissingClientId()
{
$this->setExpectedException('League\OAuth2\Server\Exception\InvalidRequestException');
$_POST['grant_type'] = 'authorization_code';
$server = new AuthorizationServer();
$grant = new AuthCodeGrant();
$server->addGrantType($grant);
$server->issueAccessToken();
}
public function testCompleteFlowMissingClientSecret()
{
$this->setExpectedException('League\OAuth2\Server\Exception\InvalidRequestException');
$_POST = [
'grant_type' => 'authorization_code',
'client_id' => 'testapp',
];
$server = new AuthorizationServer();
$grant = new AuthCodeGrant();
$server->addGrantType($grant);
$server->issueAccessToken();
}
public function testCompleteFlowMissingRedirectUri()
{
$this->setExpectedException('League\OAuth2\Server\Exception\InvalidRequestException');
$_POST = [
'grant_type' => 'authorization_code',
'client_id' => 'testapp',
'client_secret' => 'foobar',
];
$server = new AuthorizationServer();
$grant = new AuthCodeGrant();
$server->addGrantType($grant);
$server->issueAccessToken();
}
public function testCompleteFlowInvalidClient()
{
$this->setExpectedException('League\OAuth2\Server\Exception\InvalidClientException');
$_POST = [
'grant_type' => 'authorization_code',
'client_id' => 'testapp',
'client_secret' => 'foobar',
'redirect_uri' => 'http://foo/bar',
];
$server = new AuthorizationServer();
$grant = new AuthCodeGrant();
$clientStorage = M::mock('League\OAuth2\Server\Storage\ClientInterface');
$clientStorage->shouldReceive('setServer');
$clientStorage->shouldReceive('get')->andReturn(null);
$server->setClientStorage($clientStorage);
$server->addGrantType($grant);
$server->issueAccessToken();
}
public function testCompleteFlowMissingCode()
{
$this->setExpectedException('League\OAuth2\Server\Exception\InvalidRequestException');
$_POST = [
'grant_type' => 'authorization_code',
'client_id' => 'testapp',
'client_secret' => 'foobar',
'redirect_uri' => 'http://foo/bar',
];
$server = new AuthorizationServer();
$grant = new AuthCodeGrant();
$clientStorage = M::mock('League\OAuth2\Server\Storage\ClientInterface');
$clientStorage->shouldReceive('setServer');
$clientStorage->shouldReceive('get')->andReturn(
(new ClientEntity($server))->hydrate(['id' => 'testapp'])
);
$sessionStorage = M::mock('League\OAuth2\Server\Storage\SessionInterface');
$sessionStorage->shouldReceive('setServer');
$sessionStorage->shouldReceive('create');
$sessionStorage->shouldReceive('getScopes')->andReturn([]);
$accessTokenStorage = M::mock('League\OAuth2\Server\Storage\AccessTokenInterface');
$accessTokenStorage->shouldReceive('setServer');
$accessTokenStorage->shouldReceive('create');
$accessTokenStorage->shouldReceive('getScopes')->andReturn([]);
$scopeStorage = M::mock('League\OAuth2\Server\Storage\ScopeInterface');
$scopeStorage->shouldReceive('setServer');
$scopeStorage->shouldReceive('get')->andReturn(null);
$authCodeStorage = M::mock('League\OAuth2\Server\Storage\AuthCodeInterface');
$authCodeStorage->shouldReceive('setServer');
$authCodeStorage->shouldReceive('get');
$server->setClientStorage($clientStorage);
$server->setScopeStorage($scopeStorage);
$server->setSessionStorage($sessionStorage);
$server->setAccessTokenStorage($accessTokenStorage);
$server->setAuthCodeStorage($authCodeStorage);
$server->addGrantType($grant);
$server->issueAccessToken();
}
public function testCompleteFlowInvalidCode()
{
$this->setExpectedException('League\OAuth2\Server\Exception\InvalidRequestException');
$_POST = [
'grant_type' => 'authorization_code',
'client_id' => 'testapp',
'client_secret' => 'foobar',
'redirect_uri' => 'http://foo/bar',
'code' => 'foobar',
];
$server = new AuthorizationServer();
$grant = new AuthCodeGrant();
$clientStorage = M::mock('League\OAuth2\Server\Storage\ClientInterface');
$clientStorage->shouldReceive('setServer');
$clientStorage->shouldReceive('get')->andReturn(
(new ClientEntity($server))->hydrate(['id' => 'testapp'])
);
$sessionStorage = M::mock('League\OAuth2\Server\Storage\SessionInterface');
$sessionStorage->shouldReceive('setServer');
$sessionStorage->shouldReceive('create');
$sessionStorage->shouldReceive('getScopes')->andReturn([]);
$accessTokenStorage = M::mock('League\OAuth2\Server\Storage\AccessTokenInterface');
$accessTokenStorage->shouldReceive('setServer');
$accessTokenStorage->shouldReceive('create');
$accessTokenStorage->shouldReceive('getScopes')->andReturn([]);
$scopeStorage = M::mock('League\OAuth2\Server\Storage\ScopeInterface');
$scopeStorage->shouldReceive('setServer');
$scopeStorage->shouldReceive('get')->andReturn(null);
$authCodeStorage = M::mock('League\OAuth2\Server\Storage\AuthCodeInterface');
$authCodeStorage->shouldReceive('setServer');
$authCodeStorage->shouldReceive('get');
$server->setClientStorage($clientStorage);
$server->setScopeStorage($scopeStorage);
$server->setSessionStorage($sessionStorage);
$server->setAccessTokenStorage($accessTokenStorage);
$server->setAuthCodeStorage($authCodeStorage);
$server->addGrantType($grant);
$server->issueAccessToken();
}
public function testCompleteFlowExpiredCode()
{
$this->setExpectedException('League\OAuth2\Server\Exception\InvalidRequestException');
$_POST = [
'grant_type' => 'authorization_code',
'client_id' => 'testapp',
'client_secret' => 'foobar',
'redirect_uri' => 'http://foo/bar',
'code' => 'foobar',
];
$server = new AuthorizationServer();
$grant = new AuthCodeGrant();
$clientStorage = M::mock('League\OAuth2\Server\Storage\ClientInterface');
$clientStorage->shouldReceive('setServer');
$clientStorage->shouldReceive('get')->andReturn(
(new ClientEntity($server))->hydrate(['id' => 'testapp'])
);
$sessionStorage = M::mock('League\OAuth2\Server\Storage\SessionInterface');
$sessionStorage->shouldReceive('setServer');
$sessionStorage->shouldReceive('create');
$sessionStorage->shouldReceive('getScopes')->andReturn([]);
$accessTokenStorage = M::mock('League\OAuth2\Server\Storage\AccessTokenInterface');
$accessTokenStorage->shouldReceive('setServer');
$accessTokenStorage->shouldReceive('create');
$accessTokenStorage->shouldReceive('getScopes')->andReturn([]);
$scopeStorage = M::mock('League\OAuth2\Server\Storage\ScopeInterface');
$scopeStorage->shouldReceive('setServer');
$scopeStorage->shouldReceive('get')->andReturn(null);
$authCodeStorage = M::mock('League\OAuth2\Server\Storage\AuthCodeInterface');
$authCodeStorage->shouldReceive('setServer');
$authCodeStorage->shouldReceive('get')->andReturn(
(new AuthCodeEntity($server))->setId('foobar')->setExpireTime(time() - 300)->setRedirectUri('http://foo/bar')
);
$server->setClientStorage($clientStorage);
$server->setScopeStorage($scopeStorage);
$server->setSessionStorage($sessionStorage);
$server->setAccessTokenStorage($accessTokenStorage);
$server->setAuthCodeStorage($authCodeStorage);
$server->addGrantType($grant);
$server->issueAccessToken();
}
public function testCompleteFlowRedirectUriMismatch()
{
$this->setExpectedException('League\OAuth2\Server\Exception\InvalidRequestException');
$_POST = [
'grant_type' => 'authorization_code',
'client_id' => 'testapp',
'client_secret' => 'foobar',
'redirect_uri' => 'http://foo/bar',
'code' => 'foobar',
];
$server = new AuthorizationServer();
$grant = new AuthCodeGrant();
$clientStorage = M::mock('League\OAuth2\Server\Storage\ClientInterface');
$clientStorage->shouldReceive('setServer');
$clientStorage->shouldReceive('get')->andReturn(
(new ClientEntity($server))->hydrate(['id' => 'testapp'])
);
$sessionStorage = M::mock('League\OAuth2\Server\Storage\SessionInterface');
$sessionStorage->shouldReceive('setServer');
$sessionStorage->shouldReceive('create');
$sessionStorage->shouldReceive('getScopes')->andReturn([]);
$accessTokenStorage = M::mock('League\OAuth2\Server\Storage\AccessTokenInterface');
$accessTokenStorage->shouldReceive('setServer');
$accessTokenStorage->shouldReceive('create');
$accessTokenStorage->shouldReceive('getScopes')->andReturn([]);
$scopeStorage = M::mock('League\OAuth2\Server\Storage\ScopeInterface');
$scopeStorage->shouldReceive('setServer');
$scopeStorage->shouldReceive('get')->andReturn(null);
$authCodeStorage = M::mock('League\OAuth2\Server\Storage\AuthCodeInterface');
$authCodeStorage->shouldReceive('setServer');
$authCodeStorage->shouldReceive('get')->andReturn(
(new AuthCodeEntity($server))->setId('foobar')->setExpireTime(time() + 300)->setRedirectUri('http://fail/face')
);
$server->setClientStorage($clientStorage);
$server->setScopeStorage($scopeStorage);
$server->setSessionStorage($sessionStorage);
$server->setAccessTokenStorage($accessTokenStorage);
$server->setAuthCodeStorage($authCodeStorage);
$server->addGrantType($grant);
$server->issueAccessToken();
}
public function testCompleteFlow()
{
$_POST = [
'grant_type' => 'authorization_code',
'client_id' => 'testapp',
'client_secret' => 'foobar',
'redirect_uri' => 'http://foo/bar',
'code' => 'foo',
];
$server = new AuthorizationServer();
$grant = new AuthCodeGrant();
$clientStorage = M::mock('League\OAuth2\Server\Storage\ClientInterface');
$clientStorage->shouldReceive('setServer');
$clientStorage->shouldReceive('getBySession')->andReturn(
(new ClientEntity($server))->hydrate(['id' => 'testapp'])
);
$clientStorage->shouldReceive('get')->andReturn(
(new ClientEntity($server))->hydrate(['id' => 'testapp'])
);
$sessionStorage = M::mock('League\OAuth2\Server\Storage\SessionInterface');
$sessionStorage->shouldReceive('setServer');
$sessionStorage->shouldReceive('create')->andreturn(123);
$sessionStorage->shouldReceive('associateScope');
$sessionStorage->shouldReceive('getByAuthCode')->andReturn(
(new SessionEntity($server))->setId('foobar')
);
$sessionStorage->shouldReceive('getByAccessToken')->andReturn(
(new SessionEntity($server))->setId('foobar')
);
$sessionStorage->shouldReceive('getScopes')->andReturn([
(new ScopeEntity($server))->hydrate(['id' => 'foo']),
]);
$accessTokenStorage = M::mock('League\OAuth2\Server\Storage\AccessTokenInterface');
$accessTokenStorage->shouldReceive('setServer');
$accessTokenStorage->shouldReceive('create');
$accessTokenStorage->shouldReceive('associateScope');
$accessTokenStorage->shouldReceive('getScopes')->andReturn([
(new ScopeEntity($server))->hydrate(['id' => 'foo']),
]);
$scopeStorage = M::mock('League\OAuth2\Server\Storage\ScopeInterface');
$scopeStorage->shouldReceive('setServer');
$scopeStorage->shouldReceive('get')->andReturn(
(new ScopeEntity($server))->hydrate(['id' => 'foo'])
);
$authCodeStorage = M::mock('League\OAuth2\Server\Storage\AuthCodeInterface');
$authCodeStorage->shouldReceive('setServer');
$authCodeStorage->shouldReceive('delete');
$authCodeStorage->shouldReceive('get')->andReturn(
(new AuthCodeEntity($server))->setId('foobar')->setRedirectUri('http://foo/bar')->setExpireTime(time() + 300)
);
$authCodeStorage->shouldReceive('getScopes')->andReturn([
(new ScopeEntity($server))->hydrate(['id' => 'foo']),
]);
$server->setClientStorage($clientStorage);
$server->setScopeStorage($scopeStorage);
$server->setSessionStorage($sessionStorage);
$server->setAccessTokenStorage($accessTokenStorage);
$server->setAuthCodeStorage($authCodeStorage);
$server->addGrantType($grant);
$server->issueAccessToken();
}
public function testCompleteFlowWithRefreshToken()
{
$_POST = [
'grant_type' => 'authorization_code',
'client_id' => 'testapp',
'client_secret' => 'foobar',
'redirect_uri' => 'http://foo/bar',
'code' => 'foo',
];
$server = new AuthorizationServer();
$grant = new AuthCodeGrant();
$rtgrant = new RefreshTokenGrant();
$clientStorage = M::mock('League\OAuth2\Server\Storage\ClientInterface');
$clientStorage->shouldReceive('setServer');
$clientStorage->shouldReceive('getBySession')->andReturn(
(new ClientEntity($server))->hydrate(['id' => 'testapp'])
);
$clientStorage->shouldReceive('get')->andReturn(
(new ClientEntity($server))->hydrate(['id' => 'testapp'])
);
$sessionStorage = M::mock('League\OAuth2\Server\Storage\SessionInterface');
$sessionStorage->shouldReceive('setServer');
$sessionStorage->shouldReceive('create')->andreturn(123);
$sessionStorage->shouldReceive('associateScope');
$sessionStorage->shouldReceive('getByAuthCode')->andReturn(
(new SessionEntity($server))->setId('foobar')
);
$sessionStorage->shouldReceive('getByAccessToken')->andReturn(
(new SessionEntity($server))->setId('foobar')
);
$sessionStorage->shouldReceive('getScopes')->andReturn([
(new ScopeEntity($server))->hydrate(['id' => 'foo']),
]);
$accessTokenStorage = M::mock('League\OAuth2\Server\Storage\AccessTokenInterface');
$accessTokenStorage->shouldReceive('setServer');
$accessTokenStorage->shouldReceive('create');
$accessTokenStorage->shouldReceive('associateScope');
$accessTokenStorage->shouldReceive('getScopes')->andReturn([
(new ScopeEntity($server))->hydrate(['id' => 'foo']),
]);
$scopeStorage = M::mock('League\OAuth2\Server\Storage\ScopeInterface');
$scopeStorage->shouldReceive('setServer');
$scopeStorage->shouldReceive('get')->andReturn(
(new ScopeEntity($server))->hydrate(['id' => 'foo'])
);
$authCodeStorage = M::mock('League\OAuth2\Server\Storage\AuthCodeInterface');
$authCodeStorage->shouldReceive('setServer');
$authCodeStorage->shouldReceive('delete');
$authCodeStorage->shouldReceive('get')->andReturn(
(new AuthCodeEntity($server))->setId('foobar')->setRedirectUri('http://foo/bar')->setExpireTime(time() + 300)
);
$authCodeStorage->shouldReceive('getScopes')->andReturn([
(new ScopeEntity($server))->hydrate(['id' => 'foo']),
]);
$refreshTokenStorage = M::mock('League\OAuth2\Server\Storage\RefreshTokenInterface');
$refreshTokenStorage->shouldReceive('setServer');
$refreshTokenStorage->shouldReceive('create');
$refreshTokenStorage->shouldReceive('associateScope');
$server->setClientStorage($clientStorage);
$server->setScopeStorage($scopeStorage);
$server->setSessionStorage($sessionStorage);
$server->setAccessTokenStorage($accessTokenStorage);
$server->setAuthCodeStorage($authCodeStorage);
$server->setRefreshTokenStorage($refreshTokenStorage);
$server->addGrantType($grant);
$server->addGrantType($rtgrant);
$server->issueAccessToken();
}
}

View File

@ -1,251 +0,0 @@
<?php
namespace LeagueTests\Grant;
use League\OAuth2\Server\AuthorizationServer;
use League\OAuth2\Server\Entity\ClientEntity;
use League\OAuth2\Server\Entity\ScopeEntity;
use League\OAuth2\Server\Entity\SessionEntity;
use League\OAuth2\Server\Grant\ClientCredentialsGrant;
use Mockery as M;
class ClientCredentialsGrantTest extends \PHPUnit_Framework_TestCase
{
public function testCompleteFlowMissingClientId()
{
$this->setExpectedException('League\OAuth2\Server\Exception\InvalidRequestException');
$_POST['grant_type'] = 'client_credentials';
$server = new AuthorizationServer();
$grant = new ClientCredentialsGrant();
$server->addGrantType($grant);
$server->issueAccessToken();
}
public function testCompleteFlowMissingClientSecret()
{
$this->setExpectedException('League\OAuth2\Server\Exception\InvalidRequestException');
$_POST = [
'grant_type' => 'client_credentials',
'client_id' => 'testapp',
];
$server = new AuthorizationServer();
$grant = new ClientCredentialsGrant();
$server->addGrantType($grant);
$server->issueAccessToken();
}
public function testCompleteFlowInvalidClient()
{
$this->setExpectedException('League\OAuth2\Server\Exception\InvalidClientException');
$_POST = [
'grant_type' => 'client_credentials',
'client_id' => 'testapp',
'client_secret' => 'foobar',
];
$server = new AuthorizationServer();
$grant = new ClientCredentialsGrant();
$clientStorage = M::mock('League\OAuth2\Server\Storage\ClientInterface');
$clientStorage->shouldReceive('setServer');
$clientStorage->shouldReceive('get')->andReturn(null);
$server->setClientStorage($clientStorage);
$server->addGrantType($grant);
$server->issueAccessToken();
}
public function testCompleteFlowInvalidScope()
{
$this->setExpectedException('League\OAuth2\Server\Exception\InvalidScopeException');
$_POST = [
'grant_type' => 'client_credentials',
'client_id' => 'testapp',
'client_secret' => 'foobar',
'scope' => 'foo',
];
$server = new AuthorizationServer();
$grant = new ClientCredentialsGrant();
$clientStorage = M::mock('League\OAuth2\Server\Storage\ClientInterface');
$clientStorage->shouldReceive('setServer');
$clientStorage->shouldReceive('get')->andReturn(
(new ClientEntity($server))->hydrate(['id' => 'testapp'])
);
$sessionStorage = M::mock('League\OAuth2\Server\Storage\SessionInterface');
$sessionStorage->shouldReceive('setServer');
$sessionStorage->shouldReceive('create');
$sessionStorage->shouldReceive('getScopes')->andReturn([]);
$accessTokenStorage = M::mock('League\OAuth2\Server\Storage\AccessTokenInterface');
$accessTokenStorage->shouldReceive('setServer');
$accessTokenStorage->shouldReceive('create');
$accessTokenStorage->shouldReceive('getScopes')->andReturn([]);
$scopeStorage = M::mock('League\OAuth2\Server\Storage\ScopeInterface');
$scopeStorage->shouldReceive('setServer');
$scopeStorage->shouldReceive('get')->andReturn(null);
$server->setClientStorage($clientStorage);
$server->setScopeStorage($scopeStorage);
$server->setSessionStorage($sessionStorage);
$server->setAccessTokenStorage($accessTokenStorage);
$server->addGrantType($grant);
$server->issueAccessToken();
}
public function testCompleteFlowNoScopes()
{
$_POST = [
'grant_type' => 'client_credentials',
'client_id' => 'testapp',
'client_secret' => 'foobar',
];
$server = new AuthorizationServer();
$grant = new ClientCredentialsGrant();
$clientStorage = M::mock('League\OAuth2\Server\Storage\ClientInterface');
$clientStorage->shouldReceive('setServer');
$clientStorage->shouldReceive('get')->andReturn(
(new ClientEntity($server))->hydrate(['id' => 'testapp'])
);
$sessionStorage = M::mock('League\OAuth2\Server\Storage\SessionInterface');
$sessionStorage->shouldReceive('setServer');
$sessionStorage->shouldReceive('create')->andreturn(123);
$sessionStorage->shouldReceive('getScopes')->shouldReceive('getScopes')->andReturn([]);
$sessionStorage->shouldReceive('getByAccessToken')->andReturn(
(new SessionEntity($server))->setId('foobar')
);
$sessionStorage->shouldReceive('associateScope');
$accessTokenStorage = M::mock('League\OAuth2\Server\Storage\AccessTokenInterface');
$accessTokenStorage->shouldReceive('setServer');
$accessTokenStorage->shouldReceive('create');
$accessTokenStorage->shouldReceive('getScopes')->andReturn([]);
$accessTokenStorage->shouldReceive('associateScope');
$scopeStorage = M::mock('League\OAuth2\Server\Storage\ScopeInterface');
$scopeStorage->shouldReceive('setServer');
// $scopeStorage->shouldReceive('get')->andReturn(
// // (new ScopeEntity($server))->hydrate(['id' => 'foo'])
// );
$server->setClientStorage($clientStorage);
$server->setScopeStorage($scopeStorage);
$server->setSessionStorage($sessionStorage);
$server->setAccessTokenStorage($accessTokenStorage);
$server->addGrantType($grant);
$server->issueAccessToken();
}
public function testCompleteFlow()
{
$_POST = [
'grant_type' => 'client_credentials',
'client_id' => 'testapp',
'client_secret' => 'foobar',
'scope' => 'foo',
];
$server = new AuthorizationServer();
$grant = new ClientCredentialsGrant();
$clientStorage = M::mock('League\OAuth2\Server\Storage\ClientInterface');
$clientStorage->shouldReceive('setServer');
$clientStorage->shouldReceive('get')->andReturn(
(new ClientEntity($server))->hydrate(['id' => 'testapp'])
);
$sessionStorage = M::mock('League\OAuth2\Server\Storage\SessionInterface');
$sessionStorage->shouldReceive('setServer');
$sessionStorage->shouldReceive('create')->andreturn(123);
$sessionStorage->shouldReceive('getScopes')->shouldReceive('getScopes')->andReturn([
(new ScopeEntity($server))->hydrate(['id' => 'foo']),
]);
$sessionStorage->shouldReceive('getByAccessToken')->andReturn(
(new SessionEntity($server))->setId('foobar')
);
$sessionStorage->shouldReceive('associateScope');
$accessTokenStorage = M::mock('League\OAuth2\Server\Storage\AccessTokenInterface');
$accessTokenStorage->shouldReceive('setServer');
$accessTokenStorage->shouldReceive('create');
$accessTokenStorage->shouldReceive('getScopes')->andReturn([
(new ScopeEntity($server))->hydrate(['id' => 'foo']),
]);
$accessTokenStorage->shouldReceive('associateScope');
$scopeStorage = M::mock('League\OAuth2\Server\Storage\ScopeInterface');
$scopeStorage->shouldReceive('setServer');
$scopeStorage->shouldReceive('get')->andReturn(
(new ScopeEntity($server))->hydrate(['id' => 'foo'])
);
$server->setClientStorage($clientStorage);
$server->setScopeStorage($scopeStorage);
$server->setSessionStorage($sessionStorage);
$server->setAccessTokenStorage($accessTokenStorage);
$server->addGrantType($grant);
$server->issueAccessToken();
}
public function testClientNotAuthorizedToUseGrant()
{
$this->setExpectedException('\League\OAuth2\Server\Exception\UnauthorizedClientException');
$_POST = [
'grant_type' => 'client_credentials',
'client_id' => 'testapp',
'client_secret' => 'foobar',
'scope' => 'foo',
];
$server = new AuthorizationServer();
$grant = new ClientCredentialsGrant();
$clientStorage = M::mock('League\OAuth2\Server\Storage\ClientInterface');
$clientStorage->shouldReceive('setServer');
$clientStorage->shouldReceive('get')->andThrow(
new \League\OAuth2\Server\Exception\UnauthorizedClientException()
);
$sessionStorage = M::mock('League\OAuth2\Server\Storage\SessionInterface');
$sessionStorage->shouldReceive('setServer');
$sessionStorage->shouldReceive('getByAccessToken')->andReturn(
(new SessionEntity($server))->setId('foobar')
);
$accessTokenStorage = M::mock('League\OAuth2\Server\Storage\AccessTokenInterface');
$accessTokenStorage->shouldReceive('setServer');
$scopeStorage = M::mock('League\OAuth2\Server\Storage\ScopeInterface');
$scopeStorage->shouldReceive('setServer');
$scopeStorage->shouldReceive('get')->andReturn(
(new ScopeEntity($server))->hydrate(['id' => 'foo'])
);
$server->setClientStorage($clientStorage);
$server->setScopeStorage($scopeStorage);
$server->setSessionStorage($sessionStorage);
$server->setAccessTokenStorage($accessTokenStorage);
$server->addGrantType($grant);
$server->issueAccessToken();
}
}

View File

@ -1,479 +0,0 @@
<?php
namespace LeagueTests\Grant;
use League\OAuth2\Server\AuthorizationServer;
use League\OAuth2\Server\Entity\ClientEntity;
use League\OAuth2\Server\Entity\ScopeEntity;
use League\OAuth2\Server\Entity\SessionEntity;
use League\OAuth2\Server\Grant\PasswordGrant;
use League\OAuth2\Server\Grant\RefreshTokenGrant;
use Mockery as M;
class PasswordGrantTest extends \PHPUnit_Framework_TestCase
{
public function testCompleteFlowMissingClientId()
{
$this->setExpectedException('League\OAuth2\Server\Exception\InvalidRequestException');
$_POST['grant_type'] = 'password';
$server = new AuthorizationServer();
$grant = new PasswordGrant();
$server->addGrantType($grant);
$server->issueAccessToken();
}
public function testCompleteFlowMissingClientSecret()
{
$this->setExpectedException('League\OAuth2\Server\Exception\InvalidRequestException');
$_POST = [
'grant_type' => 'password',
'client_id' => 'testapp',
];
$server = new AuthorizationServer();
$grant = new PasswordGrant();
$server->addGrantType($grant);
$server->issueAccessToken();
}
public function testCompleteFlowInvalidClient()
{
$this->setExpectedException('League\OAuth2\Server\Exception\InvalidClientException');
$_POST = [
'grant_type' => 'password',
'client_id' => 'testapp',
'client_secret' => 'foobar',
];
$server = new AuthorizationServer();
$grant = new PasswordGrant();
$clientStorage = M::mock('League\OAuth2\Server\Storage\ClientInterface');
$clientStorage->shouldReceive('setServer');
$clientStorage->shouldReceive('get')->andReturn(null);
$server->setClientStorage($clientStorage);
$server->addGrantType($grant);
$server->issueAccessToken();
}
public function testNoUsername()
{
$this->setExpectedException('League\OAuth2\Server\Exception\InvalidRequestException');
$_POST = [
'grant_type' => 'password',
'client_id' => 'testapp',
'client_secret' => 'foobar',
];
$server = new AuthorizationServer();
$grant = new PasswordGrant();
$clientStorage = M::mock('League\OAuth2\Server\Storage\ClientInterface');
$clientStorage->shouldReceive('setServer');
$clientStorage->shouldReceive('get')->andReturn(
(new ClientEntity($server))->hydrate(['id' => 'testapp'])
);
$sessionStorage = M::mock('League\OAuth2\Server\Storage\SessionInterface');
$sessionStorage->shouldReceive('setServer');
$sessionStorage->shouldReceive('create');
$sessionStorage->shouldReceive('getScopes')->andReturn([]);
$accessTokenStorage = M::mock('League\OAuth2\Server\Storage\AccessTokenInterface');
$accessTokenStorage->shouldReceive('setServer');
$accessTokenStorage->shouldReceive('create');
$accessTokenStorage->shouldReceive('getScopes')->andReturn([]);
$scopeStorage = M::mock('League\OAuth2\Server\Storage\ScopeInterface');
$scopeStorage->shouldReceive('setServer');
$scopeStorage->shouldReceive('get')->andReturn(null);
$server->setClientStorage($clientStorage);
$server->setScopeStorage($scopeStorage);
$server->setSessionStorage($sessionStorage);
$server->setAccessTokenStorage($accessTokenStorage);
$server->addGrantType($grant);
$server->issueAccessToken();
}
public function testNoPassword()
{
$this->setExpectedException('League\OAuth2\Server\Exception\InvalidRequestException');
$_POST = [
'grant_type' => 'password',
'client_id' => 'testapp',
'client_secret' => 'foobar',
'username' => 'foo',
];
$server = new AuthorizationServer();
$grant = new PasswordGrant();
$clientStorage = M::mock('League\OAuth2\Server\Storage\ClientInterface');
$clientStorage->shouldReceive('setServer');
$clientStorage->shouldReceive('get')->andReturn(
(new ClientEntity($server))->hydrate(['id' => 'testapp'])
);
$sessionStorage = M::mock('League\OAuth2\Server\Storage\SessionInterface');
$sessionStorage->shouldReceive('setServer');
$sessionStorage->shouldReceive('create');
$sessionStorage->shouldReceive('getScopes')->andReturn([]);
$accessTokenStorage = M::mock('League\OAuth2\Server\Storage\AccessTokenInterface');
$accessTokenStorage->shouldReceive('setServer');
$accessTokenStorage->shouldReceive('create');
$accessTokenStorage->shouldReceive('getScopes')->andReturn([]);
$scopeStorage = M::mock('League\OAuth2\Server\Storage\ScopeInterface');
$scopeStorage->shouldReceive('setServer');
$scopeStorage->shouldReceive('get')->andReturn(null);
$server->setClientStorage($clientStorage);
$server->setScopeStorage($scopeStorage);
$server->setSessionStorage($sessionStorage);
$server->setAccessTokenStorage($accessTokenStorage);
$server->addGrantType($grant);
$server->issueAccessToken();
}
public function testNoCallable()
{
$this->setExpectedException('League\OAuth2\Server\Exception\ServerErrorException');
$_POST = [
'grant_type' => 'password',
'client_id' => 'testapp',
'client_secret' => 'foobar',
'username' => 'foo',
'password' => 'foobar',
];
$server = new AuthorizationServer();
$grant = new PasswordGrant();
$clientStorage = M::mock('League\OAuth2\Server\Storage\ClientInterface');
$clientStorage->shouldReceive('setServer');
$clientStorage->shouldReceive('get')->andReturn(
(new ClientEntity($server))->hydrate(['id' => 'testapp'])
);
$sessionStorage = M::mock('League\OAuth2\Server\Storage\SessionInterface');
$sessionStorage->shouldReceive('setServer');
$sessionStorage->shouldReceive('create');
$sessionStorage->shouldReceive('getScopes')->andReturn([]);
$accessTokenStorage = M::mock('League\OAuth2\Server\Storage\AccessTokenInterface');
$accessTokenStorage->shouldReceive('setServer');
$accessTokenStorage->shouldReceive('create');
$accessTokenStorage->shouldReceive('getScopes')->andReturn([]);
$scopeStorage = M::mock('League\OAuth2\Server\Storage\ScopeInterface');
$scopeStorage->shouldReceive('setServer');
$scopeStorage->shouldReceive('get')->andReturn(null);
$server->setClientStorage($clientStorage);
$server->setScopeStorage($scopeStorage);
$server->setSessionStorage($sessionStorage);
$server->setAccessTokenStorage($accessTokenStorage);
$server->addGrantType($grant);
$server->issueAccessToken();
}
public function testCompleteFlowInvalidScope()
{
$this->setExpectedException('League\OAuth2\Server\Exception\InvalidScopeException');
$_POST = [
'grant_type' => 'password',
'client_id' => 'testapp',
'client_secret' => 'foobar',
'username' => 'foo',
'password' => 'foobar',
'scope' => 'foo',
];
$server = new AuthorizationServer();
$grant = new PasswordGrant();
$clientStorage = M::mock('League\OAuth2\Server\Storage\ClientInterface');
$clientStorage->shouldReceive('setServer');
$clientStorage->shouldReceive('get')->andReturn(
(new ClientEntity($server))->hydrate(['id' => 'testapp'])
);
$sessionStorage = M::mock('League\OAuth2\Server\Storage\SessionInterface');
$sessionStorage->shouldReceive('setServer');
$sessionStorage->shouldReceive('create');
$sessionStorage->shouldReceive('getScopes')->andReturn([]);
$accessTokenStorage = M::mock('League\OAuth2\Server\Storage\AccessTokenInterface');
$accessTokenStorage->shouldReceive('setServer');
$accessTokenStorage->shouldReceive('create');
$accessTokenStorage->shouldReceive('getScopes')->andReturn([]);
$scopeStorage = M::mock('League\OAuth2\Server\Storage\ScopeInterface');
$scopeStorage->shouldReceive('setServer');
$scopeStorage->shouldReceive('get')->andReturn(null);
$server->setClientStorage($clientStorage);
$server->setScopeStorage($scopeStorage);
$server->setSessionStorage($sessionStorage);
$server->setAccessTokenStorage($accessTokenStorage);
$grant->setVerifyCredentialsCallback(function () {
return 123;
});
$server->addGrantType($grant);
$server->issueAccessToken();
}
public function testCompleteFlowNoScopes()
{
$this->setExpectedException('League\OAuth2\Server\Exception\InvalidRequestException');
$_POST = [
'grant_type' => 'password',
'client_id' => 'testapp',
'client_secret' => 'foobar',
'username' => 'username',
'password' => 'password',
];
$server = new AuthorizationServer();
$grant = new PasswordGrant();
$clientStorage = M::mock('League\OAuth2\Server\Storage\ClientInterface');
$clientStorage->shouldReceive('setServer');
$clientStorage->shouldReceive('get')->andReturn(
(new ClientEntity($server))->hydrate(['id' => 'testapp'])
);
$sessionStorage = M::mock('League\OAuth2\Server\Storage\SessionInterface');
$sessionStorage->shouldReceive('setServer');
$sessionStorage->shouldReceive('create')->andreturn(123);
$sessionStorage->shouldReceive('getScopes')->shouldReceive('getScopes')->andReturn([]);
$sessionStorage->shouldReceive('associateScope');
$accessTokenStorage = M::mock('League\OAuth2\Server\Storage\AccessTokenInterface');
$accessTokenStorage->shouldReceive('setServer');
$accessTokenStorage->shouldReceive('create');
$accessTokenStorage->shouldReceive('getScopes')->andReturn([]);
$accessTokenStorage->shouldReceive('associateScope');
$scopeStorage = M::mock('League\OAuth2\Server\Storage\ScopeInterface');
$scopeStorage->shouldReceive('setServer');
$server->setClientStorage($clientStorage);
$server->setScopeStorage($scopeStorage);
$server->setSessionStorage($sessionStorage);
$server->setAccessTokenStorage($accessTokenStorage);
$server->requireScopeParam(true);
$grant->setVerifyCredentialsCallback(function () {
return 123;
});
$server->addGrantType($grant);
$server->issueAccessToken();
}
public function testCompleteFlowInvalidCredentials()
{
$this->setExpectedException('League\OAuth2\Server\Exception\InvalidCredentialsException');
$_POST = [
'grant_type' => 'password',
'client_id' => 'testapp',
'client_secret' => 'foobar',
'scope' => 'foo',
'username' => 'username',
'password' => 'password',
];
$server = new AuthorizationServer();
$grant = new PasswordGrant();
$clientStorage = M::mock('League\OAuth2\Server\Storage\ClientInterface');
$clientStorage->shouldReceive('setServer');
$clientStorage->shouldReceive('get')->andReturn(
(new ClientEntity($server))->hydrate(['id' => 'testapp'])
);
$sessionStorage = M::mock('League\OAuth2\Server\Storage\SessionInterface');
$sessionStorage->shouldReceive('setServer');
$sessionStorage->shouldReceive('create')->andreturn(123);
$sessionStorage->shouldReceive('getScopes')->shouldReceive('getScopes')->andReturn([
(new ScopeEntity($server))->hydrate(['id' => 'foo']),
]);
$sessionStorage->shouldReceive('associateScope');
$accessTokenStorage = M::mock('League\OAuth2\Server\Storage\AccessTokenInterface');
$accessTokenStorage->shouldReceive('setServer');
$accessTokenStorage->shouldReceive('create');
$accessTokenStorage->shouldReceive('getScopes')->andReturn([
(new ScopeEntity($server))->hydrate(['id' => 'foo']),
]);
$accessTokenStorage->shouldReceive('associateScope');
$scopeStorage = M::mock('League\OAuth2\Server\Storage\ScopeInterface');
$scopeStorage->shouldReceive('setServer');
$scopeStorage->shouldReceive('get')->andReturn(
(new ScopeEntity($server))->hydrate(['id' => 'foo'])
);
$server->setClientStorage($clientStorage);
$server->setScopeStorage($scopeStorage);
$server->setSessionStorage($sessionStorage);
$server->setAccessTokenStorage($accessTokenStorage);
$grant->setVerifyCredentialsCallback(function () {
return false;
});
$server->addGrantType($grant);
$server->issueAccessToken();
}
public function testCompleteFlow()
{
$_POST = [
'grant_type' => 'password',
'client_id' => 'testapp',
'client_secret' => 'foobar',
'scope' => 'foo',
'username' => 'username',
'password' => 'password',
];
$server = new AuthorizationServer();
$grant = new PasswordGrant();
$clientStorage = M::mock('League\OAuth2\Server\Storage\ClientInterface');
$clientStorage->shouldReceive('setServer');
$clientStorage->shouldReceive('get')->andReturn(
(new ClientEntity($server))->hydrate(['id' => 'testapp'])
);
$sessionStorage = M::mock('League\OAuth2\Server\Storage\SessionInterface');
$sessionStorage->shouldReceive('setServer');
$sessionStorage->shouldReceive('create')->andreturn(123);
$sessionStorage->shouldReceive('getScopes')->shouldReceive('getScopes')->andReturn([
(new ScopeEntity($server))->hydrate(['id' => 'foo']),
]);
$sessionStorage->shouldReceive('getByAccessToken')->andReturn(
(new SessionEntity($server))->setId('foobar')
);
$sessionStorage->shouldReceive('associateScope');
$accessTokenStorage = M::mock('League\OAuth2\Server\Storage\AccessTokenInterface');
$accessTokenStorage->shouldReceive('setServer');
$accessTokenStorage->shouldReceive('create');
$accessTokenStorage->shouldReceive('getScopes')->andReturn([
(new ScopeEntity($server))->hydrate(['id' => 'foo']),
]);
$accessTokenStorage->shouldReceive('associateScope');
$scopeStorage = M::mock('League\OAuth2\Server\Storage\ScopeInterface');
$scopeStorage->shouldReceive('setServer');
$scopeStorage->shouldReceive('get')->andReturn(
(new ScopeEntity($server))->hydrate(['id' => 'foo'])
);
$server->setClientStorage($clientStorage);
$server->setScopeStorage($scopeStorage);
$server->setSessionStorage($sessionStorage);
$server->setAccessTokenStorage($accessTokenStorage);
$grant->setVerifyCredentialsCallback(function () {
return 123;
});
$server->addGrantType($grant);
$response = $server->issueAccessToken();
$this->assertTrue(array_key_exists('access_token', $response));
$this->assertTrue(array_key_exists('token_type', $response));
$this->assertTrue(array_key_exists('expires_in', $response));
}
public function testCompleteFlowRefreshToken()
{
$_POST = [
'grant_type' => 'password',
'client_id' => 'testapp',
'client_secret' => 'foobar',
'scope' => 'foo',
'username' => 'username',
'password' => 'password',
];
$server = new AuthorizationServer();
$grant = new PasswordGrant();
$clientStorage = M::mock('League\OAuth2\Server\Storage\ClientInterface');
$clientStorage->shouldReceive('setServer');
$clientStorage->shouldReceive('get')->andReturn(
(new ClientEntity($server))->hydrate(['id' => 'testapp'])
);
$sessionStorage = M::mock('League\OAuth2\Server\Storage\SessionInterface');
$sessionStorage->shouldReceive('setServer');
$sessionStorage->shouldReceive('create')->andreturn(123);
$sessionStorage->shouldReceive('getScopes')->shouldReceive('getScopes')->andReturn([
(new ScopeEntity($server))->hydrate(['id' => 'foo']),
]);
$sessionStorage->shouldReceive('getByAccessToken')->andReturn(
(new SessionEntity($server))->setId('foobar')
);
$sessionStorage->shouldReceive('associateScope');
$accessTokenStorage = M::mock('League\OAuth2\Server\Storage\AccessTokenInterface');
$accessTokenStorage->shouldReceive('setServer');
$accessTokenStorage->shouldReceive('create');
$accessTokenStorage->shouldReceive('getScopes')->andReturn([
(new ScopeEntity($server))->hydrate(['id' => 'foo']),
]);
$accessTokenStorage->shouldReceive('associateScope');
$scopeStorage = M::mock('League\OAuth2\Server\Storage\ScopeInterface');
$scopeStorage->shouldReceive('setServer');
$scopeStorage->shouldReceive('get')->andReturn(
(new ScopeEntity($server))->hydrate(['id' => 'foo'])
);
$refreshTokenStorage = M::mock('League\OAuth2\Server\Storage\RefreshTokenInterface');
$refreshTokenStorage->shouldReceive('setServer');
$refreshTokenStorage->shouldReceive('create');
$refreshTokenStorage->shouldReceive('associateScope');
$server->setClientStorage($clientStorage);
$server->setScopeStorage($scopeStorage);
$server->setSessionStorage($sessionStorage);
$server->setAccessTokenStorage($accessTokenStorage);
$server->setRefreshTokenStorage($refreshTokenStorage);
$grant->setVerifyCredentialsCallback(function () {
return 123;
});
$server->addGrantType($grant);
$server->addGrantType(new RefreshTokenGrant());
$response = $server->issueAccessToken();
$this->assertTrue(array_key_exists('access_token', $response));
// $this->assertTrue(array_key_exists('refresh_token', $response));
$this->assertTrue(array_key_exists('token_type', $response));
$this->assertTrue(array_key_exists('expires_in', $response));
}
}

View File

@ -1,501 +0,0 @@
<?php
namespace LeagueTests\Grant;
use League\OAuth2\Server\AuthorizationServer;
use League\OAuth2\Server\Entity\AccessTokenEntity;
use League\OAuth2\Server\Entity\ClientEntity;
use League\OAuth2\Server\Entity\RefreshTokenEntity;
use League\OAuth2\Server\Entity\ScopeEntity;
use League\OAuth2\Server\Entity\SessionEntity;
use League\OAuth2\Server\Grant\RefreshTokenGrant;
use Mockery as M;
class RefreshTokenGrantTest extends \PHPUnit_Framework_TestCase
{
public function testSetRefreshTokenTTL()
{
$grant = new RefreshTokenGrant();
$grant->setRefreshTokenTTL(86400);
$property = new \ReflectionProperty($grant, 'refreshTokenTTL');
$property->setAccessible(true);
$this->assertEquals(86400, $property->getValue($grant));
}
public function testCompleteFlowMissingClientId()
{
$this->setExpectedException('League\OAuth2\Server\Exception\InvalidRequestException');
$_POST['grant_type'] = 'refresh_token';
$server = new AuthorizationServer();
$grant = new RefreshTokenGrant();
$server->addGrantType($grant);
$server->issueAccessToken();
}
public function testCompleteFlowMissingClientSecret()
{
$this->setExpectedException('League\OAuth2\Server\Exception\InvalidRequestException');
$_POST = [
'grant_type' => 'refresh_token',
'client_id' => 'testapp',
];
$server = new AuthorizationServer();
$grant = new RefreshTokenGrant();
$server->addGrantType($grant);
$server->issueAccessToken();
}
public function testCompleteFlowInvalidClient()
{
$this->setExpectedException('League\OAuth2\Server\Exception\InvalidClientException');
$_POST = [
'grant_type' => 'refresh_token',
'client_id' => 'testapp',
'client_secret' => 'foobar',
];
$server = new AuthorizationServer();
$grant = new RefreshTokenGrant();
$clientStorage = M::mock('League\OAuth2\Server\Storage\ClientInterface');
$clientStorage->shouldReceive('setServer');
$clientStorage->shouldReceive('get')->andReturn(null);
$server->setClientStorage($clientStorage);
$server->addGrantType($grant);
$server->issueAccessToken();
}
public function testCompleteFlowMissingRefreshToken()
{
$this->setExpectedException('League\OAuth2\Server\Exception\InvalidRequestException');
$_POST = [
'grant_type' => 'refresh_token',
'client_id' => 'testapp',
'client_secret' => 'foobar',
];
$server = new AuthorizationServer();
$grant = new RefreshTokenGrant();
$clientStorage = M::mock('League\OAuth2\Server\Storage\ClientInterface');
$clientStorage->shouldReceive('setServer');
$clientStorage->shouldReceive('get')->andReturn(
(new ClientEntity($server))->hydrate(['id' => 'testapp'])
);
$sessionStorage = M::mock('League\OAuth2\Server\Storage\SessionInterface');
$sessionStorage->shouldReceive('setServer');
$scopeStorage = M::mock('League\OAuth2\Server\Storage\ScopeInterface');
$scopeStorage->shouldReceive('setServer');
$server->setClientStorage($clientStorage);
$server->setScopeStorage($scopeStorage);
$server->setSessionStorage($sessionStorage);
$server->requireScopeParam(true);
$server->addGrantType($grant);
$server->issueAccessToken();
}
public function testCompleteFlowInvalidRefreshToken()
{
$this->setExpectedException('League\OAuth2\Server\Exception\InvalidRefreshException');
$_POST = [
'grant_type' => 'refresh_token',
'client_id' => 'testapp',
'client_secret' => 'foobar',
'refresh_token' => 'meh',
];
$server = new AuthorizationServer();
$grant = new RefreshTokenGrant();
$clientStorage = M::mock('League\OAuth2\Server\Storage\ClientInterface');
$clientStorage->shouldReceive('setServer');
$clientStorage->shouldReceive('get')->andReturn(
(new ClientEntity($server))->hydrate(['id' => 'testapp'])
);
$refreshTokenStorage = M::mock('League\OAuth2\Server\Storage\RefreshTokenInterface');
$refreshTokenStorage->shouldReceive('get');
$refreshTokenStorage->shouldReceive('setServer');
$scopeStorage = M::mock('League\OAuth2\Server\Storage\ScopeInterface');
$scopeStorage->shouldReceive('setServer');
$server->setClientStorage($clientStorage);
$server->setScopeStorage($scopeStorage);
$server->setRefreshTokenStorage($refreshTokenStorage);
$server->requireScopeParam(true);
$server->addGrantType($grant);
$server->issueAccessToken();
}
public function testCompleteFlowExistingScopes()
{
$_POST = [
'grant_type' => 'refresh_token',
'client_id' => 'testapp',
'client_secret' => 'foobar',
'refresh_token' => 'refresh_token',
];
$server = new AuthorizationServer();
$grant = new RefreshTokenGrant();
$clientStorage = M::mock('League\OAuth2\Server\Storage\ClientInterface');
$clientStorage->shouldReceive('setServer');
$clientStorage->shouldReceive('get')->andReturn(
(new ClientEntity($server))->hydrate(['id' => 'testapp'])
);
$sessionStorage = M::mock('League\OAuth2\Server\Storage\SessionInterface');
$sessionStorage->shouldReceive('setServer');
$sessionStorage->shouldReceive('getScopes')->shouldReceive('getScopes')->andReturn([]);
$sessionStorage->shouldReceive('associateScope');
$sessionStorage->shouldReceive('getByAccessToken')->andReturn(
(new SessionEntity($server))
);
$accessTokenStorage = M::mock('League\OAuth2\Server\Storage\AccessTokenInterface');
$accessTokenStorage->shouldReceive('setServer');
$accessTokenStorage->shouldReceive('get')->andReturn(
(new AccessTokenEntity($server))
);
$accessTokenStorage->shouldReceive('delete');
$accessTokenStorage->shouldReceive('create');
$accessTokenStorage->shouldReceive('getScopes')->andReturn([
(new ScopeEntity($server))->hydrate(['id' => 'foo']),
]);
$accessTokenStorage->shouldReceive('associateScope');
$refreshTokenStorage = M::mock('League\OAuth2\Server\Storage\RefreshTokenInterface');
$refreshTokenStorage->shouldReceive('setServer');
$refreshTokenStorage->shouldReceive('associateScope');
$refreshTokenStorage->shouldReceive('delete');
$refreshTokenStorage->shouldReceive('create');
$refreshTokenStorage->shouldReceive('get')->andReturn(
(new RefreshTokenEntity($server))->setExpireTime(time() + 86400)
);
$scopeStorage = M::mock('League\OAuth2\Server\Storage\ScopeInterface');
$scopeStorage->shouldReceive('setServer');
$scopeStorage->shouldReceive('get')->andReturn(
(new ScopeEntity($server))->hydrate(['id' => 'foo'])
);
$server->setClientStorage($clientStorage);
$server->setScopeStorage($scopeStorage);
$server->setSessionStorage($sessionStorage);
$server->setAccessTokenStorage($accessTokenStorage);
$server->setRefreshTokenStorage($refreshTokenStorage);
$server->addGrantType($grant);
$response = $server->issueAccessToken();
$this->assertTrue(array_key_exists('access_token', $response));
$this->assertTrue(array_key_exists('refresh_token', $response));
$this->assertTrue(array_key_exists('token_type', $response));
$this->assertTrue(array_key_exists('expires_in', $response));
}
public function testCompleteFlowRequestScopes()
{
$_POST = [
'grant_type' => 'refresh_token',
'client_id' => 'testapp',
'client_secret' => 'foobar',
'refresh_token' => 'refresh_token',
'scope' => 'foo',
];
$server = new AuthorizationServer();
$grant = new RefreshTokenGrant();
$oldSession = (new SessionEntity($server))->associateScope((new ScopeEntity($server))->hydrate(['id' => 'foo']));
$clientStorage = M::mock('League\OAuth2\Server\Storage\ClientInterface');
$clientStorage->shouldReceive('setServer');
$clientStorage->shouldReceive('get')->andReturn(
(new ClientEntity($server))->hydrate(['id' => 'testapp'])
);
$sessionStorage = M::mock('League\OAuth2\Server\Storage\SessionInterface');
$sessionStorage->shouldReceive('setServer');
$sessionStorage->shouldReceive('getScopes')->shouldReceive('getScopes')->andReturn([]);
$sessionStorage->shouldReceive('associateScope');
$sessionStorage->shouldReceive('getByAccessToken')->andReturn(
$oldSession
);
$accessTokenStorage = M::mock('League\OAuth2\Server\Storage\AccessTokenInterface');
$accessTokenStorage->shouldReceive('setServer');
$accessTokenStorage->shouldReceive('get')->andReturn(
(new AccessTokenEntity($server))
);
$accessTokenStorage->shouldReceive('delete');
$accessTokenStorage->shouldReceive('create');
$accessTokenStorage->shouldReceive('getScopes')->andReturn([
(new ScopeEntity($server))->hydrate(['id' => 'foo']),
]);
$accessTokenStorage->shouldReceive('associateScope');
$refreshTokenStorage = M::mock('League\OAuth2\Server\Storage\RefreshTokenInterface');
$refreshTokenStorage->shouldReceive('setServer');
$refreshTokenStorage->shouldReceive('associateScope');
$refreshTokenStorage->shouldReceive('delete');
$refreshTokenStorage->shouldReceive('create');
$refreshTokenStorage->shouldReceive('get')->andReturn(
(new RefreshTokenEntity($server))->setExpireTime(time() + 86400)
);
$scopeStorage = M::mock('League\OAuth2\Server\Storage\ScopeInterface');
$scopeStorage->shouldReceive('setServer');
$scopeStorage->shouldReceive('get')->andReturn(
(new ScopeEntity($server))->hydrate(['id' => 'foo'])
);
$server->setClientStorage($clientStorage);
$server->setScopeStorage($scopeStorage);
$server->setSessionStorage($sessionStorage);
$server->setAccessTokenStorage($accessTokenStorage);
$server->setRefreshTokenStorage($refreshTokenStorage);
$server->addGrantType($grant);
$response = $server->issueAccessToken();
$this->assertTrue(isset($response['access_token']));
$this->assertTrue(isset($response['refresh_token']));
$this->assertTrue(isset($response['token_type']));
$this->assertTrue(isset($response['expires_in']));
}
public function testCompleteFlowExpiredRefreshToken()
{
$this->setExpectedException('League\OAuth2\Server\Exception\InvalidRefreshException');
$_POST = [
'grant_type' => 'refresh_token',
'client_id' => 'testapp',
'client_secret' => 'foobar',
'refresh_token' => 'refresh_token',
'scope' => 'foo',
];
$server = new AuthorizationServer();
$grant = new RefreshTokenGrant();
$oldSession = (new SessionEntity($server))->associateScope((new ScopeEntity($server))->hydrate(['id' => 'foo']));
$clientStorage = M::mock('League\OAuth2\Server\Storage\ClientInterface');
$clientStorage->shouldReceive('setServer');
$clientStorage->shouldReceive('get')->andReturn(
(new ClientEntity($server))->hydrate(['id' => 'testapp'])
);
$sessionStorage = M::mock('League\OAuth2\Server\Storage\SessionInterface');
$sessionStorage->shouldReceive('setServer');
$sessionStorage->shouldReceive('getScopes')->shouldReceive('getScopes')->andReturn([]);
$sessionStorage->shouldReceive('associateScope');
$sessionStorage->shouldReceive('getByAccessToken')->andReturn(
$oldSession
);
$accessTokenStorage = M::mock('League\OAuth2\Server\Storage\AccessTokenInterface');
$accessTokenStorage->shouldReceive('setServer');
$accessTokenStorage->shouldReceive('get')->andReturn(
(new AccessTokenEntity($server))
);
$accessTokenStorage->shouldReceive('delete');
$accessTokenStorage->shouldReceive('create');
$accessTokenStorage->shouldReceive('getScopes')->andReturn([
(new ScopeEntity($server))->hydrate(['id' => 'foo']),
]);
$accessTokenStorage->shouldReceive('associateScope');
$refreshTokenStorage = M::mock('League\OAuth2\Server\Storage\RefreshTokenInterface');
$refreshTokenStorage->shouldReceive('setServer');
$refreshTokenStorage->shouldReceive('associateScope');
$refreshTokenStorage->shouldReceive('delete');
$refreshTokenStorage->shouldReceive('create');
$refreshTokenStorage->shouldReceive('get')->andReturn(
(new RefreshTokenEntity($server))
);
$scopeStorage = M::mock('League\OAuth2\Server\Storage\ScopeInterface');
$scopeStorage->shouldReceive('setServer');
$scopeStorage->shouldReceive('get')->andReturn(
(new ScopeEntity($server))->hydrate(['id' => 'foo'])
);
$server->setClientStorage($clientStorage);
$server->setScopeStorage($scopeStorage);
$server->setSessionStorage($sessionStorage);
$server->setAccessTokenStorage($accessTokenStorage);
$server->setRefreshTokenStorage($refreshTokenStorage);
$server->addGrantType($grant);
$server->issueAccessToken();
}
public function testCompleteFlowRequestScopesInvalid()
{
$_POST = [
'grant_type' => 'refresh_token',
'client_id' => 'testapp',
'client_secret' => 'foobar',
'refresh_token' => 'refresh_token',
'scope' => 'blah',
];
$server = new AuthorizationServer();
$grant = new RefreshTokenGrant();
$oldSession = (new SessionEntity($server))->associateScope((new ScopeEntity($server))->hydrate(['id' => 'foo']));
$clientStorage = M::mock('League\OAuth2\Server\Storage\ClientInterface');
$clientStorage->shouldReceive('setServer');
$clientStorage->shouldReceive('get')->andReturn(
(new ClientEntity($server))->hydrate(['id' => 'testapp'])
);
$sessionStorage = M::mock('League\OAuth2\Server\Storage\SessionInterface');
$sessionStorage->shouldReceive('setServer');
$sessionStorage->shouldReceive('getScopes')->shouldReceive('getScopes')->andReturn([]);
$sessionStorage->shouldReceive('associateScope');
$sessionStorage->shouldReceive('getByAccessToken')->andReturn(
$oldSession
);
$accessTokenStorage = M::mock('League\OAuth2\Server\Storage\AccessTokenInterface');
$accessTokenStorage->shouldReceive('setServer');
$accessTokenStorage->shouldReceive('get')->andReturn(
(new AccessTokenEntity($server))
);
$accessTokenStorage->shouldReceive('delete');
$accessTokenStorage->shouldReceive('create');
$accessTokenStorage->shouldReceive('getScopes')->andReturn([
(new ScopeEntity($server))->hydrate(['id' => 'foo']),
]);
$accessTokenStorage->shouldReceive('associateScope');
$refreshTokenStorage = M::mock('League\OAuth2\Server\Storage\RefreshTokenInterface');
$refreshTokenStorage->shouldReceive('setServer');
$refreshTokenStorage->shouldReceive('associateScope');
$refreshTokenStorage->shouldReceive('delete');
$refreshTokenStorage->shouldReceive('create');
$refreshTokenStorage->shouldReceive('get')->andReturn(
(new RefreshTokenEntity($server))->setExpireTime(time() + 86400)
);
$scopeStorage = M::mock('League\OAuth2\Server\Storage\ScopeInterface');
$scopeStorage->shouldReceive('setServer');
$scopeStorage->shouldReceive('get')->andReturn(
(new ScopeEntity($server))->hydrate(['id' => 'blah'])
);
$server->setClientStorage($clientStorage);
$server->setScopeStorage($scopeStorage);
$server->setSessionStorage($sessionStorage);
$server->setAccessTokenStorage($accessTokenStorage);
$server->setRefreshTokenStorage($refreshTokenStorage);
$server->addGrantType($grant);
$this->setExpectedException('League\OAuth2\Server\Exception\InvalidScopeException');
$server->issueAccessToken();
}
public function testCompleteFlowRotateRefreshToken()
{
$_POST = [
'grant_type' => 'refresh_token',
'client_id' => 'testapp',
'client_secret' => 'foobar',
'refresh_token' => 'refresh_token',
];
$server = new AuthorizationServer();
$grant = new RefreshTokenGrant();
$clientStorage = M::mock('League\OAuth2\Server\Storage\ClientInterface');
$clientStorage->shouldReceive('setServer');
$clientStorage->shouldReceive('get')->andReturn(
(new ClientEntity($server))->hydrate(['id' => 'testapp'])
);
$sessionStorage = M::mock('League\OAuth2\Server\Storage\SessionInterface');
$sessionStorage->shouldReceive('setServer');
$sessionStorage->shouldReceive('getScopes')->shouldReceive('getScopes')->andReturn([]);
$sessionStorage->shouldReceive('associateScope');
$sessionStorage->shouldReceive('getByAccessToken')->andReturn(
(new SessionEntity($server))
);
$accessTokenStorage = M::mock('League\OAuth2\Server\Storage\AccessTokenInterface');
$accessTokenStorage->shouldReceive('setServer');
$accessTokenStorage->shouldReceive('get')->andReturn(
(new AccessTokenEntity($server))
);
$accessTokenStorage->shouldReceive('delete');
$accessTokenStorage->shouldReceive('create');
$accessTokenStorage->shouldReceive('getScopes')->andReturn([
(new ScopeEntity($server))->hydrate(['id' => 'foo']),
]);
$accessTokenStorage->shouldReceive('associateScope');
$refreshTokenStorage = M::mock('League\OAuth2\Server\Storage\RefreshTokenInterface');
$refreshTokenStorage->shouldReceive('setServer');
$refreshTokenStorage->shouldReceive('associateScope');
$refreshTokenStorage->shouldReceive('delete');
$refreshTokenStorage->shouldReceive('create');
$refreshTokenStorage->shouldReceive('get')->andReturn(
(new RefreshTokenEntity($server))->setId('refresh_token')->setExpireTime(time() + 86400)
);
$scopeStorage = M::mock('League\OAuth2\Server\Storage\ScopeInterface');
$scopeStorage->shouldReceive('setServer');
$scopeStorage->shouldReceive('get')->andReturn(
(new ScopeEntity($server))->hydrate(['id' => 'foo'])
);
$server->setClientStorage($clientStorage);
$server->setScopeStorage($scopeStorage);
$server->setSessionStorage($sessionStorage);
$server->setAccessTokenStorage($accessTokenStorage);
$server->setRefreshTokenStorage($refreshTokenStorage);
$server->addGrantType($grant);
$response = $server->issueAccessToken();
$this->assertTrue(array_key_exists('access_token', $response));
$this->assertTrue(array_key_exists('refresh_token', $response));
$this->assertTrue(array_key_exists('token_type', $response));
$this->assertTrue(array_key_exists('expires_in', $response));
$this->assertNotEquals($response['refresh_token'], $_POST['refresh_token']);
$grant->setRefreshTokenRotation(false);
$response = $server->issueAccessToken();
$this->assertTrue(array_key_exists('access_token', $response));
$this->assertTrue(array_key_exists('refresh_token', $response));
$this->assertTrue(array_key_exists('token_type', $response));
$this->assertTrue(array_key_exists('expires_in', $response));
$this->assertEquals($response['refresh_token'], $_POST['refresh_token']);
}
}

View File

@ -1,226 +0,0 @@
<?php
namespace LeagueTests;
use League\OAuth2\Server\Entity\AccessTokenEntity;
use League\OAuth2\Server\Entity\ClientEntity;
use League\OAuth2\Server\Entity\ScopeEntity;
use League\OAuth2\Server\Entity\SessionEntity;
use League\OAuth2\Server\ResourceServer;
use Mockery as M;
class ResourceServerTest extends \PHPUnit_Framework_TestCase
{
private function returnDefault()
{
$sessionStorage = M::mock('League\OAuth2\Server\Storage\SessionInterface');
$sessionStorage->shouldReceive('setServer');
$accessTokenStorage = M::mock('League\OAuth2\Server\Storage\AccessTokenInterface');
$accessTokenStorage->shouldReceive('setServer');
$clientStorage = M::mock('League\OAuth2\Server\Storage\ClientInterface');
$clientStorage->shouldReceive('setServer');
$scopeStorage = M::mock('League\OAuth2\Server\Storage\ScopeInterface');
$scopeStorage->shouldReceive('setServer');
$server = new ResourceServer(
$sessionStorage,
$accessTokenStorage,
$clientStorage,
$scopeStorage
);
return $server;
}
public function testGetSet()
{
$sessionStorage = M::mock('League\OAuth2\Server\Storage\SessionInterface');
$sessionStorage->shouldReceive('setServer');
$accessTokenStorage = M::mock('League\OAuth2\Server\Storage\AccessTokenInterface');
$accessTokenStorage->shouldReceive('setServer');
$clientStorage = M::mock('League\OAuth2\Server\Storage\ClientInterface');
$clientStorage->shouldReceive('setServer');
$scopeStorage = M::mock('League\OAuth2\Server\Storage\ScopeInterface');
$scopeStorage->shouldReceive('setServer');
$server = new ResourceServer(
$sessionStorage,
$accessTokenStorage,
$clientStorage,
$scopeStorage
);
}
public function testDetermineAccessTokenMissingToken()
{
$this->setExpectedException('League\OAuth2\Server\Exception\InvalidRequestException');
$sessionStorage = M::mock('League\OAuth2\Server\Storage\SessionInterface');
$sessionStorage->shouldReceive('setServer');
$accessTokenStorage = M::mock('League\OAuth2\Server\Storage\AccessTokenInterface');
$accessTokenStorage->shouldReceive('setServer');
$accessTokenStorage->shouldReceive('get')->andReturn(false);
$clientStorage = M::mock('League\OAuth2\Server\Storage\ClientInterface');
$clientStorage->shouldReceive('setServer');
$scopeStorage = M::mock('League\OAuth2\Server\Storage\ScopeInterface');
$scopeStorage->shouldReceive('setServer');
$server = new ResourceServer(
$sessionStorage,
$accessTokenStorage,
$clientStorage,
$scopeStorage
);
$request = new \Symfony\Component\HttpFoundation\Request();
$request->headers = new \Symfony\Component\HttpFoundation\ParameterBag([
'HTTP_AUTHORIZATION' => 'Bearer',
]);
$server->setRequest($request);
$reflector = new \ReflectionClass($server);
$method = $reflector->getMethod('determineAccessToken');
$method->setAccessible(true);
$method->invoke($server);
}
public function testIsValidNotValid()
{
$sessionStorage = M::mock('League\OAuth2\Server\Storage\SessionInterface');
$sessionStorage->shouldReceive('setServer');
$accessTokenStorage = M::mock('League\OAuth2\Server\Storage\AccessTokenInterface');
$accessTokenStorage->shouldReceive('setServer');
$accessTokenStorage->shouldReceive('get')->andReturn(false);
$clientStorage = M::mock('League\OAuth2\Server\Storage\ClientInterface');
$clientStorage->shouldReceive('setServer');
$scopeStorage = M::mock('League\OAuth2\Server\Storage\ScopeInterface');
$scopeStorage->shouldReceive('setServer');
$server = new ResourceServer(
$sessionStorage,
$accessTokenStorage,
$clientStorage,
$scopeStorage
);
$this->setExpectedException('League\OAuth2\Server\Exception\AccessDeniedException');
$server->isValidRequest(false, 'foobar');
}
public function testIsValid()
{
$sessionStorage = M::mock('League\OAuth2\Server\Storage\SessionInterface');
$sessionStorage->shouldReceive('setServer');
$accessTokenStorage = M::mock('League\OAuth2\Server\Storage\AccessTokenInterface');
$accessTokenStorage->shouldReceive('setServer');
$clientStorage = M::mock('League\OAuth2\Server\Storage\ClientInterface');
$clientStorage->shouldReceive('setServer');
$scopeStorage = M::mock('League\OAuth2\Server\Storage\ScopeInterface');
$scopeStorage->shouldReceive('setServer');
$server = new ResourceServer(
$sessionStorage,
$accessTokenStorage,
$clientStorage,
$scopeStorage
);
$server->setIdKey('at');
$server->addEventListener('session.owner', function ($event) {
$this->assertTrue($event->getSession() instanceof \League\OAuth2\Server\Entity\SessionEntity);
});
$accessTokenStorage->shouldReceive('get')->andReturn(
(new AccessTokenEntity($server))->setId('abcdef')->setExpireTime(time() + 300)
);
$accessTokenStorage->shouldReceive('getScopes')->andReturn([
(new ScopeEntity($server))->hydrate(['id' => 'foo']),
(new ScopeEntity($server))->hydrate(['id' => 'bar']),
]);
$sessionStorage->shouldReceive('getByAccessToken')->andReturn(
(new SessionEntity($server))->setId('foobar')->setOwner('user', 123)
);
$clientStorage->shouldReceive('getBySession')->andReturn(
(new ClientEntity($server))->hydrate(['id' => 'testapp'])
);
$request = new \Symfony\Component\HttpFoundation\Request();
$request->headers = new \Symfony\Component\HttpFoundation\ParameterBag([
'Authorization' => 'Bearer abcdef',
]);
$server->setRequest($request);
$this->assertTrue($server->isValidRequest());
$this->assertEquals('abcdef', $server->getAccessToken());
}
/**
* @expectedException League\OAuth2\Server\Exception\AccessDeniedException
*/
public function testIsValidExpiredToken()
{
$sessionStorage = M::mock('League\OAuth2\Server\Storage\SessionInterface');
$sessionStorage->shouldReceive('setServer');
$accessTokenStorage = M::mock('League\OAuth2\Server\Storage\AccessTokenInterface');
$accessTokenStorage->shouldReceive('setServer');
$clientStorage = M::mock('League\OAuth2\Server\Storage\ClientInterface');
$clientStorage->shouldReceive('setServer');
$scopeStorage = M::mock('League\OAuth2\Server\Storage\ScopeInterface');
$scopeStorage->shouldReceive('setServer');
$server = new ResourceServer(
$sessionStorage,
$accessTokenStorage,
$clientStorage,
$scopeStorage
);
$server->setIdKey('at');
$server->addEventListener('session.owner', function ($event) {
$this->assertTrue($event->getSession() instanceof \League\OAuth2\Server\Entity\SessionEntity);
});
$accessTokenStorage->shouldReceive('get')->andReturn(
(new AccessTokenEntity($server))->setId('abcdef')->setExpireTime(time() - 300)
);
$accessTokenStorage->shouldReceive('getScopes')->andReturn([
(new ScopeEntity($server))->hydrate(['id' => 'foo']),
(new ScopeEntity($server))->hydrate(['id' => 'bar']),
]);
$sessionStorage->shouldReceive('getByAccessToken')->andReturn(
(new SessionEntity($server))->setId('foobar')->setOwner('user', 123)
);
$clientStorage->shouldReceive('getBySession')->andReturn(
(new ClientEntity($server))->hydrate(['id' => 'testapp'])
);
$request = new \Symfony\Component\HttpFoundation\Request();
$request->headers = new \Symfony\Component\HttpFoundation\ParameterBag([
'Authorization' => 'Bearer abcdef',
]);
$server->setRequest($request);
$server->isValidRequest();
}
}

View File

@ -1,23 +0,0 @@
<?php
namespace LeagueTests\Storage;
use LeagueTests\Stubs\StubAbstractServer;
use LeagueTests\Stubs\StubAbstractStorage;
class AbstractStorageTest extends \PHPUnit_Framework_TestCase
{
public function testSetGet()
{
$storage = new StubAbstractStorage();
$reflector = new \ReflectionClass($storage);
$setMethod = $reflector->getMethod('setServer');
$setMethod->setAccessible(true);
$setMethod->invokeArgs($storage, [new StubAbstractServer()]);
$getMethod = $reflector->getMethod('getServer');
$getMethod->setAccessible(true);
$this->assertTrue($getMethod->invoke($storage) instanceof StubAbstractServer);
}
}

View File

@ -1,18 +0,0 @@
<?php
namespace LeagueTests\Stubs;
class StubAbstractGrant extends \League\OAuth2\Server\Grant\AbstractGrant
{
protected $responseType = 'foobar';
public function completeFlow()
{
return true;
}
public function getAuthorizationServer()
{
return $this->server;
}
}

View File

@ -1,8 +0,0 @@
<?php
namespace LeagueTests\Stubs;
class StubAbstractServer extends \League\OAuth2\Server\AbstractServer
{
//
}

View File

@ -1,8 +0,0 @@
<?php
namespace LeagueTests\Stubs;
class StubAbstractStorage extends \League\OAuth2\Server\Storage\AbstractStorage
{
//
}

View File

@ -1,18 +0,0 @@
<?php
namespace LeagueTests\Stubs;
use League\OAuth2\Server\Entity\AbstractTokenEntity;
class StubAbstractTokenEntity extends AbstractTokenEntity
{
public function expire()
{
//
}
public function save()
{
//
}
}

View File

@ -1,165 +0,0 @@
<?php
namespace LeagueTests\TokenType;
use League\OAuth2\Server\AuthorizationServer;
use League\OAuth2\Server\Entity\AccessTokenEntity;
use League\OAuth2\Server\TokenType\MAC;
use Mockery as M;
use Symfony\Component\HttpFoundation\Request;
class MacTest extends \PHPUnit_Framework_TestCase
{
public function testGenerateResponse()
{
$macStorage = M::mock('\League\OAuth2\Server\Storage\MacTokenInterface');
$macStorage->shouldReceive('create');
$server = new AuthorizationServer();
$server->setMacStorage($macStorage);
$tokenType = new MAC();
$tokenType->setServer($server);
$accessToken = new AccessTokenEntity($server);
$accessToken->setId(uniqid());
$accessToken->setExpireTime(time());
$tokenType->setParam('access_token', $accessToken->getId());
$tokenType->setParam('expires_in', 3600);
$response = $tokenType->generateResponse();
$this->assertEquals($accessToken->getId(), $response['access_token']);
$this->assertEquals('mac', $response['token_type']);
$this->assertEquals(3600, $response['expires_in']);
$this->assertEquals('hmac-sha-256', $response['mac_algorithm']);
$this->assertArrayHasKey('mac_key', $response);
}
public function testDetermineAccessTokenInHeaderValid()
{
$macStorage = M::mock('\League\OAuth2\Server\Storage\MacTokenInterface');
$macStorage->shouldReceive('getByAccessToken')->andReturn('abcdef');
$server = new AuthorizationServer();
$server->setMacStorage($macStorage);
$ts = time();
$request = Request::createFromGlobals();
$calculatedSignatureParts = [
$ts,
'foo',
strtoupper($request->getMethod()),
$request->getUri(),
$request->getHost(),
$request->getPort(),
'ext'
];
$calculatedSignature = base64_encode(hash_hmac('sha256', implode("\n", $calculatedSignatureParts), 'abcdef'));
$request->headers->set('Authorization', sprintf('MAC id="foo", nonce="foo", ts="%s", mac="%s", ext="ext"', $ts, $calculatedSignature));
$tokenType = new MAC();
$tokenType->setServer($server);
$response = $tokenType->determineAccessTokenInHeader($request);
$this->assertEquals('foo', $response);
}
public function testDetermineAccessTokenInHeaderMissingHeader()
{
$macStorage = M::mock('\League\OAuth2\Server\Storage\MacTokenInterface');
$macStorage->shouldReceive('getByAccessToken')->andReturn('abcdef');
$server = new AuthorizationServer();
$server->setMacStorage($macStorage);
$request = Request::createFromGlobals();
$tokenType = new MAC();
$tokenType->setServer($server);
$response = $tokenType->determineAccessTokenInHeader($request);
$this->assertEquals(null, $response);
}
public function testDetermineAccessTokenInHeaderMissingAuthMac()
{
$macStorage = M::mock('\League\OAuth2\Server\Storage\MacTokenInterface');
$macStorage->shouldReceive('getByAccessToken')->andReturn('abcdef');
$server = new AuthorizationServer();
$server->setMacStorage($macStorage);
$request = Request::createFromGlobals();
$request->headers->set('Authorization', '');
$tokenType = new MAC();
$tokenType->setServer($server);
$response = $tokenType->determineAccessTokenInHeader($request);
$this->assertEquals(null, $response);
}
public function testDetermineAccessTokenInHeaderInvalidParam()
{
$macStorage = M::mock('\League\OAuth2\Server\Storage\MacTokenInterface');
$macStorage->shouldReceive('getByAccessToken')->andReturn('abcdef');
$server = new AuthorizationServer();
$server->setMacStorage($macStorage);
$request = Request::createFromGlobals();
$request->headers->set('Authorization', 'MAC ');
$tokenType = new MAC();
$tokenType->setServer($server);
$response = $tokenType->determineAccessTokenInHeader($request);
$this->assertEquals(null, $response);
}
public function testDetermineAccessTokenInHeaderMismatchTimestamp()
{
$macStorage = M::mock('\League\OAuth2\Server\Storage\MacTokenInterface');
$macStorage->shouldReceive('getByAccessToken')->andReturn('abcdef');
$server = new AuthorizationServer();
$server->setMacStorage($macStorage);
$ts = time() - 100;
$request = Request::createFromGlobals();
$request->headers->set('Authorization', sprintf('MAC id="foo", nonce="foo", ts="%s", mac="%s", ext="ext"', $ts, 'foo'));
$tokenType = new MAC();
$tokenType->setServer($server);
$response = $tokenType->determineAccessTokenInHeader($request);
$this->assertEquals(null, $response);
}
public function testDetermineAccessTokenInHeaderMissingMacKey()
{
$macStorage = M::mock('\League\OAuth2\Server\Storage\MacTokenInterface');
$macStorage->shouldReceive('getByAccessToken')->andReturn(null);
$server = new AuthorizationServer();
$server->setMacStorage($macStorage);
$ts = time();
$request = Request::createFromGlobals();
$request->headers->set('Authorization', sprintf('MAC id="foo", nonce="foo", ts="%s", mac="%s", ext="ext"', $ts, 'foo'));
$tokenType = new MAC();
$tokenType->setServer($server);
$response = $tokenType->determineAccessTokenInHeader($request);
$this->assertEquals(null, $response);
}
}

View File

@ -1,19 +0,0 @@
<?php
namespace LeagueTests\util;
use League\OAuth2\Server\Util\RedirectUri;
class RedirectUriTest extends \PHPUnit_Framework_TestCase
{
public function testMake()
{
$v1 = RedirectUri::make('https://foobar/', ['foo' => 'bar']);
$v2 = RedirectUri::make('https://foobar/', ['foo' => 'bar'], '#');
$v3 = RedirectUri::make('https://foobar/', ['foo' => 'bar', 'bar' => 'foo']);
$this->assertEquals('https://foobar/?foo=bar', $v1);
$this->assertEquals('https://foobar/#foo=bar', $v2);
$this->assertEquals('https://foobar/?foo=bar&bar=foo', $v3);
}
}

View File

@ -1,35 +0,0 @@
<?php
namespace LeagueTests\util;
use League\OAuth2\Server\Util\SecureKey;
class SecureKeyTest extends \PHPUnit_Framework_TestCase
{
public function testGenerate()
{
$v1 = SecureKey::generate();
$v2 = SecureKey::generate();
$v3 = SecureKey::generate(50);
$this->assertEquals(40, strlen($v1));
$this->assertTrue($v1 !== $v2);
$this->assertEquals(50, strlen($v3));
}
public function testGenerateWithDifferentAlgorithm()
{
$algorithm = $this->getMock('League\OAuth2\Server\Util\KeyAlgorithm\KeyAlgorithmInterface');
$result = 'dasdsdsaads';
$algorithm
->expects($this->once())
->method('generate')
->with(11)
->will($this->returnValue($result));
SecureKey::setAlgorithm($algorithm);
$this->assertSame($algorithm, SecureKey::getAlgorithm());
$this->assertEquals($result, SecureKey::generate(11));
}
}