Compare commits

...

38 Commits
1.0.7 ... 1.0.9

Author SHA1 Message Date
Phil Sturgeon
d506969543 Bumped version number to 1.0.9 2013-08-15 15:08:35 -04:00
Phil Sturgeon
f9cb89c175 Updated composer.json for new packagist name. 2013-08-15 15:08:26 -04:00
Alex Bilbie
85312f6995 Updated ClientCredentials to properly include scopes 2013-03-22 12:36:18 +00:00
Alex Bilbie
f463eb9db1 Style fixes 2013-03-22 11:44:53 +00:00
Alex Bilbie
f4cdfa91c1 Updated Password grant 2013-03-22 11:41:04 +00:00
Alex Bilbie
fe6ecb1dcf Added test_issueAccessToken_HTTP_auth(). Fixes #22 2013-03-22 11:08:52 +00:00
Alex Bilbie
0bf2a5333a Added test_scopeParamRequired() 2013-03-22 11:07:55 +00:00
Alex Bilbie
105a5b2a31 Fixed client_id and client_secret retrieval from request in conformity with the RFC 2013-03-22 10:40:47 +00:00
Alex Bilbie
ecf2f2b9ea Updated ResourceServerTest 2013-03-22 10:37:01 +00:00
Alex Bilbie
493834fcbf Removed base64 decoding of token when present in authorization header. Fixes #23 2013-03-22 10:35:42 +00:00
Alex Bilbie
fb518715ce Updated authserver tests 2013-03-21 16:25:44 +00:00
Alex Bilbie
fce24aa74d Added getDefaultScope method 2013-03-21 16:22:44 +00:00
Alex Bilbie
0c30b9ca66 Added scopeParamRequired method 2013-03-21 16:22:29 +00:00
Alex Bilbie
03aa81450e Renamed method to setDefaultScope 2013-03-21 16:22:16 +00:00
Michael Gooden
6c34535155 First test case.
Signed-off-by: Michael Gooden <michael@bluepointweb.com>
2013-03-21 14:47:32 +00:00
Michael Gooden
5bd62fe942 Add optional default scope parameter.
Signed-off-by: Michael Gooden <me@michaelgooden.net>
2013-03-21 14:47:29 +00:00
lapause
26781d2c38 Corrected wrong return documentation for SessionInterface::validateAuthCode() method 2013-03-21 14:42:51 +00:00
lapause
18e1bb33de Added missing details (return values on failure) to methods of SessionInterface 2013-03-21 14:42:47 +00:00
lapause
3a6468897f Removed obsolete namespace inclusion 2013-03-21 14:42:43 +00:00
lapause
97484eea6a Typo correction in inline doc 2013-03-21 14:42:38 +00:00
Alex Bilbie
3341728eb2 Added implicit grant 2013-03-06 18:01:44 +00:00
Alex Bilbie
6b172d4c27 Made getGrantType public for use with implicit grant 2013-03-06 18:01:34 +00:00
Alex Bilbie
4962762c28 Change from static calls 2013-03-06 18:01:12 +00:00
Alex Bilbie
56b559894c Spelling fix 2013-03-06 17:57:48 +00:00
Alex Bilbie
a9a68a5cc8 Added scope parameter association for clientcredentials and password scope
TODO: Unit tests
2013-03-06 17:18:48 +00:00
Alex Bilbie
542ca52d49 Set a default parameter for getParam 2013-03-06 17:18:13 +00:00
Alex Bilbie
7d0c075b36 It ain't static anymore Jim 2013-03-06 17:18:04 +00:00
Alex Bilbie
c056be3e48 Updated .travis.yml 2013-03-06 17:05:07 +00:00
Alex Bilbie
f3e6f99696 Removed old build files 2013-03-06 17:04:49 +00:00
Alex Bilbie
3ad4010526 Cleaned up .gitignore 2013-03-06 17:04:31 +00:00
Alex Bilbie
07c07ccb5e Removed static functions, inject authserver instance into grants 2013-03-06 16:59:18 +00:00
Alex Bilbie
6a8f8bf7b7 Removed phpunit from composer.json 2013-03-06 16:58:29 +00:00
Alex Bilbie
4917bc228c Updated .gitignore 2013-03-06 16:57:29 +00:00
Alex Bilbie
b58082b536 Merge pull request #10 from MichaelGooden/patch-1
Fix state parameter check typo
2013-03-04 07:43:33 -08:00
Michael Gooden
f70c039275 Fix state parameter check typo 2013-03-04 17:31:59 +02:00
Alex Bilbie
f102b4fb68 Merge branch 'master' of github.com:lncd/OAuth2 2013-03-04 13:22:44 +00:00
Alex Bilbie
7d3712a4b1 Added tutorial section 2013-02-28 17:03:15 +00:00
Alex Bilbie
d6955922e9 Added description of grants link 2013-02-28 16:26:06 +00:00
22 changed files with 782 additions and 241 deletions

12
.gitignore vendored
View File

@@ -1,8 +1,6 @@
/vendor/ /vendor
/composer.lock /composer.lock
/docs/build/ /build/logs
/build/logs/ /build/coverage
/build/coverage/ /docs
test /testing
/docs/
/testing/

View File

@@ -5,4 +5,4 @@ php:
- 5.4 - 5.4
before_script: composer install --dev before_script: composer install --dev
script: phpunit -c build/phpunit.xml script: phpunit

View File

@@ -29,13 +29,18 @@ The authorization server is a flexible class and following core specification gr
* client credentials ([section 2.3.1](http://tools.ietf.org/html/rfc6749#section-2.3.1)) * client credentials ([section 2.3.1](http://tools.ietf.org/html/rfc6749#section-2.3.1))
* password (user credentials) ([section 4.3](http://tools.ietf.org/html/rfc6749#section-4.3)) * password (user credentials) ([section 4.3](http://tools.ietf.org/html/rfc6749#section-4.3))
A tutorial on how to use the authorization server can be found at [http://alexbilbie.com/2013/02/developing-an-oauth2-authorization-server/](http://alexbilbie.com/2013/02/developing-an-oauth2-authorization-server/). An overview of the different OAuth 2.0 grants can be found at [http://alexbilbie.com/2013/02/a-guide-to-oauth-2-grants/](http://alexbilbie.com/2013/02/a-guide-to-oauth-2-grants/).
### Resource Server ### Resource Server
The resource server allows you to secure your API endpoints by checking for a valid OAuth access token in the request and ensuring the token has the correct permission to access resources. The resource server allows you to secure your API endpoints by checking for a valid OAuth access token in the request and ensuring the token has the correct permission to access resources.
A tutorial on how to use the resource server can be found at [http://alexbilbie.com/2013/02/securing-your-api-with-oauth-2/](http://alexbilbie.com/2013/02/securing-your-api-with-oauth-2/).
## Tutorials
A tutorial on how to use the authorization server can be found at [http://alexbilbie.com/2013/02/developing-an-oauth2-authorization-server/](http://alexbilbie.com/2013/02/developing-an-oauth2-authorization-server/).
A tutorial on how to use the resource server to secure an API server can be found at [http://alexbilbie.com/2013/02/securing-your-api-with-oauth-2/](http://alexbilbie.com/2013/02/securing-your-api-with-oauth-2/).
## Future Goals ## Future Goals

View File

@@ -1,8 +0,0 @@
<?xml version="1.0"?>
<ruleset name="PHP_CodeSniffer">
<description>PHP_CodeSniffer configuration</description>
<rule ref="PSR2"/>
</ruleset>

View File

@@ -1,14 +0,0 @@
<ruleset name="OAuth 2.0 Server"
xmlns="http://pmd.sf.net/ruleset/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://pmd.sf.net/ruleset/1.0.0
http://pmd.sf.net/ruleset_xml_schema.xsd"
xsi:noNamespaceSchemaLocation="http://pmd.sf.net/ruleset_xml_schema.xsd">
<description>
Ruleset for OAuth 2.0 server
</description>
<!-- Import the entire unused code rule set -->
<rule ref="rulesets/unusedcode.xml" />
</ruleset>

View File

@@ -1,31 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit colors="true" convertNoticesToExceptions="true" convertWarningsToExceptions="true" stopOnError="false" stopOnFailure="false" stopOnIncomplete="false" stopOnSkipped="false" bootstrap="../tests/Bootstrap.php">
<testsuites>
<testsuite name="Authorization Server">
<directory suffix="Test.php">../tests/authorization</directory>
</testsuite>
<testsuite name="Resource Server">
<directory suffix="Test.php">../tests/resource</directory>
</testsuite>
<testsuite name="Utility Methods">
<directory suffix="Test.php">../tests/util</directory>
</testsuite>
</testsuites>
<filter>
<blacklist>
<directory suffix=".php">PEAR_INSTALL_DIR</directory>
<directory suffix=".php">PHP_LIBDIR</directory>
<directory suffix=".php">../vendor/composer</directory>
<directory suffix=".php">../vendor/mockery</directory>
<directory suffix=".php">../vendor/phpunit</directory>
<directory suffix=".php">../tests</directory>
<directory suffix=".php">../testing</directory>
</blacklist>
</filter>
<logging>
<log type="coverage-html" target="coverage" title="lncd/OAuth" charset="UTF-8" yui="true" highlight="true" lowUpperBound="50" highLowerBound="90"/>
<log type="coverage-text" target="php://stdout" title="lncd/OAuth" charset="UTF-8" yui="true" highlight="true" lowUpperBound="50" highLowerBound="90"/>
<log type="coverage-clover" target="logs/clover.xml"/>
<log type="junit" target="logs/junit.xml" logIncompleteSkipped="false"/>
</logging>
</phpunit>

View File

@@ -1,22 +1,15 @@
{ {
"name": "lncd/oauth2", "name": "league/oauth2-server",
"description": "A lightweight and powerful OAuth 2.0 authorization and resource server library with support for all the core specification grants", "description": "A lightweight and powerful OAuth 2.0 authorization and resource server library with support for all the core specification grants",
"version": "1.0.7", "version": "1.0.9",
"homepage": "https://github.com/lncd/OAuth2", "homepage": "https://github.com/php-loep/oauth2-server",
"license": "MIT", "license": "MIT",
"require": { "require": {
"php": ">=5.3.0" "php": ">=5.3.0"
}, },
"require-dev": { "require-dev": {
"phpunit/phpunit": "*", "mockery/mockery": ">=0.7.2"
"mockery/mockery": ">=0.7.2"
}, },
"repositories": [
{
"type": "git",
"url": "https://github.com/lncd/OAuth2"
}
],
"keywords": [ "keywords": [
"oauth", "oauth",
"oauth2", "oauth2",
@@ -34,6 +27,10 @@
"role": "Developer" "role": "Developer"
} }
], ],
"replace": {
"lncd/oauth2": "*",
"league/oauth2server": "*"
},
"autoload": { "autoload": {
"psr-0": { "psr-0": {
"OAuth2": "src/" "OAuth2": "src/"

31
phpunit.xml Normal file
View File

@@ -0,0 +1,31 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit colors="true" convertNoticesToExceptions="true" convertWarningsToExceptions="true" stopOnError="false" stopOnFailure="false" stopOnIncomplete="false" stopOnSkipped="false" bootstrap="tests/Bootstrap.php">
<testsuites>
<testsuite name="Authorization Server">
<directory suffix="Test.php">tests/authorization</directory>
</testsuite>
<testsuite name="Resource Server">
<directory suffix="Test.php">tests/resource</directory>
</testsuite>
<testsuite name="Utility Methods">
<directory suffix="Test.php">tests/util</directory>
</testsuite>
</testsuites>
<filter>
<blacklist>
<directory suffix=".php">PEAR_INSTALL_DIR</directory>
<directory suffix=".php">PHP_LIBDIR</directory>
<directory suffix=".php">vendor/composer</directory>
<directory suffix=".php">vendor/mockery</directory>
<directory suffix=".php">vendor/phpunit</directory>
<directory suffix=".php">tests</directory>
<directory suffix=".php">testing</directory>
</blacklist>
</filter>
<logging>
<log type="coverage-html" target="build/coverage" title="lncd/OAuth" charset="UTF-8" yui="true" highlight="true" lowUpperBound="50" highLowerBound="90"/>
<log type="coverage-text" target="php://stdout" title="lncd/OAuth" charset="UTF-8" yui="true" highlight="true" lowUpperBound="50" highLowerBound="90"/>
<log type="coverage-clover" target="build/logs/clover.xml"/>
<log type="junit" target="build/logs/junit.xml" logIncompleteSkipped="false"/>
</logging>
</phpunit>

View File

@@ -37,7 +37,7 @@ class AuthServer
* The TTL (time to live) of an access token in seconds (default: 3600) * The TTL (time to live) of an access token in seconds (default: 3600)
* @var integer * @var integer
*/ */
static protected $expiresIn = 3600; protected $expiresIn = 3600;
/** /**
* The registered grant response types * The registered grant response types
@@ -49,13 +49,13 @@ class AuthServer
* The client, scope and session storage classes * The client, scope and session storage classes
* @var array * @var array
*/ */
static protected $storages = array(); protected $storages = array();
/** /**
* The registered grant types * The registered grant types
* @var array * @var array
*/ */
static protected $grantTypes = array(); protected $grantTypes = array();
/** /**
* Require the "scope" parameter to be in checkAuthoriseParams() * Require the "scope" parameter to be in checkAuthoriseParams()
@@ -63,6 +63,12 @@ class AuthServer
*/ */
protected $requireScopeParam = true; protected $requireScopeParam = true;
/**
* Default scope to be used if none is provided and requireScopeParam is false
* @var string
*/
protected $defaultScope = null;
/** /**
* Require the "state" parameter to be in checkAuthoriseParams() * Require the "state" parameter to be in checkAuthoriseParams()
* @var boolean * @var boolean
@@ -73,7 +79,7 @@ class AuthServer
* The request object * The request object
* @var Util\RequestInterface * @var Util\RequestInterface
*/ */
static protected $request = null; protected $request = null;
/** /**
* Exception error codes * Exception error codes
@@ -96,7 +102,7 @@ class AuthServer
* Exception error messages * Exception error messages
* @var array * @var array
*/ */
static protected $exceptionMessages = array( protected static $exceptionMessages = array(
'invalid_request' => 'The request is missing a required parameter, includes an invalid parameter value, includes a parameter more than once, or is otherwise malformed. Check the "%s" parameter.', 'invalid_request' => 'The request is missing a required parameter, includes an invalid parameter value, includes a parameter more than once, or is otherwise malformed. Check the "%s" parameter.',
'unauthorized_client' => 'The client is not authorized to request an access token using this method.', 'unauthorized_client' => 'The client is not authorized to request an access token using this method.',
'access_denied' => 'The resource owner or authorization server denied the request.', 'access_denied' => 'The resource owner or authorization server denied the request.',
@@ -142,7 +148,7 @@ class AuthServer
*/ */
public function __construct(ClientInterface $client, SessionInterface $session, ScopeInterface $scope) public function __construct(ClientInterface $client, SessionInterface $session, ScopeInterface $scope)
{ {
self::$storages = array( $this->storages = array(
'client' => $client, 'client' => $client,
'session' => $session, 'session' => $session,
'scope' => $scope 'scope' => $scope
@@ -159,7 +165,7 @@ class AuthServer
if (is_null($identifier)) { if (is_null($identifier)) {
$identifier = $grantType->getIdentifier(); $identifier = $grantType->getIdentifier();
} }
self::$grantTypes[$identifier] = $grantType; $this->grantTypes[$identifier] = $grantType;
if ( ! is_null($grantType->getResponseType())) { if ( ! is_null($grantType->getResponseType())) {
$this->responseTypes[] = $grantType->getResponseType(); $this->responseTypes[] = $grantType->getResponseType();
@@ -171,9 +177,9 @@ class AuthServer
* @param string $identifier The grant type identifier * @param string $identifier The grant type identifier
* @return boolean Returns "true" if enabled, "false" if not * @return boolean Returns "true" if enabled, "false" if not
*/ */
public static function hasGrantType($identifier) public function hasGrantType($identifier)
{ {
return (array_key_exists($identifier, self::$grantTypes)); return (array_key_exists($identifier, $this->grantTypes));
} }
/** /**
@@ -186,6 +192,33 @@ class AuthServer
$this->requireScopeParam = $require; $this->requireScopeParam = $require;
} }
/**
* Is the scope parameter required?
* @return bool
*/
public function scopeParamRequired()
{
return $this->requireScopeParam;
}
/**
* Default scope to be used if none is provided and requireScopeParam is false
* @var string
*/
public function setDefaultScope($default = null)
{
$this->defaultScope = $default;
}
/**
* Default scope to be used if none is provided and requireScopeParam is false
* @return string|null
*/
public function getDefaultScope()
{
return $this->defaultScope;
}
/** /**
* Require the "state" paremter in checkAuthoriseParams() * Require the "state" paremter in checkAuthoriseParams()
* @param boolean $require * @param boolean $require
@@ -220,9 +253,9 @@ class AuthServer
* Get the TTL for an access token * Get the TTL for an access token
* @return int The TTL * @return int The TTL
*/ */
public static function getExpiresIn() public function getExpiresIn()
{ {
return self::$expiresIn; return $this->expiresIn;
} }
/** /**
@@ -231,7 +264,7 @@ class AuthServer
*/ */
public function setExpiresIn($expiresIn) public function setExpiresIn($expiresIn)
{ {
self::$expiresIn = $expiresIn; $this->expiresIn = $expiresIn;
} }
/** /**
@@ -241,7 +274,7 @@ class AuthServer
*/ */
public function setRequest(Util\RequestInterface $request) public function setRequest(Util\RequestInterface $request)
{ {
self::$request = $request; $this->request = $request;
} }
/** /**
@@ -249,16 +282,16 @@ class AuthServer
* *
* @return Util\RequestInterface * @return Util\RequestInterface
*/ */
public static function getRequest() public function getRequest()
{ {
if (self::$request === null) { if ($this->request === null) {
// @codeCoverageIgnoreStart // @codeCoverageIgnoreStart
self::$request = Request::buildFromGlobals(); $this->request = Request::buildFromGlobals();
} }
// @codeCoverageIgnoreEnd // @codeCoverageIgnoreEnd
return self::$request; return $this->request;
} }
/** /**
@@ -266,9 +299,9 @@ class AuthServer
* @param string $obj The class required * @param string $obj The class required
* @return Storage\ClientInterface|Storage\ScopeInterface|Storage\SessionInterface * @return Storage\ClientInterface|Storage\ScopeInterface|Storage\SessionInterface
*/ */
public static function getStorage($obj) public function getStorage($obj)
{ {
return self::$storages[$obj]; return $this->storages[$obj];
} }
/** /**
@@ -281,7 +314,7 @@ class AuthServer
public function checkAuthoriseParams($inputParams = array()) public function checkAuthoriseParams($inputParams = array())
{ {
// Auth params // Auth params
$authParams = self::getParam(array('client_id', 'redirect_uri', 'response_type', 'scope', 'state'), 'get', $inputParams); $authParams = $this->getParam(array('client_id', 'redirect_uri', 'response_type', 'scope', 'state'), 'get', $inputParams);
if (is_null($authParams['client_id'])) { if (is_null($authParams['client_id'])) {
throw new Exception\ClientException(sprintf(self::$exceptionMessages['invalid_request'], 'client_id'), 0); throw new Exception\ClientException(sprintf(self::$exceptionMessages['invalid_request'], 'client_id'), 0);
@@ -291,12 +324,12 @@ class AuthServer
throw new Exception\ClientException(sprintf(self::$exceptionMessages['invalid_request'], 'redirect_uri'), 0); throw new Exception\ClientException(sprintf(self::$exceptionMessages['invalid_request'], 'redirect_uri'), 0);
} }
if ($this->requireStateParam === true && is_null($authParams['redirect_uri'])) { if ($this->requireStateParam === true && is_null($authParams['state'])) {
throw new Exception\ClientException(sprintf(self::$exceptionMessages['invalid_request'], 'redirect_uri'), 0); throw new Exception\ClientException(sprintf(self::$exceptionMessages['invalid_request'], 'state'), 0);
} }
// Validate client ID and redirect URI // Validate client ID and redirect URI
$clientDetails = self::getStorage('client')->getClient($authParams['client_id'], null, $authParams['redirect_uri']); $clientDetails = $this->getStorage('client')->getClient($authParams['client_id'], null, $authParams['redirect_uri']);
if ($clientDetails === false) { if ($clientDetails === false) {
throw new Exception\ClientException(self::$exceptionMessages['invalid_client'], 8); throw new Exception\ClientException(self::$exceptionMessages['invalid_client'], 8);
@@ -323,12 +356,14 @@ class AuthServer
if ($this->requireScopeParam === true && count($scopes) === 0) { if ($this->requireScopeParam === true && count($scopes) === 0) {
throw new Exception\ClientException(sprintf(self::$exceptionMessages['invalid_request'], 'scope'), 0); throw new Exception\ClientException(sprintf(self::$exceptionMessages['invalid_request'], 'scope'), 0);
} elseif (count($scopes) === 0 && $this->defaultScope) {
$scopes = array($this->defaultScope);
} }
$authParams['scopes'] = array(); $authParams['scopes'] = array();
foreach ($scopes as $scope) { foreach ($scopes as $scope) {
$scopeDetails = self::getStorage('scope')->getScope($scope); $scopeDetails = $this->getStorage('scope')->getScope($scope);
if ($scopeDetails === false) { if ($scopeDetails === false) {
throw new Exception\ClientException(sprintf(self::$exceptionMessages['invalid_scope'], $scope), 4); throw new Exception\ClientException(sprintf(self::$exceptionMessages['invalid_scope'], $scope), 4);
@@ -354,15 +389,15 @@ class AuthServer
$authCode = SecureKey::make(); $authCode = SecureKey::make();
// Remove any old sessions the user might have // Remove any old sessions the user might have
self::getStorage('session')->deleteSession($authParams['client_id'], $type, $typeId); $this->getStorage('session')->deleteSession($authParams['client_id'], $type, $typeId);
// Create a new session // Create a new session
$sessionId = self::getStorage('session')->createSession($authParams['client_id'], $authParams['redirect_uri'], $type, $typeId, $authCode); $sessionId = $this->getStorage('session')->createSession($authParams['client_id'], $authParams['redirect_uri'], $type, $typeId, $authCode);
// Associate scopes with the new session // Associate scopes with the new session
foreach ($authParams['scopes'] as $scope) foreach ($authParams['scopes'] as $scope)
{ {
self::getStorage('session')->associateScope($sessionId, $scope['id']); $this->getStorage('session')->associateScope($sessionId, $scope['id']);
} }
return $authCode; return $authCode;
@@ -376,14 +411,14 @@ class AuthServer
*/ */
public function issueAccessToken($inputParams = array()) public function issueAccessToken($inputParams = array())
{ {
$grantType = self::getParam('grant_type', 'post', $inputParams); $grantType = $this->getParam('grant_type', 'post', $inputParams);
if (is_null($grantType)) { if (is_null($grantType)) {
throw new Exception\ClientException(sprintf(self::$exceptionMessages['invalid_request'], 'grant_type'), 0); throw new Exception\ClientException(sprintf(self::$exceptionMessages['invalid_request'], 'grant_type'), 0);
} }
// Ensure grant type is one that is recognised and is enabled // Ensure grant type is one that is recognised and is enabled
if ( ! in_array($grantType, array_keys(self::$grantTypes))) { if ( ! in_array($grantType, array_keys($this->grantTypes))) {
throw new Exception\ClientException(sprintf(self::$exceptionMessages['unsupported_grant_type'], $grantType), 7); throw new Exception\ClientException(sprintf(self::$exceptionMessages['unsupported_grant_type'], $grantType), 7);
} }
@@ -396,26 +431,34 @@ class AuthServer
* @param string $grantType The grant type identifer * @param string $grantType The grant type identifer
* @return class * @return class
*/ */
protected function getGrantType($grantType) public function getGrantType($grantType)
{ {
return self::$grantTypes[$grantType]; return $this->grantTypes[$grantType];
} }
/** /**
* Get a parameter from passed input parameters or the Request class * Get a parameter from passed input parameters or the Request class
* @param string|array $param Requried parameter * @param string|array $param Required parameter
* @param string $method Get/put/post/delete * @param string $method Get/put/post/delete
* @param array $inputParams Passed input parameters * @param array $inputParams Passed input parameters
* @return mixed 'Null' if parameter is missing * @return mixed 'Null' if parameter is missing
*/ */
public static function getParam($param = '', $method = 'get', $inputParams = array()) public function getParam($param = '', $method = 'get', $inputParams = array(), $default = null)
{ {
if (is_string($param)) { if (is_string($param)) {
return (isset($inputParams[$param])) ? $inputParams[$param] : self::getRequest()->{$method}($param); if (isset($inputParams[$param])) {
return $inputParams[$param];
} elseif ($param === 'client_id' && ! is_null($client_id = $this->getRequest()->server('PHP_AUTH_USER'))) {
return $client_id;
} elseif ($param === 'client_secret' && ! is_null($client_secret = $this->getRequest()->server('PHP_AUTH_PW'))) {
return $client_secret;
} else {
return $this->getRequest()->{$method}($param, $default);
}
} else { } else {
$response = array(); $response = array();
foreach ($param as $p) { foreach ($param as $p) {
$response[$p] = self::getParam($p, $method, $inputParams); $response[$p] = $this->getParam($p, $method, $inputParams);
} }
return $response; return $response;
} }

View File

@@ -36,6 +36,22 @@ class AuthCode implements GrantTypeInterface {
*/ */
protected $responseType = 'code'; protected $responseType = 'code';
/**
* AuthServer instance
* @var AuthServer
*/
protected $authServer = null;
/**
* Constructor
* @param AuthServer $authServer AuthServer instance
* @return void
*/
public function __construct(AuthServer $authServer)
{
$this->authServer = $authServer;
}
/** /**
* Return the identifier * Return the identifier
* @return string * @return string
@@ -62,51 +78,51 @@ class AuthCode implements GrantTypeInterface {
public function completeFlow($inputParams = null) public function completeFlow($inputParams = null)
{ {
// Get the required params // Get the required params
$authParams = AuthServer::getParam(array('client_id', 'client_secret', 'redirect_uri', 'code'), 'post', $inputParams); $authParams = $this->authServer->getParam(array('client_id', 'client_secret', 'redirect_uri', 'code'), 'post', $inputParams);
if (is_null($authParams['client_id'])) { if (is_null($authParams['client_id'])) {
throw new Exception\ClientException(sprintf(AuthServer::getExceptionMessage('invalid_request'), 'client_id'), 0); throw new Exception\ClientException(sprintf($this->authServer->getExceptionMessage('invalid_request'), 'client_id'), 0);
} }
if (is_null($authParams['client_secret'])) { if (is_null($authParams['client_secret'])) {
throw new Exception\ClientException(sprintf(AuthServer::getExceptionMessage('invalid_request'), 'client_secret'), 0); throw new Exception\ClientException(sprintf($this->authServer->getExceptionMessage('invalid_request'), 'client_secret'), 0);
} }
if (is_null($authParams['redirect_uri'])) { if (is_null($authParams['redirect_uri'])) {
throw new Exception\ClientException(sprintf(AuthServer::getExceptionMessage('invalid_request'), 'redirect_uri'), 0); throw new Exception\ClientException(sprintf($this->authServer->getExceptionMessage('invalid_request'), 'redirect_uri'), 0);
} }
// Validate client ID and redirect URI // Validate client ID and redirect URI
$clientDetails = AuthServer::getStorage('client')->getClient($authParams['client_id'], $authParams['client_secret'], $authParams['redirect_uri']); $clientDetails = $this->authServer->getStorage('client')->getClient($authParams['client_id'], $authParams['client_secret'], $authParams['redirect_uri']);
if ($clientDetails === false) { if ($clientDetails === false) {
throw new Exception\ClientException(AuthServer::getExceptionMessage('invalid_client'), 8); throw new Exception\ClientException($this->authServer->getExceptionMessage('invalid_client'), 8);
} }
$authParams['client_details'] = $clientDetails; $authParams['client_details'] = $clientDetails;
// Validate the authorization code // Validate the authorization code
if (is_null($authParams['code'])) { if (is_null($authParams['code'])) {
throw new Exception\ClientException(sprintf(AuthServer::getExceptionMessage('invalid_request'), 'code'), 0); throw new Exception\ClientException(sprintf($this->authServer->getExceptionMessage('invalid_request'), 'code'), 0);
} }
// Verify the authorization code matches the client_id and the request_uri // Verify the authorization code matches the client_id and the request_uri
$session = AuthServer::getStorage('session')->validateAuthCode($authParams['client_id'], $authParams['redirect_uri'], $authParams['code']); $session = $this->authServer->getStorage('session')->validateAuthCode($authParams['client_id'], $authParams['redirect_uri'], $authParams['code']);
if ( ! $session) { if ( ! $session) {
throw new Exception\ClientException(sprintf(AuthServer::getExceptionMessage('invalid_grant'), 'code'), 9); throw new Exception\ClientException(sprintf($this->authServer->getExceptionMessage('invalid_grant'), 'code'), 9);
} }
// A session ID was returned so update it with an access token, // A session ID was returned so update it with an access token,
// remove the authorisation code, change the stage to 'granted' // remove the authorisation code, change the stage to 'granted'
$accessToken = SecureKey::make(); $accessToken = SecureKey::make();
$refreshToken = (AuthServer::hasGrantType('refresh_token')) ? SecureKey::make() : null; $refreshToken = ($this->authServer->hasGrantType('refresh_token')) ? SecureKey::make() : null;
$accessTokenExpires = time() + AuthServer::getExpiresIn(); $accessTokenExpires = time() + $this->authServer->getExpiresIn();
$accessTokenExpiresIn = AuthServer::getExpiresIn(); $accessTokenExpiresIn = $this->authServer->getExpiresIn();
AuthServer::getStorage('session')->updateSession( $this->authServer->getStorage('session')->updateSession(
$session['id'], $session['id'],
null, null,
$accessToken, $accessToken,
@@ -122,7 +138,7 @@ class AuthCode implements GrantTypeInterface {
'expires_in' => $accessTokenExpiresIn 'expires_in' => $accessTokenExpiresIn
); );
if (AuthServer::hasGrantType('refresh_token')) { if ($this->authServer->hasGrantType('refresh_token')) {
$response['refresh_token'] = $refreshToken; $response['refresh_token'] = $refreshToken;
} }

View File

@@ -1,6 +1,6 @@
<?php <?php
/** /**
* OAuth 2.0 Auth code grant * OAuth 2.0 Client credentials grant
* *
* @package lncd/oauth2 * @package lncd/oauth2
* @author Alex Bilbie <hello@alexbilbie.com> * @author Alex Bilbie <hello@alexbilbie.com>
@@ -36,6 +36,22 @@ class ClientCredentials implements GrantTypeInterface {
*/ */
protected $responseType = null; protected $responseType = null;
/**
* AuthServer instance
* @var AuthServer
*/
protected $authServer = null;
/**
* Constructor
* @param AuthServer $authServer AuthServer instance
* @return void
*/
public function __construct(AuthServer $authServer)
{
$this->authServer = $authServer;
}
/** /**
* Return the identifier * Return the identifier
* @return string * @return string
@@ -62,7 +78,7 @@ class ClientCredentials implements GrantTypeInterface {
public function completeFlow($inputParams = null) public function completeFlow($inputParams = null)
{ {
// Get the required params // Get the required params
$authParams = AuthServer::getParam(array('client_id', 'client_secret'), 'post', $inputParams); $authParams = $this->authServer->getParam(array('client_id', 'client_secret'), 'post', $inputParams);
if (is_null($authParams['client_id'])) { if (is_null($authParams['client_id'])) {
throw new Exception\ClientException(sprintf(AuthServer::getExceptionMessage('invalid_request'), 'client_id'), 0); throw new Exception\ClientException(sprintf(AuthServer::getExceptionMessage('invalid_request'), 'client_id'), 0);
@@ -73,7 +89,7 @@ class ClientCredentials implements GrantTypeInterface {
} }
// Validate client ID and client secret // Validate client ID and client secret
$clientDetails = AuthServer::getStorage('client')->getClient($authParams['client_id'], $authParams['client_secret']); $clientDetails = $this->authServer->getStorage('client')->getClient($authParams['client_id'], $authParams['client_secret']);
if ($clientDetails === false) { if ($clientDetails === false) {
throw new Exception\ClientException(AuthServer::getExceptionMessage('invalid_client'), 8); throw new Exception\ClientException(AuthServer::getExceptionMessage('invalid_client'), 8);
@@ -81,18 +97,45 @@ class ClientCredentials implements GrantTypeInterface {
$authParams['client_details'] = $clientDetails; $authParams['client_details'] = $clientDetails;
// Validate any scopes that are in the request
$scope = $this->authServer->getParam('scope', 'post', $inputParams, '');
$scopes = explode($this->authServer->getScopeDelimeter(), $scope);
for ($i = 0; $i < count($scopes); $i++) {
$scopes[$i] = trim($scopes[$i]);
if ($scopes[$i] === '') unset($scopes[$i]); // Remove any junk scopes
}
if ($this->authServer->scopeParamRequired() === true && count($scopes) === 0) {
throw new Exception\ClientException(sprintf($this->authServer->getExceptionMessage('invalid_request'), 'scope'), 0);
} elseif (count($scopes) === 0 && $this->authServer->getDefaultScope()) {
$scopes = array($this->authServer->getDefaultScope());
}
$authParams['scopes'] = array();
foreach ($scopes as $scope) {
$scopeDetails = $this->authServer->getStorage('scope')->getScope($scope);
if ($scopeDetails === false) {
throw new Exception\ClientException(sprintf($this->authServer->getExceptionMessage('invalid_scope'), $scope), 4);
}
$authParams['scopes'][] = $scopeDetails;
}
// Generate an access token // Generate an access token
$accessToken = SecureKey::make(); $accessToken = SecureKey::make();
$refreshToken = (AuthServer::hasGrantType('refresh_token')) ? SecureKey::make() : null; $refreshToken = ($this->authServer->hasGrantType('refresh_token')) ? SecureKey::make() : null;
$accessTokenExpires = time() + AuthServer::getExpiresIn(); $accessTokenExpires = time() + $this->authServer->getExpiresIn();
$accessTokenExpiresIn = AuthServer::getExpiresIn(); $accessTokenExpiresIn = $this->authServer->getExpiresIn();
// Delete any existing sessions just to be sure // Delete any existing sessions just to be sure
AuthServer::getStorage('session')->deleteSession($authParams['client_id'], 'client', $authParams['client_id']); $this->authServer->getStorage('session')->deleteSession($authParams['client_id'], 'client', $authParams['client_id']);
// Create a new session // Create a new session
AuthServer::getStorage('session')->createSession( $sessionId = $this->authServer->getStorage('session')->createSession(
$authParams['client_id'], $authParams['client_id'],
null, null,
'client', 'client',
@@ -104,6 +147,12 @@ class ClientCredentials implements GrantTypeInterface {
'granted' 'granted'
); );
// Associate scopes with the new session
foreach ($authParams['scopes'] as $scope)
{
$this->authServer->getStorage('session')->associateScope($sessionId, $scope['id']);
}
$response = array( $response = array(
'access_token' => $accessToken, 'access_token' => $accessToken,
'token_type' => 'bearer', 'token_type' => 'bearer',
@@ -111,7 +160,7 @@ class ClientCredentials implements GrantTypeInterface {
'expires_in' => $accessTokenExpiresIn 'expires_in' => $accessTokenExpiresIn
); );
if (AuthServer::hasGrantType('refresh_token')) { if ($this->authServer->hasGrantType('refresh_token')) {
$response['refresh_token'] = $refreshToken; $response['refresh_token'] = $refreshToken;
} }

View File

@@ -21,10 +21,17 @@ use OAuth2\Storage\ScopeInterface;
interface GrantTypeInterface interface GrantTypeInterface
{ {
/** /**
* Returns the grant identifier (used to validate grant_type in OAuth2\AuthServer\issueAccessToken()) * Constructor
* @return string * @param AuthServer $authServer AuthServer instance
*/ * @return void
*/
public function __construct(AuthServer $authServer);
/**
* Returns the grant identifier (used to validate grant_type in OAuth2\AuthServer\issueAccessToken())
* @return string
*/
public function getIdentifier(); public function getIdentifier();
/** /**

View File

@@ -0,0 +1,116 @@
<?php
/**
* OAuth 2.0 implicit grant
*
* @package lncd/oauth2
* @author Alex Bilbie <hello@alexbilbie.com>
* @copyright Copyright (c) 2013 University of Lincoln
* @license http://mit-license.org/
* @link http://github.com/lncd/oauth2
*/
namespace OAuth2\Grant;
use OAuth2\Request;
use OAuth2\AuthServer;
use OAuth2\Exception;
use OAuth2\Util\SecureKey;
use OAuth2\Storage\SessionInterface;
use OAuth2\Storage\ClientInterface;
use OAuth2\Storage\ScopeInterface;
/**
* Client credentials grant class
*/
class Implict implements GrantTypeInterface {
/**
* Grant identifier
* @var string
*/
protected $identifier = 'implicit';
/**
* Response type
* @var string
*/
protected $responseType = 'token';
/**
* AuthServer instance
* @var AuthServer
*/
protected $authServer = null;
/**
* Constructor
* @param AuthServer $authServer AuthServer instance
* @return void
*/
public function __construct(AuthServer $authServer)
{
$this->authServer = $authServer;
}
/**
* Return the identifier
* @return string
*/
public function getIdentifier()
{
return $this->identifier;
}
/**
* Return the response type
* @return string
*/
public function getResponseType()
{
return $this->responseType;
}
/**
* Complete the client credentials grant
* @param null|array $inputParams
* @return array
*/
public function completeFlow($authParams = null)
{
// Remove any old sessions the user might have
$this->authServer->getStorage('session')->deleteSession($authParams['client_id'], 'user', $authParams['user_id']);
// Generate a new access token
$accessToken = SecureKey::make();
// Compute expiry time
$accessTokenExpires = time() + $this->authServer->getExpiresIn();
// Create a new session
$sessionId = $this->authServer->getStorage('session')->createSession(
$authParams['client_id'],
$authParams['redirect_uri'],
'user',
$authParams['user_id'],
null,
$accessToken,
null,
$accessTokenExpires,
'granted'
);
// Associate scopes with the new session
foreach ($authParams['scopes'] as $scope)
{
$this->authServer->getStorage('session')->associateScope($sessionId, $scope['id']);
}
$response = array(
'access_token' => $accessToken
);
return $response;
}
}
}

View File

@@ -42,6 +42,22 @@ class Password implements GrantTypeInterface {
*/ */
protected $callback = null; protected $callback = null;
/**
* AuthServer instance
* @var AuthServer
*/
protected $authServer = null;
/**
* Constructor
* @param AuthServer $authServer AuthServer instance
* @return void
*/
public function __construct(AuthServer $authServer)
{
$this->authServer = $authServer;
}
/** /**
* Return the identifier * Return the identifier
* @return string * @return string
@@ -90,52 +106,79 @@ class Password implements GrantTypeInterface {
public function completeFlow($inputParams = null) public function completeFlow($inputParams = null)
{ {
// Get the required params // Get the required params
$authParams = AuthServer::getParam(array('client_id', 'client_secret', 'username', 'password'), 'post', $inputParams); $authParams = $this->authServer->getParam(array('client_id', 'client_secret', 'username', 'password'), 'post', $inputParams);
if (is_null($authParams['client_id'])) { if (is_null($authParams['client_id'])) {
throw new Exception\ClientException(sprintf(AuthServer::getExceptionMessage('invalid_request'), 'client_id'), 0); throw new Exception\ClientException(sprintf($this->authServer->getExceptionMessage('invalid_request'), 'client_id'), 0);
} }
if (is_null($authParams['client_secret'])) { if (is_null($authParams['client_secret'])) {
throw new Exception\ClientException(sprintf(AuthServer::getExceptionMessage('invalid_request'), 'client_secret'), 0); throw new Exception\ClientException(sprintf($this->authServer->getExceptionMessage('invalid_request'), 'client_secret'), 0);
} }
// Validate client ID and redirect URI // Validate client ID and redirect URI
$clientDetails = AuthServer::getStorage('client')->getClient($authParams['client_id'], $authParams['client_secret']); $clientDetails = $this->authServer->getStorage('client')->getClient($authParams['client_id'], $authParams['client_secret']);
if ($clientDetails === false) { if ($clientDetails === false) {
throw new Exception\ClientException(AuthServer::getExceptionMessage('invalid_client'), 8); throw new Exception\ClientException($this->authServer->getExceptionMessage('invalid_client'), 8);
} }
$authParams['client_details'] = $clientDetails; $authParams['client_details'] = $clientDetails;
if (is_null($authParams['username'])) { if (is_null($authParams['username'])) {
throw new Exception\ClientException(sprintf(AuthServer::getExceptionMessage('invalid_request'), 'username'), 0); throw new Exception\ClientException(sprintf($this->authServer->getExceptionMessage('invalid_request'), 'username'), 0);
} }
if (is_null($authParams['password'])) { if (is_null($authParams['password'])) {
throw new Exception\ClientException(sprintf(AuthServer::getExceptionMessage('invalid_request'), 'password'), 0); throw new Exception\ClientException(sprintf($this->authServer->getExceptionMessage('invalid_request'), 'password'), 0);
} }
// Check if user's username and password are correct // Check if user's username and password are correct
$userId = call_user_func($this->getVerifyCredentialsCallback(), $authParams['username'], $authParams['password']); $userId = call_user_func($this->getVerifyCredentialsCallback(), $authParams['username'], $authParams['password']);
if ($userId === false) { if ($userId === false) {
throw new Exception\ClientException(AuthServer::getExceptionMessage('invalid_credentials'), 0); throw new Exception\ClientException($this->authServer->getExceptionMessage('invalid_credentials'), 0);
}
// Validate any scopes that are in the request
$scope = $this->authServer->getParam('scope', 'post', $inputParams, '');
$scopes = explode($this->authServer->getScopeDelimeter(), $scope);
for ($i = 0; $i < count($scopes); $i++) {
$scopes[$i] = trim($scopes[$i]);
if ($scopes[$i] === '') unset($scopes[$i]); // Remove any junk scopes
}
if ($this->authServer->scopeParamRequired() === true && count($scopes) === 0) {
throw new Exception\ClientException(sprintf($this->authServer->getExceptionMessage('invalid_request'), 'scope'), 0);
} elseif (count($scopes) === 0 && $this->authServer->getDefaultScope()) {
$scopes = array($this->authServer->getDefaultScope());
}
$authParams['scopes'] = array();
foreach ($scopes as $scope) {
$scopeDetails = $this->authServer->getStorage('scope')->getScope($scope);
if ($scopeDetails === false) {
throw new Exception\ClientException(sprintf($this->authServer->getExceptionMessage('invalid_scope'), $scope), 4);
}
$authParams['scopes'][] = $scopeDetails;
} }
// Generate an access token // Generate an access token
$accessToken = SecureKey::make(); $accessToken = SecureKey::make();
$refreshToken = (AuthServer::hasGrantType('refresh_token')) ? SecureKey::make() : null; $refreshToken = ($this->authServer->hasGrantType('refresh_token')) ? SecureKey::make() : null;
$accessTokenExpires = time() + AuthServer::getExpiresIn(); $accessTokenExpires = time() + $this->authServer->getExpiresIn();
$accessTokenExpiresIn = AuthServer::getExpiresIn(); $accessTokenExpiresIn = $this->authServer->getExpiresIn();
// Delete any existing sessions just to be sure // Delete any existing sessions just to be sure
AuthServer::getStorage('session')->deleteSession($authParams['client_id'], 'user', $userId); $this->authServer->getStorage('session')->deleteSession($authParams['client_id'], 'user', $userId);
// Create a new session // Create a new session
AuthServer::getStorage('session')->createSession( $sessionId = $this->authServer->getStorage('session')->createSession(
$authParams['client_id'], $authParams['client_id'],
null, null,
'user', 'user',
@@ -147,6 +190,12 @@ class Password implements GrantTypeInterface {
'granted' 'granted'
); );
// Associate scopes with the new session
foreach ($authParams['scopes'] as $scope)
{
$this->authServer->getStorage('session')->associateScope($sessionId, $scope['id']);
}
$response = array( $response = array(
'access_token' => $accessToken, 'access_token' => $accessToken,
'token_type' => 'bearer', 'token_type' => 'bearer',
@@ -154,7 +203,7 @@ class Password implements GrantTypeInterface {
'expires_in' => $accessTokenExpiresIn 'expires_in' => $accessTokenExpiresIn
); );
if (AuthServer::hasGrantType('refresh_token')) { if ($this->authServer->hasGrantType('refresh_token')) {
$response['refresh_token'] = $refreshToken; $response['refresh_token'] = $refreshToken;
} }

View File

@@ -36,6 +36,22 @@ class RefreshToken implements GrantTypeInterface {
*/ */
protected $responseType = null; protected $responseType = null;
/**
* AuthServer instance
* @var AuthServer
*/
protected $authServer = null;
/**
* Constructor
* @param AuthServer $authServer AuthServer instance
* @return void
*/
public function __construct(AuthServer $authServer)
{
$this->authServer = $authServer;
}
/** /**
* Return the identifier * Return the identifier
* @return string * @return string
@@ -62,47 +78,47 @@ class RefreshToken implements GrantTypeInterface {
public function completeFlow($inputParams = null) public function completeFlow($inputParams = null)
{ {
// Get the required params // Get the required params
$authParams = AuthServer::getParam(array('client_id', 'client_secret', 'refresh_token'), 'post', $inputParams); $authParams = $this->authServer->getParam(array('client_id', 'client_secret', 'refresh_token'), 'post', $inputParams);
if (is_null($authParams['client_id'])) { if (is_null($authParams['client_id'])) {
throw new Exception\ClientException(sprintf(AuthServer::getExceptionMessage('invalid_request'), 'client_id'), 0); throw new Exception\ClientException(sprintf($this->authServer->getExceptionMessage('invalid_request'), 'client_id'), 0);
} }
if (is_null($authParams['client_secret'])) { if (is_null($authParams['client_secret'])) {
throw new Exception\ClientException(sprintf(AuthServer::getExceptionMessage('invalid_request'), 'client_secret'), 0); throw new Exception\ClientException(sprintf($this->authServer->getExceptionMessage('invalid_request'), 'client_secret'), 0);
} }
// Validate client ID and client secret // Validate client ID and client secret
$clientDetails = AuthServer::getStorage('client')->getClient($authParams['client_id'], $authParams['client_secret']); $clientDetails = $this->authServer->getStorage('client')->getClient($authParams['client_id'], $authParams['client_secret']);
if ($clientDetails === false) { if ($clientDetails === false) {
throw new Exception\ClientException(AuthServer::getExceptionMessage('invalid_client'), 8); throw new Exception\ClientException($this->authServer->getExceptionMessage('invalid_client'), 8);
} }
$authParams['client_details'] = $clientDetails; $authParams['client_details'] = $clientDetails;
if (is_null($authParams['refresh_token'])) { if (is_null($authParams['refresh_token'])) {
throw new Exception\ClientException(sprintf(AuthServer::getExceptionMessage('invalid_request'), 'refresh_token'), 0); throw new Exception\ClientException(sprintf($this->authServer->getExceptionMessage('invalid_request'), 'refresh_token'), 0);
} }
// Validate refresh token // Validate refresh token
$sessionId = AuthServer::getStorage('client')->validateRefreshToken( $sessionId = $this->authServer->getStorage('client')->validateRefreshToken(
$authParams['refresh_token'], $authParams['refresh_token'],
$authParams['client_id'] $authParams['client_id']
); );
if ($sessionId === false) { if ($sessionId === false) {
throw new Exception\ClientException(AuthServer::getExceptionMessage('invalid_refresh'), 0); throw new Exception\ClientException($this->authServer->getExceptionMessage('invalid_refresh'), 0);
} }
// Generate new tokens // Generate new tokens
$accessToken = SecureKey::make(); $accessToken = SecureKey::make();
$refreshToken = (AuthServer::hasGrantType('refresh_token')) ? SecureKey::make() : null; $refreshToken = ($this->authServer->hasGrantType('refresh_token')) ? SecureKey::make() : null;
$accessTokenExpires = time() + AuthServer::getExpiresIn(); $accessTokenExpires = time() + $this->authServer->getExpiresIn();
$accessTokenExpiresIn = AuthServer::getExpiresIn(); $accessTokenExpiresIn = $this->authServer->getExpiresIn();
AuthServer::getStorage('session')->updateRefreshToken($sessionId, $accessToken, $refreshToken, $accessTokenExpires); $this->authServer->getStorage('session')->updateRefreshToken($sessionId, $accessToken, $refreshToken, $accessTokenExpires);
return array( return array(
'access_token' => $accessToken, 'access_token' => $accessToken,

View File

@@ -13,7 +13,6 @@ namespace OAuth2;
use OutOfBoundsException; use OutOfBoundsException;
use OAuth2\Storage\SessionInterface; use OAuth2\Storage\SessionInterface;
use OAuth2\Storage\SessionScopeInterface;
use OAuth2\Util\RequestInterface; use OAuth2\Util\RequestInterface;
use OAuth2\Util\Request; use OAuth2\Util\Request;
@@ -216,7 +215,7 @@ class ResourceServer
protected function determineAccessToken() protected function determineAccessToken()
{ {
if ($header = $this->getRequest()->header('Authorization')) { if ($header = $this->getRequest()->header('Authorization')) {
$access_token = base64_decode(trim(str_replace('Bearer', '', $header))); $access_token = trim(str_replace('Bearer', '', $header));
} else { } else {
$method = $this->getRequest()->server('REQUEST_METHOD'); $method = $this->getRequest()->server('REQUEST_METHOD');
$access_token = $this->getRequest()->{$method}($this->tokenKey); $access_token = $this->getRequest()->{$method}($this->tokenKey);

View File

@@ -108,7 +108,7 @@ interface SessionInterface
* @param string $clientId The client ID * @param string $clientId The client ID
* @param string $redirectUri The redirect URI * @param string $redirectUri The redirect URI
* @param string $authCode The authorisation code * @param string $authCode The authorisation code
* @return int|bool Returns the session ID if the auth code * @return array|bool Returns an array with the session ID in the 'id' key if the auth code
* is valid otherwise returns false * is valid otherwise returns false
*/ */
public function validateAuthCode( public function validateAuthCode(
@@ -137,8 +137,8 @@ interface SessionInterface
* ) * )
* </code> * </code>
* *
* @param [type] $accessToken [description] * @param string $accessToken The access token
* @return [type] [description] * @return bool|array Returns false if the validation fails, array on success
*/ */
public function validateAccessToken($accessToken); public function validateAccessToken($accessToken);
@@ -161,7 +161,7 @@ interface SessionInterface
* Validate a refresh token * Validate a refresh token
* @param string $refreshToken The refresh token * @param string $refreshToken The refresh token
* @param string $clientId The client ID * @param string $clientId The client ID
* @return int The session ID * @return bool|int The session ID, or false on failure
*/ */
public function validateRefreshToken($refreshToken, $clientId); public function validateRefreshToken($refreshToken, $clientId);

View File

@@ -52,7 +52,8 @@ class Authorization_Server_test extends PHPUnit_Framework_TestCase
public function test_hasGrantType() public function test_hasGrantType()
{ {
$this->assertFalse(OAuth2\AuthServer::hasGrantType('test')); $a = $this->returnDefault();
$this->assertFalse($a->hasGrantType('test'));
} }
public function test_addGrantType() public function test_addGrantType()
@@ -62,7 +63,7 @@ class Authorization_Server_test extends PHPUnit_Framework_TestCase
$grant->shouldReceive('getResponseType')->andReturn('test'); $grant->shouldReceive('getResponseType')->andReturn('test');
$a->addGrantType($grant, 'test'); $a->addGrantType($grant, 'test');
$this->assertTrue(OAuth2\AuthServer::hasGrantType('test')); $this->assertTrue($a->hasGrantType('test'));
} }
public function test_addGrantType_noIdentifier() public function test_addGrantType_noIdentifier()
@@ -73,7 +74,7 @@ class Authorization_Server_test extends PHPUnit_Framework_TestCase
$grant->shouldReceive('getResponseType')->andReturn('test'); $grant->shouldReceive('getResponseType')->andReturn('test');
$a->addGrantType($grant); $a->addGrantType($grant);
$this->assertTrue(OAuth2\AuthServer::hasGrantType('test')); $this->assertTrue($a->hasGrantType('test'));
} }
public function test_getScopeDelimeter() public function test_getScopeDelimeter()
@@ -102,6 +103,34 @@ class Authorization_Server_test extends PHPUnit_Framework_TestCase
$this->assertFalse($v); $this->assertFalse($v);
} }
public function test_scopeParamRequired()
{
$a = $this->returnDefault();
$a->requireScopeParam(false);
$this->assertFalse($a->scopeParamRequired());
}
public function test_setDefaultScope()
{
$a = $this->returnDefault();
$a->setDefaultScope('test.default');
$reflector = new ReflectionClass($a);
$requestProperty = $reflector->getProperty('defaultScope');
$requestProperty->setAccessible(true);
$v = $requestProperty->getValue($a);
$this->assertEquals('test.default', $v);
}
public function test_getDefaultScope()
{
$a = $this->returnDefault();
$a->setDefaultScope('test.default');
$this->assertEquals('test.default', $a->getDefaultScope());
}
public function test_requireStateParam() public function test_requireStateParam()
{ {
$a = $this->returnDefault(); $a = $this->returnDefault();
@@ -119,7 +148,7 @@ class Authorization_Server_test extends PHPUnit_Framework_TestCase
{ {
$a = $this->returnDefault(); $a = $this->returnDefault();
$a->setExpiresIn(7200); $a->setExpiresIn(7200);
$this->assertEquals(7200, $a::getExpiresIn()); $this->assertEquals(7200, $a->getExpiresIn());
} }
public function test_setExpiresIn() public function test_setExpiresIn()
@@ -138,7 +167,7 @@ class Authorization_Server_test extends PHPUnit_Framework_TestCase
$reflector = new ReflectionClass($a); $reflector = new ReflectionClass($a);
$requestProperty = $reflector->getProperty('request'); $requestProperty = $reflector->getProperty('request');
$requestProperty->setAccessible(true); $requestProperty->setAccessible(true);
$v = $requestProperty->getValue(); $v = $requestProperty->getValue($a);
$this->assertTrue($v instanceof OAuth2\Util\RequestInterface); $this->assertTrue($v instanceof OAuth2\Util\RequestInterface);
} }
@@ -148,7 +177,7 @@ class Authorization_Server_test extends PHPUnit_Framework_TestCase
$a = $this->returnDefault(); $a = $this->returnDefault();
$request = new OAuth2\Util\Request(); $request = new OAuth2\Util\Request();
$a->setRequest($request); $a->setRequest($request);
$v = $a::getRequest(); $v = $a->getRequest();
$this->assertTrue($v instanceof OAuth2\Util\RequestInterface); $this->assertTrue($v instanceof OAuth2\Util\RequestInterface);
} }
@@ -181,6 +210,20 @@ class Authorization_Server_test extends PHPUnit_Framework_TestCase
)); ));
} }
/**
* @expectedException OAuth2\Exception\ClientException
* @expectedExceptionCode 0
*/
public function test_checkAuthoriseParams_noRequiredState()
{
$a = $this->returnDefault();
$a->requireStateParam(true);
$a->checkAuthoriseParams(array(
'client_id' => 1234,
'redirect_uri' => 'http://foo/redirect'
));
}
/** /**
* @expectedException OAuth2\Exception\ClientException * @expectedException OAuth2\Exception\ClientException
* @expectedExceptionCode 8 * @expectedExceptionCode 8
@@ -251,7 +294,7 @@ class Authorization_Server_test extends PHPUnit_Framework_TestCase
)); ));
$a = $this->returnDefault(); $a = $this->returnDefault();
$a->addGrantType(new OAuth2\Grant\AuthCode()); $a->addGrantType(new OAuth2\Grant\AuthCode($a));
$a->checkAuthoriseParams(array( $a->checkAuthoriseParams(array(
'client_id' => 1234, 'client_id' => 1234,
@@ -261,6 +304,37 @@ class Authorization_Server_test extends PHPUnit_Framework_TestCase
)); ));
} }
public function test_checkAuthoriseParams_defaultScope()
{
$this->client->shouldReceive('getClient')->andReturn(array(
'client_id' => 1234,
'client_secret' => 5678,
'redirect_uri' => 'http://foo/redirect',
'name' => 'Example Client'
));
$this->scope->shouldReceive('getScope')->andReturn(array(
'id' => 1,
'scope' => 'foo',
'name' => 'Foo Name',
'description' => 'Foo Name Description'
));
$a = $this->returnDefault();
$a->addGrantType(new OAuth2\Grant\AuthCode($a));
$a->setDefaultScope('test.scope');
$a->requireScopeParam(false);
$params = $a->checkAuthoriseParams(array(
'client_id' => 1234,
'redirect_uri' => 'http://foo/redirect',
'response_type' => 'code',
'scope' => ''
));
$this->assertArrayHasKey('scopes', $params);
}
/** /**
* @expectedException OAuth2\Exception\ClientException * @expectedException OAuth2\Exception\ClientException
* @expectedExceptionCode 4 * @expectedExceptionCode 4
@@ -277,7 +351,7 @@ class Authorization_Server_test extends PHPUnit_Framework_TestCase
$this->scope->shouldReceive('getScope')->andReturn(false); $this->scope->shouldReceive('getScope')->andReturn(false);
$a = $this->returnDefault(); $a = $this->returnDefault();
$a->addGrantType(new OAuth2\Grant\AuthCode()); $a->addGrantType(new OAuth2\Grant\AuthCode($a));
$a->checkAuthoriseParams(array( $a->checkAuthoriseParams(array(
'client_id' => 1234, 'client_id' => 1234,
@@ -290,7 +364,7 @@ class Authorization_Server_test extends PHPUnit_Framework_TestCase
public function test_checkAuthoriseParams_passedInput() public function test_checkAuthoriseParams_passedInput()
{ {
$a = $this->returnDefault(); $a = $this->returnDefault();
$a->addGrantType(new OAuth2\Grant\AuthCode()); $a->addGrantType(new OAuth2\Grant\AuthCode($a));
$this->client->shouldReceive('getClient')->andReturn(array( $this->client->shouldReceive('getClient')->andReturn(array(
'client_id' => 1234, 'client_id' => 1234,
@@ -354,7 +428,7 @@ class Authorization_Server_test extends PHPUnit_Framework_TestCase
)); ));
$a = $this->returnDefault(); $a = $this->returnDefault();
$a->addGrantType(new OAuth2\Grant\AuthCode()); $a->addGrantType(new OAuth2\Grant\AuthCode($a));
$_GET['client_id'] = 1234; $_GET['client_id'] = 1234;
$_GET['redirect_uri'] = 'http://foo/redirect'; $_GET['redirect_uri'] = 'http://foo/redirect';
@@ -426,7 +500,7 @@ class Authorization_Server_test extends PHPUnit_Framework_TestCase
public function test_getGrantType() public function test_getGrantType()
{ {
$a = $this->returnDefault(); $a = $this->returnDefault();
$a->addGrantType(new OAuth2\Grant\AuthCode()); $a->addGrantType(new OAuth2\Grant\AuthCode($a));
$reflector = new ReflectionClass($a); $reflector = new ReflectionClass($a);
$method = $reflector->getMethod('getGrantType'); $method = $reflector->getMethod('getGrantType');
@@ -444,7 +518,7 @@ class Authorization_Server_test extends PHPUnit_Framework_TestCase
public function test_issueAccessToken_missingGrantType() public function test_issueAccessToken_missingGrantType()
{ {
$a = $this->returnDefault(); $a = $this->returnDefault();
$a->addGrantType(new OAuth2\Grant\AuthCode()); $a->addGrantType(new OAuth2\Grant\AuthCode($a));
$v = $a->issueAccessToken(); $v = $a->issueAccessToken();
} }
@@ -456,7 +530,7 @@ class Authorization_Server_test extends PHPUnit_Framework_TestCase
public function test_issueAccessToken_badGrantType() public function test_issueAccessToken_badGrantType()
{ {
$a = $this->returnDefault(); $a = $this->returnDefault();
$a->addGrantType(new OAuth2\Grant\AuthCode()); $a->addGrantType(new OAuth2\Grant\AuthCode($a));
$v = $a->issueAccessToken(array('grant_type' => 'foo')); $v = $a->issueAccessToken(array('grant_type' => 'foo'));
} }
@@ -468,7 +542,7 @@ class Authorization_Server_test extends PHPUnit_Framework_TestCase
public function test_issueAccessToken_missingClientId() public function test_issueAccessToken_missingClientId()
{ {
$a = $this->returnDefault(); $a = $this->returnDefault();
$a->addGrantType(new OAuth2\Grant\AuthCode()); $a->addGrantType(new OAuth2\Grant\AuthCode($a));
$v = $a->issueAccessToken(array( $v = $a->issueAccessToken(array(
'grant_type' => 'authorization_code' 'grant_type' => 'authorization_code'
@@ -482,7 +556,7 @@ class Authorization_Server_test extends PHPUnit_Framework_TestCase
public function test_issueAccessToken_missingClientSecret() public function test_issueAccessToken_missingClientSecret()
{ {
$a = $this->returnDefault(); $a = $this->returnDefault();
$a->addGrantType(new OAuth2\Grant\AuthCode()); $a->addGrantType(new OAuth2\Grant\AuthCode($a));
$v = $a->issueAccessToken(array( $v = $a->issueAccessToken(array(
'grant_type' => 'authorization_code', 'grant_type' => 'authorization_code',
@@ -497,7 +571,7 @@ class Authorization_Server_test extends PHPUnit_Framework_TestCase
public function test_issueAccessToken_missingRedirectUri() public function test_issueAccessToken_missingRedirectUri()
{ {
$a = $this->returnDefault(); $a = $this->returnDefault();
$a->addGrantType(new OAuth2\Grant\AuthCode()); $a->addGrantType(new OAuth2\Grant\AuthCode($a));
$v = $a->issueAccessToken(array( $v = $a->issueAccessToken(array(
'grant_type' => 'authorization_code', 'grant_type' => 'authorization_code',
@@ -515,7 +589,7 @@ class Authorization_Server_test extends PHPUnit_Framework_TestCase
$this->client->shouldReceive('getClient')->andReturn(false); $this->client->shouldReceive('getClient')->andReturn(false);
$a = $this->returnDefault(); $a = $this->returnDefault();
$a->addGrantType(new OAuth2\Grant\AuthCode()); $a->addGrantType(new OAuth2\Grant\AuthCode($a));
$v = $a->issueAccessToken(array( $v = $a->issueAccessToken(array(
'grant_type' => 'authorization_code', 'grant_type' => 'authorization_code',
@@ -534,7 +608,7 @@ class Authorization_Server_test extends PHPUnit_Framework_TestCase
$this->client->shouldReceive('getClient')->andReturn(array()); $this->client->shouldReceive('getClient')->andReturn(array());
$a = $this->returnDefault(); $a = $this->returnDefault();
$a->addGrantType(new OAuth2\Grant\AuthCode()); $a->addGrantType(new OAuth2\Grant\AuthCode($a));
$v = $a->issueAccessToken(array( $v = $a->issueAccessToken(array(
'grant_type' => 'authorization_code', 'grant_type' => 'authorization_code',
@@ -554,7 +628,7 @@ class Authorization_Server_test extends PHPUnit_Framework_TestCase
$this->session->shouldReceive('validateAuthCode')->andReturn(false); $this->session->shouldReceive('validateAuthCode')->andReturn(false);
$a = $this->returnDefault(); $a = $this->returnDefault();
$a->addGrantType(new OAuth2\Grant\AuthCode()); $a->addGrantType(new OAuth2\Grant\AuthCode($a));
$v = $a->issueAccessToken(array( $v = $a->issueAccessToken(array(
'grant_type' => 'authorization_code', 'grant_type' => 'authorization_code',
@@ -578,7 +652,7 @@ class Authorization_Server_test extends PHPUnit_Framework_TestCase
$this->session->shouldReceive('updateSession')->andReturn(null); $this->session->shouldReceive('updateSession')->andReturn(null);
$a = $this->returnDefault(); $a = $this->returnDefault();
$a->addGrantType(new OAuth2\Grant\AuthCode()); $a->addGrantType(new OAuth2\Grant\AuthCode($a));
$v = $a->issueAccessToken(array( $v = $a->issueAccessToken(array(
'grant_type' => 'authorization_code', 'grant_type' => 'authorization_code',
@@ -593,8 +667,8 @@ class Authorization_Server_test extends PHPUnit_Framework_TestCase
$this->assertArrayHasKey('expires', $v); $this->assertArrayHasKey('expires', $v);
$this->assertArrayHasKey('expires_in', $v); $this->assertArrayHasKey('expires_in', $v);
$this->assertEquals($a::getExpiresIn(), $v['expires_in']); $this->assertEquals($a->getExpiresIn(), $v['expires_in']);
$this->assertEquals(time()+$a::getExpiresIn(), $v['expires']); $this->assertEquals(time()+$a->getExpiresIn(), $v['expires']);
} }
public function test_issueAccessToken() public function test_issueAccessToken()
@@ -610,7 +684,7 @@ class Authorization_Server_test extends PHPUnit_Framework_TestCase
$this->session->shouldReceive('updateSession')->andReturn(null); $this->session->shouldReceive('updateSession')->andReturn(null);
$a = $this->returnDefault(); $a = $this->returnDefault();
$a->addGrantType(new OAuth2\Grant\AuthCode()); $a->addGrantType(new OAuth2\Grant\AuthCode($a));
$_POST['grant_type'] = 'authorization_code'; $_POST['grant_type'] = 'authorization_code';
$_POST['client_id'] = 1234; $_POST['client_id'] = 1234;
@@ -628,8 +702,43 @@ class Authorization_Server_test extends PHPUnit_Framework_TestCase
$this->assertArrayHasKey('expires', $v); $this->assertArrayHasKey('expires', $v);
$this->assertArrayHasKey('expires_in', $v); $this->assertArrayHasKey('expires_in', $v);
$this->assertEquals($a::getExpiresIn(), $v['expires_in']); $this->assertEquals($a->getExpiresIn(), $v['expires_in']);
$this->assertEquals(time()+$a::getExpiresIn(), $v['expires']); $this->assertEquals(time()+$a->getExpiresIn(), $v['expires']);
}
public function test_issueAccessToken_HTTP_auth()
{
$this->client->shouldReceive('getClient')->andReturn(array(
'client_id' => 1234,
'client_secret' => 5678,
'redirect_uri' => 'http://foo/redirect',
'name' => 'Example Client'
));
$this->session->shouldReceive('validateAuthCode')->andReturn(1);
$this->session->shouldReceive('updateSession')->andReturn(null);
$a = $this->returnDefault();
$a->addGrantType(new OAuth2\Grant\AuthCode($a));
$_POST['grant_type'] = 'authorization_code';
$_SERVER['PHP_AUTH_USER'] = 1234;
$_SERVER['PHP_AUTH_PW'] = 5678;
$_POST['redirect_uri'] = 'http://foo/redirect';
$_POST['code'] = 'foobar';
$request = new OAuth2\Util\Request(array(), $_POST, array(), array(), $_SERVER);
$a->setRequest($request);
$v = $a->issueAccessToken();
$this->assertArrayHasKey('access_token', $v);
$this->assertArrayHasKey('token_type', $v);
$this->assertArrayHasKey('expires', $v);
$this->assertArrayHasKey('expires_in', $v);
$this->assertEquals($a->getExpiresIn(), $v['expires_in']);
$this->assertEquals(time()+$a->getExpiresIn(), $v['expires']);
} }
public function tearDown() { public function tearDown() {

View File

@@ -27,7 +27,7 @@ class Client_Credentials_Grant_Test extends PHPUnit_Framework_TestCase
public function test_issueAccessToken_clientCredentialsGrant_missingClientId() public function test_issueAccessToken_clientCredentialsGrant_missingClientId()
{ {
$a = $this->returnDefault(); $a = $this->returnDefault();
$a->addGrantType(new OAuth2\Grant\ClientCredentials()); $a->addGrantType(new OAuth2\Grant\ClientCredentials($a));
$request = new OAuth2\Util\Request(array(), $_POST); $request = new OAuth2\Util\Request(array(), $_POST);
$a->setRequest($request); $a->setRequest($request);
@@ -44,7 +44,7 @@ class Client_Credentials_Grant_Test extends PHPUnit_Framework_TestCase
public function test_issueAccessToken_clientCredentialsGrant_missingClientPassword() public function test_issueAccessToken_clientCredentialsGrant_missingClientPassword()
{ {
$a = $this->returnDefault(); $a = $this->returnDefault();
$a->addGrantType(new OAuth2\Grant\ClientCredentials()); $a->addGrantType(new OAuth2\Grant\ClientCredentials($a));
$request = new OAuth2\Util\Request(array(), $_POST); $request = new OAuth2\Util\Request(array(), $_POST);
$a->setRequest($request); $a->setRequest($request);
@@ -64,7 +64,7 @@ class Client_Credentials_Grant_Test extends PHPUnit_Framework_TestCase
$this->client->shouldReceive('getClient')->andReturn(false); $this->client->shouldReceive('getClient')->andReturn(false);
$a = $this->returnDefault(); $a = $this->returnDefault();
$a->addGrantType(new OAuth2\Grant\ClientCredentials()); $a->addGrantType(new OAuth2\Grant\ClientCredentials($a));
$request = new OAuth2\Util\Request(array(), $_POST); $request = new OAuth2\Util\Request(array(), $_POST);
$a->setRequest($request); $a->setRequest($request);
@@ -93,7 +93,7 @@ class Client_Credentials_Grant_Test extends PHPUnit_Framework_TestCase
$this->session->shouldReceive('updateRefreshToken')->andReturn(null); $this->session->shouldReceive('updateRefreshToken')->andReturn(null);
$a = $this->returnDefault(); $a = $this->returnDefault();
$a->addGrantType(new OAuth2\Grant\ClientCredentials()); $a->addGrantType(new OAuth2\Grant\ClientCredentials($a));
$v = $a->issueAccessToken(array( $v = $a->issueAccessToken(array(
'grant_type' => 'client_credentials', 'grant_type' => 'client_credentials',
@@ -106,8 +106,8 @@ class Client_Credentials_Grant_Test extends PHPUnit_Framework_TestCase
$this->assertArrayHasKey('expires', $v); $this->assertArrayHasKey('expires', $v);
$this->assertArrayHasKey('expires_in', $v); $this->assertArrayHasKey('expires_in', $v);
$this->assertEquals($a::getExpiresIn(), $v['expires_in']); $this->assertEquals($a->getExpiresIn(), $v['expires_in']);
$this->assertEquals(time()+$a::getExpiresIn(), $v['expires']); $this->assertEquals(time()+$a->getExpiresIn(), $v['expires']);
} }
function test_issueAccessToken_clientCredentialsGrant() function test_issueAccessToken_clientCredentialsGrant()
@@ -127,7 +127,7 @@ class Client_Credentials_Grant_Test extends PHPUnit_Framework_TestCase
$this->session->shouldReceive('updateRefreshToken')->andReturn(null); $this->session->shouldReceive('updateRefreshToken')->andReturn(null);
$a = $this->returnDefault(); $a = $this->returnDefault();
$a->addGrantType(new OAuth2\Grant\ClientCredentials()); $a->addGrantType(new OAuth2\Grant\ClientCredentials($a));
$_POST['grant_type'] = 'client_credentials'; $_POST['grant_type'] = 'client_credentials';
$_POST['client_id'] = 1234; $_POST['client_id'] = 1234;
@@ -143,8 +143,8 @@ class Client_Credentials_Grant_Test extends PHPUnit_Framework_TestCase
$this->assertArrayHasKey('expires', $v); $this->assertArrayHasKey('expires', $v);
$this->assertArrayHasKey('expires_in', $v); $this->assertArrayHasKey('expires_in', $v);
$this->assertEquals($a::getExpiresIn(), $v['expires_in']); $this->assertEquals($a->getExpiresIn(), $v['expires_in']);
$this->assertEquals(time()+$a::getExpiresIn(), $v['expires']); $this->assertEquals(time()+$a->getExpiresIn(), $v['expires']);
} }
function test_issueAccessToken_clientCredentialsGrant_withRefreshToken() function test_issueAccessToken_clientCredentialsGrant_withRefreshToken()
@@ -164,8 +164,8 @@ class Client_Credentials_Grant_Test extends PHPUnit_Framework_TestCase
$this->session->shouldReceive('updateRefreshToken')->andReturn(null); $this->session->shouldReceive('updateRefreshToken')->andReturn(null);
$a = $this->returnDefault(); $a = $this->returnDefault();
$a->addGrantType(new OAuth2\Grant\ClientCredentials()); $a->addGrantType(new OAuth2\Grant\ClientCredentials($a));
$a->addGrantType(new OAuth2\Grant\RefreshToken()); $a->addGrantType(new OAuth2\Grant\RefreshToken($a));
$_POST['grant_type'] = 'client_credentials'; $_POST['grant_type'] = 'client_credentials';
$_POST['client_id'] = 1234; $_POST['client_id'] = 1234;
@@ -182,8 +182,8 @@ class Client_Credentials_Grant_Test extends PHPUnit_Framework_TestCase
$this->assertArrayHasKey('expires_in', $v); $this->assertArrayHasKey('expires_in', $v);
$this->assertArrayHasKey('refresh_token', $v); $this->assertArrayHasKey('refresh_token', $v);
$this->assertEquals($a::getExpiresIn(), $v['expires_in']); $this->assertEquals($a->getExpiresIn(), $v['expires_in']);
$this->assertEquals(time()+$a::getExpiresIn(), $v['expires']); $this->assertEquals(time()+$a->getExpiresIn(), $v['expires']);
} }
} }

View File

@@ -27,7 +27,7 @@ class Password_Grant_Test extends PHPUnit_Framework_TestCase
public function test_issueAccessToken_passwordGrant_missingClientId() public function test_issueAccessToken_passwordGrant_missingClientId()
{ {
$a = $this->returnDefault(); $a = $this->returnDefault();
$a->addGrantType(new OAuth2\Grant\Password()); $a->addGrantType(new OAuth2\Grant\Password($a));
$request = new OAuth2\Util\Request(array(), $_POST); $request = new OAuth2\Util\Request(array(), $_POST);
$a->setRequest($request); $a->setRequest($request);
@@ -44,7 +44,7 @@ class Password_Grant_Test extends PHPUnit_Framework_TestCase
public function test_issueAccessToken_passwordGrant_missingClientPassword() public function test_issueAccessToken_passwordGrant_missingClientPassword()
{ {
$a = $this->returnDefault(); $a = $this->returnDefault();
$a->addGrantType(new OAuth2\Grant\Password()); $a->addGrantType(new OAuth2\Grant\Password($a));
$request = new OAuth2\Util\Request(array(), $_POST); $request = new OAuth2\Util\Request(array(), $_POST);
$a->setRequest($request); $a->setRequest($request);
@@ -64,7 +64,7 @@ class Password_Grant_Test extends PHPUnit_Framework_TestCase
$this->client->shouldReceive('getClient')->andReturn(false); $this->client->shouldReceive('getClient')->andReturn(false);
$a = $this->returnDefault(); $a = $this->returnDefault();
$a->addGrantType(new OAuth2\Grant\Password()); $a->addGrantType(new OAuth2\Grant\Password($a));
$request = new OAuth2\Util\Request(array(), $_POST); $request = new OAuth2\Util\Request(array(), $_POST);
$a->setRequest($request); $a->setRequest($request);
@@ -98,7 +98,7 @@ class Password_Grant_Test extends PHPUnit_Framework_TestCase
$testCredentials = null; $testCredentials = null;
$a = $this->returnDefault(); $a = $this->returnDefault();
$pgrant = new OAuth2\Grant\Password(); $pgrant = new OAuth2\Grant\Password($a);
$pgrant->setVerifyCredentialsCallback($testCredentials); $pgrant->setVerifyCredentialsCallback($testCredentials);
$a->addGrantType($pgrant); $a->addGrantType($pgrant);
@@ -134,7 +134,7 @@ class Password_Grant_Test extends PHPUnit_Framework_TestCase
$testCredentials = function($u, $p) { return false; }; $testCredentials = function($u, $p) { return false; };
$a = $this->returnDefault(); $a = $this->returnDefault();
$pgrant = new OAuth2\Grant\Password(); $pgrant = new OAuth2\Grant\Password($a);
$pgrant->setVerifyCredentialsCallback($testCredentials); $pgrant->setVerifyCredentialsCallback($testCredentials);
$a->addGrantType($pgrant); $a->addGrantType($pgrant);
@@ -168,7 +168,7 @@ class Password_Grant_Test extends PHPUnit_Framework_TestCase
$testCredentials = function($u, $p) { return false; }; $testCredentials = function($u, $p) { return false; };
$a = $this->returnDefault(); $a = $this->returnDefault();
$pgrant = new OAuth2\Grant\Password(); $pgrant = new OAuth2\Grant\Password($a);
$pgrant->setVerifyCredentialsCallback($testCredentials); $pgrant->setVerifyCredentialsCallback($testCredentials);
$a->addGrantType($pgrant); $a->addGrantType($pgrant);
@@ -203,7 +203,7 @@ class Password_Grant_Test extends PHPUnit_Framework_TestCase
$testCredentials = function($u, $p) { return false; }; $testCredentials = function($u, $p) { return false; };
$a = $this->returnDefault(); $a = $this->returnDefault();
$pgrant = new OAuth2\Grant\Password(); $pgrant = new OAuth2\Grant\Password($a);
$pgrant->setVerifyCredentialsCallback($testCredentials); $pgrant->setVerifyCredentialsCallback($testCredentials);
$a->addGrantType($pgrant); $a->addGrantType($pgrant);
@@ -216,6 +216,162 @@ class Password_Grant_Test extends PHPUnit_Framework_TestCase
)); ));
} }
/**
* @expectedException OAuth2\Exception\ClientException
* @expectedExceptionCode 4
*/
public function test_issueAccessToken_passwordGrant_badScopes()
{
$this->scope->shouldReceive('getScope')->andReturn(false);
$this->client->shouldReceive('getClient')->andReturn(array(
'client_id' => 1234,
'client_secret' => 5678,
'redirect_uri' => 'http://foo/redirect',
'name' => 'Example Client'
));
$this->client->shouldReceive('validateRefreshToken')->andReturn(1);
$this->session->shouldReceive('validateAuthCode')->andReturn(1);
$this->session->shouldReceive('createSession')->andReturn(1);
$this->session->shouldReceive('deleteSession')->andReturn(null);
$this->session->shouldReceive('updateRefreshToken')->andReturn(null);
$testCredentials = function($u, $p) { return 1; };
$a = $this->returnDefault();
$pgrant = new OAuth2\Grant\Password($a);
$pgrant->setVerifyCredentialsCallback($testCredentials);
$a->addGrantType($pgrant);
$v = $a->issueAccessToken(array(
'grant_type' => 'password',
'client_id' => 1234,
'client_secret' => 5678,
'username' => 'foo',
'password' => 'bar',
'scope' => 'blah'
));
}
/**
* @expectedException OAuth2\Exception\ClientException
* @expectedExceptionCode 0
*/
public function test_issueAccessToken_passwordGrant_missingScopes()
{
$this->client->shouldReceive('getClient')->andReturn(array(
'client_id' => 1234,
'client_secret' => 5678,
'redirect_uri' => 'http://foo/redirect',
'name' => 'Example Client'
));
$this->client->shouldReceive('validateRefreshToken')->andReturn(1);
$this->session->shouldReceive('validateAuthCode')->andReturn(1);
$this->session->shouldReceive('createSession')->andReturn(1);
$this->session->shouldReceive('deleteSession')->andReturn(null);
$this->session->shouldReceive('updateRefreshToken')->andReturn(null);
$testCredentials = function($u, $p) { return 1; };
$a = $this->returnDefault();
$pgrant = new OAuth2\Grant\Password($a);
$pgrant->setVerifyCredentialsCallback($testCredentials);
$a->addGrantType($pgrant);
$a->requireScopeParam(true);
$v = $a->issueAccessToken(array(
'grant_type' => 'password',
'client_id' => 1234,
'client_secret' => 5678,
'username' => 'foo',
'password' => 'bar'
));
}
public function test_issueAccessToken_passwordGrant_defaultScope()
{
$this->scope->shouldReceive('getScope')->andReturn(array(
'id' => 1,
'scope' => 'foo',
'name' => 'Foo Name',
'description' => 'Foo Name Description'
));
$this->client->shouldReceive('getClient')->andReturn(array(
'client_id' => 1234,
'client_secret' => 5678,
'redirect_uri' => 'http://foo/redirect',
'name' => 'Example Client'
));
$this->client->shouldReceive('validateRefreshToken')->andReturn(1);
$this->session->shouldReceive('validateAuthCode')->andReturn(1);
$this->session->shouldReceive('createSession')->andReturn(1);
$this->session->shouldReceive('deleteSession')->andReturn(null);
$this->session->shouldReceive('updateRefreshToken')->andReturn(null);
$this->session->shouldReceive('associateScope')->andReturn(null);
$testCredentials = function($u, $p) { return 1; };
$a = $this->returnDefault();
$pgrant = new OAuth2\Grant\Password($a);
$pgrant->setVerifyCredentialsCallback($testCredentials);
$a->addGrantType($pgrant);
$a->requireScopeParam(false);
$a->setDefaultScope('foobar');
$v = $a->issueAccessToken(array(
'grant_type' => 'password',
'client_id' => 1234,
'client_secret' => 5678,
'username' => 'foo',
'password' => 'bar',
'scope' => ''
));
}
public function test_issueAccessToken_passwordGrant_goodScope()
{
$this->scope->shouldReceive('getScope')->andReturn(array(
'id' => 1,
'scope' => 'foo',
'name' => 'Foo Name',
'description' => 'Foo Name Description'
));
$this->client->shouldReceive('getClient')->andReturn(array(
'client_id' => 1234,
'client_secret' => 5678,
'redirect_uri' => 'http://foo/redirect',
'name' => 'Example Client'
));
$this->client->shouldReceive('validateRefreshToken')->andReturn(1);
$this->session->shouldReceive('validateAuthCode')->andReturn(1);
$this->session->shouldReceive('createSession')->andReturn(1);
$this->session->shouldReceive('deleteSession')->andReturn(null);
$this->session->shouldReceive('updateRefreshToken')->andReturn(null);
$this->session->shouldReceive('associateScope')->andReturn(null);
$testCredentials = function($u, $p) { return 1; };
$a = $this->returnDefault();
$pgrant = new OAuth2\Grant\Password($a);
$pgrant->setVerifyCredentialsCallback($testCredentials);
$a->addGrantType($pgrant);
$v = $a->issueAccessToken(array(
'grant_type' => 'password',
'client_id' => 1234,
'client_secret' => 5678,
'username' => 'foo',
'password' => 'bar',
'scope' => 'blah'
));
}
function test_issueAccessToken_passwordGrant_passedInput() function test_issueAccessToken_passwordGrant_passedInput()
{ {
$this->client->shouldReceive('getClient')->andReturn(array( $this->client->shouldReceive('getClient')->andReturn(array(
@@ -235,9 +391,10 @@ class Password_Grant_Test extends PHPUnit_Framework_TestCase
$testCredentials = function($u, $p) { return 1; }; $testCredentials = function($u, $p) { return 1; };
$a = $this->returnDefault(); $a = $this->returnDefault();
$pgrant = new OAuth2\Grant\Password(); $pgrant = new OAuth2\Grant\Password($a);
$pgrant->setVerifyCredentialsCallback($testCredentials); $pgrant->setVerifyCredentialsCallback($testCredentials);
$a->addGrantType($pgrant); $a->addGrantType($pgrant);
$a->requireScopeParam(false);
$v = $a->issueAccessToken(array( $v = $a->issueAccessToken(array(
'grant_type' => 'password', 'grant_type' => 'password',
@@ -252,8 +409,8 @@ class Password_Grant_Test extends PHPUnit_Framework_TestCase
$this->assertArrayHasKey('expires', $v); $this->assertArrayHasKey('expires', $v);
$this->assertArrayHasKey('expires_in', $v); $this->assertArrayHasKey('expires_in', $v);
$this->assertEquals($a::getExpiresIn(), $v['expires_in']); $this->assertEquals($a->getExpiresIn(), $v['expires_in']);
$this->assertEquals(time()+$a::getExpiresIn(), $v['expires']); $this->assertEquals(time()+$a->getExpiresIn(), $v['expires']);
} }
function test_issueAccessToken_passwordGrant() function test_issueAccessToken_passwordGrant()
@@ -275,9 +432,10 @@ class Password_Grant_Test extends PHPUnit_Framework_TestCase
$testCredentials = function($u, $p) { return 1; }; $testCredentials = function($u, $p) { return 1; };
$a = $this->returnDefault(); $a = $this->returnDefault();
$pgrant = new OAuth2\Grant\Password(); $pgrant = new OAuth2\Grant\Password($a);
$pgrant->setVerifyCredentialsCallback($testCredentials); $pgrant->setVerifyCredentialsCallback($testCredentials);
$a->addGrantType($pgrant); $a->addGrantType($pgrant);
$a->requireScopeParam(false);
$_POST['grant_type'] = 'password'; $_POST['grant_type'] = 'password';
$_POST['client_id'] = 1234; $_POST['client_id'] = 1234;
@@ -295,8 +453,8 @@ class Password_Grant_Test extends PHPUnit_Framework_TestCase
$this->assertArrayHasKey('expires', $v); $this->assertArrayHasKey('expires', $v);
$this->assertArrayHasKey('expires_in', $v); $this->assertArrayHasKey('expires_in', $v);
$this->assertEquals($a::getExpiresIn(), $v['expires_in']); $this->assertEquals($a->getExpiresIn(), $v['expires_in']);
$this->assertEquals(time()+$a::getExpiresIn(), $v['expires']); $this->assertEquals(time()+$a->getExpiresIn(), $v['expires']);
} }
function test_issueAccessToken_passwordGrant_withRefreshToken() function test_issueAccessToken_passwordGrant_withRefreshToken()
@@ -318,10 +476,11 @@ class Password_Grant_Test extends PHPUnit_Framework_TestCase
$testCredentials = function($u, $p) { return 1; }; $testCredentials = function($u, $p) { return 1; };
$a = $this->returnDefault(); $a = $this->returnDefault();
$pgrant = new OAuth2\Grant\Password(); $pgrant = new OAuth2\Grant\Password($a);
$pgrant->setVerifyCredentialsCallback($testCredentials); $pgrant->setVerifyCredentialsCallback($testCredentials);
$a->addGrantType($pgrant); $a->addGrantType($pgrant);
$a->addGrantType(new OAuth2\Grant\RefreshToken()); $a->addGrantType(new OAuth2\Grant\RefreshToken($a));
$a->requireScopeParam(false);
$_POST['grant_type'] = 'password'; $_POST['grant_type'] = 'password';
$_POST['client_id'] = 1234; $_POST['client_id'] = 1234;
@@ -340,8 +499,8 @@ class Password_Grant_Test extends PHPUnit_Framework_TestCase
$this->assertArrayHasKey('expires_in', $v); $this->assertArrayHasKey('expires_in', $v);
$this->assertArrayHasKey('refresh_token', $v); $this->assertArrayHasKey('refresh_token', $v);
$this->assertEquals($a::getExpiresIn(), $v['expires_in']); $this->assertEquals($a->getExpiresIn(), $v['expires_in']);
$this->assertEquals(time()+$a::getExpiresIn(), $v['expires']); $this->assertEquals(time()+$a->getExpiresIn(), $v['expires']);
} }
} }

View File

@@ -33,8 +33,8 @@ class Refresh_Token_test extends PHPUnit_Framework_TestCase
$this->session->shouldReceive('updateSession')->andReturn(null); $this->session->shouldReceive('updateSession')->andReturn(null);
$a = $this->returnDefault(); $a = $this->returnDefault();
$a->addGrantType(new OAuth2\Grant\AuthCode()); $a->addGrantType(new OAuth2\Grant\AuthCode($a));
$a->addGrantType(new OAuth2\Grant\RefreshToken()); $a->addGrantType(new OAuth2\Grant\RefreshToken($a));
$_POST['grant_type'] = 'authorization_code'; $_POST['grant_type'] = 'authorization_code';
$_POST['client_id'] = 1234; $_POST['client_id'] = 1234;
@@ -53,8 +53,8 @@ class Refresh_Token_test extends PHPUnit_Framework_TestCase
$this->assertArrayHasKey('expires_in', $v); $this->assertArrayHasKey('expires_in', $v);
$this->assertArrayHasKey('refresh_token', $v); $this->assertArrayHasKey('refresh_token', $v);
$this->assertEquals($a::getExpiresIn(), $v['expires_in']); $this->assertEquals($a->getExpiresIn(), $v['expires_in']);
$this->assertEquals(time()+$a::getExpiresIn(), $v['expires']); $this->assertEquals(time()+$a->getExpiresIn(), $v['expires']);
} }
/** /**
@@ -64,7 +64,7 @@ class Refresh_Token_test extends PHPUnit_Framework_TestCase
public function test_issueAccessToken_refreshTokenGrant_missingClientId() public function test_issueAccessToken_refreshTokenGrant_missingClientId()
{ {
$a = $this->returnDefault(); $a = $this->returnDefault();
$a->addGrantType(new OAuth2\Grant\RefreshToken()); $a->addGrantType(new OAuth2\Grant\RefreshToken($a));
$request = new OAuth2\Util\Request(array(), $_POST); $request = new OAuth2\Util\Request(array(), $_POST);
$a->setRequest($request); $a->setRequest($request);
@@ -81,7 +81,7 @@ class Refresh_Token_test extends PHPUnit_Framework_TestCase
public function test_issueAccessToken_refreshTokenGrant_missingClientSecret() public function test_issueAccessToken_refreshTokenGrant_missingClientSecret()
{ {
$a = $this->returnDefault(); $a = $this->returnDefault();
$a->addGrantType(new OAuth2\Grant\RefreshToken()); $a->addGrantType(new OAuth2\Grant\RefreshToken($a));
$request = new OAuth2\Util\Request(array(), $_POST); $request = new OAuth2\Util\Request(array(), $_POST);
$a->setRequest($request); $a->setRequest($request);
@@ -101,7 +101,7 @@ class Refresh_Token_test extends PHPUnit_Framework_TestCase
$this->client->shouldReceive('getClient')->andReturn(false); $this->client->shouldReceive('getClient')->andReturn(false);
$a = $this->returnDefault(); $a = $this->returnDefault();
$a->addGrantType(new OAuth2\Grant\RefreshToken()); $a->addGrantType(new OAuth2\Grant\RefreshToken($a));
$request = new OAuth2\Util\Request(array(), $_POST); $request = new OAuth2\Util\Request(array(), $_POST);
$a->setRequest($request); $a->setRequest($request);
@@ -122,7 +122,7 @@ class Refresh_Token_test extends PHPUnit_Framework_TestCase
$this->client->shouldReceive('getClient')->andReturn(array()); $this->client->shouldReceive('getClient')->andReturn(array());
$a = $this->returnDefault(); $a = $this->returnDefault();
$a->addGrantType(new OAuth2\Grant\RefreshToken()); $a->addGrantType(new OAuth2\Grant\RefreshToken($a));
$request = new OAuth2\Util\Request(array(), $_POST); $request = new OAuth2\Util\Request(array(), $_POST);
$a->setRequest($request); $a->setRequest($request);
@@ -145,7 +145,7 @@ class Refresh_Token_test extends PHPUnit_Framework_TestCase
$this->client->shouldReceive('validateRefreshToken')->andReturn(false); $this->client->shouldReceive('validateRefreshToken')->andReturn(false);
$a = $this->returnDefault(); $a = $this->returnDefault();
$a->addGrantType(new OAuth2\Grant\RefreshToken()); $a->addGrantType(new OAuth2\Grant\RefreshToken($a));
$request = new OAuth2\Util\Request(array(), $_POST); $request = new OAuth2\Util\Request(array(), $_POST);
$a->setRequest($request); $a->setRequest($request);
@@ -174,7 +174,7 @@ class Refresh_Token_test extends PHPUnit_Framework_TestCase
$this->session->shouldReceive('updateRefreshToken')->andReturn(null); $this->session->shouldReceive('updateRefreshToken')->andReturn(null);
$a = $this->returnDefault(); $a = $this->returnDefault();
$a->addGrantType(new OAuth2\Grant\RefreshToken()); $a->addGrantType(new OAuth2\Grant\RefreshToken($a));
$_POST['grant_type'] = 'refresh_token'; $_POST['grant_type'] = 'refresh_token';
$_POST['client_id'] = 1234; $_POST['client_id'] = 1234;
@@ -192,8 +192,8 @@ class Refresh_Token_test extends PHPUnit_Framework_TestCase
$this->assertArrayHasKey('expires_in', $v); $this->assertArrayHasKey('expires_in', $v);
$this->assertArrayHasKey('refresh_token', $v); $this->assertArrayHasKey('refresh_token', $v);
$this->assertEquals($a::getExpiresIn(), $v['expires_in']); $this->assertEquals($a->getExpiresIn(), $v['expires_in']);
$this->assertEquals(time()+$a::getExpiresIn(), $v['expires']); $this->assertEquals(time()+$a->getExpiresIn(), $v['expires']);
} }
public function test_issueAccessToken_refreshTokenGrant() public function test_issueAccessToken_refreshTokenGrant()
@@ -212,7 +212,7 @@ class Refresh_Token_test extends PHPUnit_Framework_TestCase
$this->session->shouldReceive('updateRefreshToken')->andReturn(null); $this->session->shouldReceive('updateRefreshToken')->andReturn(null);
$a = $this->returnDefault(); $a = $this->returnDefault();
$a->addGrantType(new OAuth2\Grant\RefreshToken()); $a->addGrantType(new OAuth2\Grant\RefreshToken($a));
$v = $a->issueAccessToken(array( $v = $a->issueAccessToken(array(
'grant_type' => 'refresh_token', 'grant_type' => 'refresh_token',
@@ -227,7 +227,7 @@ class Refresh_Token_test extends PHPUnit_Framework_TestCase
$this->assertArrayHasKey('expires_in', $v); $this->assertArrayHasKey('expires_in', $v);
$this->assertArrayHasKey('refresh_token', $v); $this->assertArrayHasKey('refresh_token', $v);
$this->assertEquals($a::getExpiresIn(), $v['expires_in']); $this->assertEquals($a->getExpiresIn(), $v['expires_in']);
$this->assertEquals(time()+$a::getExpiresIn(), $v['expires']); $this->assertEquals(time()+$a->getExpiresIn(), $v['expires']);
} }
} }

View File

@@ -85,7 +85,7 @@ class Resource_Server_test extends PHPUnit_Framework_TestCase
$param = $requestReflector->getProperty('headers'); $param = $requestReflector->getProperty('headers');
$param->setAccessible(true); $param->setAccessible(true);
$param->setValue($request, array( $param->setValue($request, array(
'Authorization' => 'Bearer YWJjZGVm' 'Authorization' => 'Bearer abcdef'
)); ));
$s = $this->returnDefault(); $s = $this->returnDefault();
$s->setRequest($request); $s->setRequest($request);
@@ -131,7 +131,7 @@ class Resource_Server_test extends PHPUnit_Framework_TestCase
$param = $requestReflector->getProperty('headers'); $param = $requestReflector->getProperty('headers');
$param->setAccessible(true); $param->setAccessible(true);
$param->setValue($request, array( $param->setValue($request, array(
'Authorization' => 'Bearer YWJjZGVm' 'Authorization' => 'Bearer abcdef'
)); ));
$s = $this->returnDefault(); $s = $this->returnDefault();
$s->setRequest($request); $s->setRequest($request);
@@ -153,7 +153,7 @@ class Resource_Server_test extends PHPUnit_Framework_TestCase
$param = $requestReflector->getProperty('headers'); $param = $requestReflector->getProperty('headers');
$param->setAccessible(true); $param->setAccessible(true);
$param->setValue($request, array( $param->setValue($request, array(
'Authorization' => 'Bearer YWJjZGVm' 'Authorization' => 'Bearer abcdef'
)); ));
$s = $this->returnDefault(); $s = $this->returnDefault();
$s->setRequest($request); $s->setRequest($request);