Compare commits

...

56 Commits
0.3 ... 0.4.1

Author SHA1 Message Date
Alex Bilbie
b4e8c27618 Merge branch 'release/0.4.1' 2013-01-02 22:36:48 +00:00
Alex Bilbie
d65cdaf028 Version bump 2013-01-02 22:36:41 +00:00
Alex Bilbie
5f1779c4e7 Autoload dependencies with autoloader in bootstrap.php 2013-01-02 22:32:49 +00:00
Alex Bilbie
b10613c5e3 Composer install 2013-01-02 21:31:33 +00:00
Alex Bilbie
1c3b319aa6 Altered the script parameter of .travis.yml 2013-01-02 21:22:09 +00:00
Alex Bilbie
1069507ab4 Revert require_once statements 2013-01-02 21:13:32 +00:00
Alex Bilbie
5ca63c921a Updated PHPUnit.xml 2013-01-02 21:13:12 +00:00
Alex Bilbie
943fc1cc82 Possible fix for Travis? 2013-01-02 20:34:09 +00:00
Alex Bilbie
a158883aed Another attempt to fix paths for travis 2013-01-02 20:32:38 +00:00
Alex Bilbie
8aba2b29b8 Better travis debugging 2013-01-02 20:24:45 +00:00
Alex Bilbie
b5e8f9206b Fool. 2013-01-02 20:21:25 +00:00
Alex Bilbie
755a753cb5 Test include path on travis 2013-01-02 20:19:26 +00:00
Alex Bilbie
e99211db31 Moved require_once statement outside of setUp tests method 2013-01-02 20:13:02 +00:00
Alex Bilbie
1142f8d86b Merge branch 'release/0.4' into develop 2013-01-02 19:17:12 +00:00
Alex Bilbie
5772a2f12f Merge branch 'release/0.4' 2013-01-02 19:17:01 +00:00
Alex Bilbie
f351cea442 Version bump 2013-01-02 19:16:51 +00:00
Alex Bilbie
2e1f1c05cf Updated README 2013-01-02 19:16:16 +00:00
Alex Bilbie
7279c8675b Merge branch 'feature/grants' into develop 2013-01-02 19:14:33 +00:00
Alex Bilbie
94945ec49e Added support for refresh tokens, user credentials and client credentials grant. 100% unit test code coverage for authentication. Fixes #2 2013-01-02 19:14:22 +00:00
Alex Bilbie
2b8a27ef47 Ignore code coverage in ../tests folder 2013-01-02 19:12:53 +00:00
Alex Bilbie
7d1aa28087 Added .travis.yml 2012-12-30 21:31:19 +00:00
Alex Bilbie
0fcbeb8158 PSR fixes 2012-12-23 22:13:22 +00:00
Alex Bilbie
0876fd9ad3 Spacing fixes 2012-12-23 22:12:51 +00:00
Alex Bilbie
2545ea7dc1 Added refresh token params and examples 2012-12-23 22:12:44 +00:00
Alex Bilbie
6eeb7e13e4 Updated unit tests 2012-12-23 22:11:33 +00:00
Alex Bilbie
38c50c00b0 PSR fixes 2012-12-23 21:39:42 +00:00
Alex Bilbie
df85c98e53 PSR fixes 2012-12-23 21:36:30 +00:00
Alex Bilbie
0f30b2a803 Removed lots of unnecessary if/else blocks.
Removed null value of expires/expiresIn parameter
2012-12-23 21:21:37 +00:00
Alex Bilbie
f2dc89cdf3 Merge remote-tracking branch 'dhorrigan/master' into feature/grants 2012-12-23 20:34:21 +00:00
Alex Bilbie
c676ba9857 Merge remote-tracking branch 'origin/develop' into develop 2012-12-23 20:33:42 +00:00
Alex Bilbie
d99e871e11 Set a default token ttl of one hour 2012-12-23 20:31:16 +00:00
Daniel Horrigan
0f6f5e2939 Added the user_credentials and refresh_token grants. Fixed expires_in so it is inline with the spec, but added expires for the old usage of expires_in. Made redirect_uri in oauth_sessions ALLOW NULL since user_credential grants don't have a redirect 2012-12-19 16:12:48 -05:00
Alex Bilbie
9fd6f309df Merge branch 'release/0.3.5' into develop 2012-12-12 11:45:07 +00:00
Alex Bilbie
41d8a1efa3 Merge branch 'release/0.3.5' 2012-12-12 11:44:56 +00:00
Alex Bilbie
4928221b49 Version bump 2012-12-12 11:44:51 +00:00
Alex Bilbie
8131d5be90 Merge branch 'hotfix/resourceConfig' into develop 2012-12-12 11:44:04 +00:00
Alex Bilbie
a948335e45 Merge branch 'hotfix/resourceConfig' 2012-12-12 11:43:11 +00:00
Alex Bilbie
aa978d3581 Fix variable name 2012-12-12 11:43:01 +00:00
Alex Bilbie
b1d91f33cf Merge branch 'release/0.3.4' into develop 2012-12-11 15:33:20 +00:00
Alex Bilbie
1be25955d6 Merge branch 'release/0.3.4' 2012-12-11 15:33:05 +00:00
Alex Bilbie
3365953257 Version bump 2012-12-11 15:32:27 +00:00
Alex Bilbie
302bf1f70d Clean trailing whitespace 2012-12-11 15:31:42 +00:00
Alex Bilbie
6553fb3f22 Return client details 2012-12-11 12:09:56 +00:00
Alex Bilbie
fdfe80289a Merge branch 'release/0.3.3'. Release version 0.3.3
Conflicts:
	composer.json
2012-12-10 21:31:58 +00:00
Alex Bilbie
0ed6674ceb Version bump. Fixed website 2012-12-10 21:31:08 +00:00
Alex Bilbie
912cd3fa25 Changed session stage to 'requested' as per enum 2012-12-10 21:19:11 +00:00
Alex Bilbie
1b29c0f1a0 Merge branch 'release/0.3.2' into develop 2012-11-20 15:30:02 +00:00
Alex Bilbie
a5b83c00bd Version bump 2012-11-20 15:29:43 +00:00
Alex Bilbie
129c9a7b7a Version bump 2012-11-20 15:28:48 +00:00
Alex Bilbie
958eab33a7 Lots of small documentation updates and clarifications 2012-11-20 15:27:33 +00:00
Alex Bilbie
fead044830 Spacing fixes and fixed sessionScopes() example query 2012-11-20 15:27:15 +00:00
Alex Bilbie
21f48c0491 Spacing updates 2012-11-20 15:26:04 +00:00
Alex Bilbie
ac990b609a Fixed client_id column length 2012-11-16 16:40:01 +00:00
Alex Bilbie
e5bbd41570 Version bump
Signed-off-by: Alex Bilbie <alex@alexbilbie.com>
2012-10-14 17:33:46 +01:00
Alex Bilbie
99f54d1a02 Missing provider class
Signed-off-by: Alex Bilbie <alex@alexbilbie.com>
2012-10-14 17:33:22 +01:00
Alex Bilbie
b2188514d9 Merge branch 'release/0.3' into develop 2012-10-14 17:21:04 +01:00
14 changed files with 1670 additions and 867 deletions

8
.travis.yml Normal file
View File

@@ -0,0 +1,8 @@
language: php
php:
- 5.3
- 5.4
before_script: composer install
script: phpunit -c build/phpunit.xml

View File

@@ -22,7 +22,12 @@ Check out the [wiki](https://github.com/lncd/OAuth2/wiki)
### Authentication Server
The authentication server is a flexible class that supports the standard authorization code grant.
The authentication server is a flexible class that supports the following grants:
* authentication code
* refresh token
* client credentials
* password (user credentials)
### Resource Server

View File

@@ -1,5 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit colors="true" convertNoticesToExceptions="true" convertWarningsToExceptions="true" stopOnError="false" stopOnFailure="false" stopOnIncomplete="false" stopOnSkipped="false">
<phpunit colors="true" convertNoticesToExceptions="true" convertWarningsToExceptions="true" stopOnError="false" stopOnFailure="false" stopOnIncomplete="false" stopOnSkipped="false" bootstrap="../tests/Bootstrap.php">
<testsuites>
<testsuite name="Authentication Server">
<directory suffix="test.php">../tests/authentication</directory>
@@ -13,10 +13,12 @@
<directory suffix=".php">PEAR_INSTALL_DIR</directory>
<directory suffix=".php">PHP_LIBDIR</directory>
<directory suffix=".php">../vendor/composer</directory>
<directory suffix=".php">../tests</directory>
</blacklist>
</filter>
<logging>
<log type="coverage-html" target="coverage" title="lncd/OAuth" charset="UTF-8" yui="true" highlight="true" lowUpperBound="35" highLowerBound="70"/>
<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>

View File

@@ -1,7 +1,7 @@
{
"name": "lncd/oauth2",
"description": "OAuth 2.0 Framework",
"version": "0.3",
"version": "0.4.1",
"homepage": "https://github.com/lncd/OAuth2",
"license": "MIT",
"require": {
@@ -29,7 +29,7 @@
{
"name": "Alex Bilbie",
"email": "hello@alexbilbie.com",
"homepage": "http://www.httpster.org",
"homepage": "http://www.alexbilbie.com",
"role": "Developer"
}
],

View File

@@ -20,12 +20,13 @@ CREATE TABLE `client_endpoints` (
-- Create syntax for TABLE 'oauth_sessions'
CREATE TABLE `oauth_sessions` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`client_id` varchar(32) NOT NULL DEFAULT '',
`redirect_uri` varchar(250) NOT NULL DEFAULT '',
`client_id` varchar(40) NOT NULL DEFAULT '',
`redirect_uri` varchar(250) DEFAULT '',
`owner_type` enum('user','client') NOT NULL DEFAULT 'user',
`owner_id` varchar(255) DEFAULT NULL,
`auth_code` varchar(40) DEFAULT '',
`access_token` varchar(40) DEFAULT '',
`refresh_token` varchar(40) NOT NULL,
`access_token_expires` int(10) DEFAULT NULL,
`stage` enum('requested','granted') NOT NULL DEFAULT 'requested',
`first_requested` int(10) unsigned NOT NULL,

View File

@@ -26,10 +26,22 @@ interface Database
* $redirectUri
* </code>
*
* Response:
*
* <code>
* Array
* (
* [client_id] => (string) The client ID
* [client secret] => (string) The client secret
* [redirect_uri] => (string) The redirect URI used in this request
* [name] => (string) The name of the client
* )
* </code>
*
* @param string $clientId The client's ID
* @param string $clientSecret The client's secret (default = "null")
* @param string $redirectUri The client's redirect URI (default = "null")
* @return [type] [description]
* @return bool|array Returns false if the validation fails, array on success
*/
public function validateClient(
$clientId,
@@ -44,8 +56,8 @@ interface Database
*
* <code>
* INSERT INTO oauth_sessions (client_id, redirect_uri, owner_type,
* owner_id, auth_code, access_token, stage, first_requested, last_updated)
* VALUES ($clientId, $redirectUri, $type, $typeId, $authCode,
* owner_id, auth_code, access_token, refresh_token, stage, first_requested,
* last_updated) VALUES ($clientId, $redirectUri, $type, $typeId, $authCode,
* $accessToken, $stage, UNIX_TIMESTAMP(NOW()), UNIX_TIMESTAMP(NOW()))
* </code>
*
@@ -55,8 +67,9 @@ interface Database
* @param string $typeId The session owner's ID (default = "null")
* @param string $authCode The authorisation code (default = "null")
* @param string $accessToken The access token (default = "null")
* @param string $refreshToken The refresh token (default = "null")
* @param string $stage The stage of the session (default ="request")
* @return [type] [description]
* @return int The session ID
*/
public function newSession(
$clientId,
@@ -65,6 +78,7 @@ interface Database
$typeId = null,
$authCode = null,
$accessToken = null,
$refreshToken = null,
$accessTokenExpire = null,
$stage = 'requested'
);
@@ -83,6 +97,7 @@ interface Database
* @param string $sessionId The session ID
* @param string $authCode The authorisation code (default = "null")
* @param string $accessToken The access token (default = "null")
* @param string $refreshToken The refresh token (default = "null")
* @param string $stage The stage of the session (default ="request")
* @return void
*/
@@ -90,6 +105,7 @@ interface Database
$sessionId,
$authCode = null,
$accessToken = null,
$refreshToken = null,
$accessTokenExpire = null,
$stage = 'requested'
);
@@ -105,7 +121,7 @@ interface Database
* @param string $clientId The client ID
* @param string $type The session owner's type
* @param string $typeId The session owner's ID
* @return [type] [description]
* @return void
*/
public function deleteSession(
$clientId,
@@ -113,6 +129,27 @@ interface Database
$typeId
);
public function validateRefreshToken($refreshToken, $clientId);
/**
* Update the refresh token
*
* Database query:
*
* <code>
* UPDATE oauth_sessions SET access_token = $newAccessToken, refresh_token =
* $newRefreshToken, access_toke_expires = $accessTokenExpires, last_updated = UNIX_TIMESTAMP(NOW()) WHERE
* id = $sessionId
* </code>
*
* @param string $sessionId The session ID
* @param string $newAccessToken The new access token for this session
* @param string $newRefreshToken The new refresh token for the session
* @param int $accessTokenExpires The UNIX timestamp of when the new token expires
* @return void
*/
public function updateRefreshToken($sessionId, $newAccessToken, $newRefreshToken, $accessTokenExpires);
/**
* Validate that an authorisation code is valid
*

View File

@@ -31,7 +31,7 @@ class Server
*/
private $_config = array(
'scope_delimeter' => ',',
'access_token_ttl' => null
'access_token_ttl' => 3600
);
/**
@@ -47,7 +47,14 @@ class Server
* @var array
*/
private $_grantTypes = array(
'authorization_code'
'authorization_code' => false,
'client_credentials' => false,
'password' => false,
'refresh_token' => false,
);
private $_grantTypeCallbacks = array(
'password' => null
);
/**
@@ -82,9 +89,11 @@ class Server
'invalid_scope' => 'The requested scope is invalid, unknown, or malformed. Check the "%s" scope.',
'server_error' => 'The authorization server encountered an unexpected condition which prevented it from fulfilling the request.',
'temporarily_unavailable' => 'The authorization server is currently unable to handle the request due to a temporary overloading or maintenance of the server.',
'unsupported_grant_type' => 'The authorization grant type is not supported by the authorization server',
'unsupported_grant_type' => 'The authorization grant type "%s" is not supported by the authorization server',
'invalid_client' => 'Client authentication failed',
'invalid_grant' => 'The provided authorization grant is invalid, expired, revoked, does not match the redirection URI used in the authorization request, or was issued to another client. Check the "%s" parameter.'
'invalid_grant' => 'The provided authorization grant is invalid, expired, revoked, does not match the redirection URI used in the authorization request, or was issued to another client. Check the "%s" parameter.',
'invalid_credentials' => 'The user credentials were incorrect.',
'invalid_refresh' => 'The refresh token is invalid.',
);
/**
@@ -97,7 +106,7 @@ class Server
public function __construct($options = null)
{
if ($options !== null) {
$this->options = array_merge($this->_config, $options);
$this->_config = array_merge($this->_config, $options);
}
}
@@ -113,6 +122,27 @@ class Server
$this->_db = $db;
}
/**
* Enable a grant type
*
* @access public
* @return void
*/
public function enableGrantType($type, $callback = null)
{
if (isset($this->_grantTypes[$type])) {
$this->_grantTypes[$type] = true;
}
if (in_array($type, array_keys($this->_grantTypeCallbacks))) {
if (is_null($callback) || ! is_callable($callback)) {
throw new ServerException('No registered callback function for grant type `'.$type.'`');
}
$this->_grantTypeCallbacks[$type] = $callback;
}
}
/**
* Check client authorise parameters
*
@@ -126,30 +156,22 @@ class Server
// Client ID
if ( ! isset($authParams['client_id']) && ! isset($_GET['client_id'])) {
throw new ClientException(sprintf($this->errors['invalid_request'], 'client_id'), 0);
} else {
}
$params['client_id'] = (isset($authParams['client_id'])) ?
$authParams['client_id'] :
$_GET['client_id'];
}
// Redirect URI
if ( ! isset($authParams['redirect_uri']) && ! isset($_GET['redirect_uri'])) {
throw new ClientException(sprintf($this->errors['invalid_request'], 'redirect_uri'), 0);
} else {
}
$params['redirect_uri'] = (isset($authParams['redirect_uri'])) ?
$authParams['redirect_uri'] :
$_GET['redirect_uri'];
}
// Validate client ID and redirect URI
$clientDetails = $this->_dbCall(
'validateClient',
@@ -159,16 +181,15 @@ class Server
);
if ($clientDetails === false) {
throw new ClientException($this->errors['invalid_client'], 8);
}
$params['client_details'] = $clientDetails;
// Response type
if ( ! isset($authParams['response_type']) && ! isset($_GET['response_type'])) {
throw new ClientException(sprintf($this->errors['invalid_request'], 'response_type'), 0);
} else {
}
$params['response_type'] = (isset($authParams['response_type'])) ?
$authParams['response_type'] :
@@ -176,10 +197,7 @@ class Server
// Ensure response type is one that is recognised
if ( ! in_array($params['response_type'], $this->_responseTypes)) {
throw new ClientException($this->errors['unsupported_response_type'], 3);
}
}
// Get and validate scopes
@@ -202,7 +220,6 @@ class Server
}
if (count($scopes) === 0) {
throw new ClientException(sprintf($this->errors['invalid_request'], 'scope'), 0);
}
@@ -216,9 +233,7 @@ class Server
);
if ($scopeDetails === false) {
throw new ClientException(sprintf($this->errors['invalid_scope'], $scope), 4);
}
$params['scopes'][] = $scopeDetails;
@@ -248,7 +263,7 @@ class Server
);
// Create the new auth code
$authCode = $this->newAuthCode(
$authCode = $this->_newAuthCode(
$authoriseParams['client_id'],
'user',
$typeId,
@@ -266,7 +281,7 @@ class Server
*
* @return string A unique code
*/
private function generateCode()
private function _generateCode()
{
return sha1(uniqid(microtime()));
}
@@ -282,25 +297,9 @@ class Server
* @param string $accessToken The access token (default = null)
* @return string An authorisation code
*/
private function newAuthCode($clientId, $type, $typeId, $redirectUri, $scopes = array(), $accessToken = null)
private function _newAuthCode($clientId, $type, $typeId, $redirectUri, $scopes = array())
{
$authCode = $this->generateCode();
// If an access token exists then update the existing session with the
// new authorisation code otherwise create a new session
if ($accessToken !== null) {
$this->_dbCall(
'updateSession',
$clientId,
$type,
$typeId,
$authCode,
$accessToken,
'request'
);
} else {
$authCode = $this->_generateCode();
// Delete any existing sessions just to be sure
$this->_dbCall('deleteSession', $clientId, $type, $typeId);
@@ -315,7 +314,7 @@ class Server
$authCode,
null,
null,
'request'
'requested'
);
// Add the scopes
@@ -329,8 +328,6 @@ class Server
}
}
return $authCode;
}
@@ -345,40 +342,43 @@ class Server
*/
public function issueAccessToken($authParams = null)
{
$params = array();
if ( ! isset($authParams['grant_type']) && ! isset($_POST['grant_type'])) {
throw new ClientException(sprintf($this->errors['invalid_request'], 'grant_type'), 0);
} else {
}
$params['grant_type'] = (isset($authParams['grant_type'])) ?
$authParams['grant_type'] :
$_POST['grant_type'];
// Ensure grant type is one that is recognised
if ( ! in_array($params['grant_type'], $this->_grantTypes)) {
throw new ClientException($this->errors['unsupported_grant_type'], 7);
}
// Ensure grant type is one that is recognised and is enabled
if ( ! in_array($params['grant_type'], array_keys($this->_grantTypes)) || $this->_grantTypes[$params['grant_type']] !== true) {
throw new ClientException(sprintf($this->errors['unsupported_grant_type'], $params['grant_type']), 7);
}
switch ($params['grant_type'])
{
case 'authorization_code': // Authorization code grant
return $this->completeAuthCodeGrant($authParams, $params);
return $this->_completeAuthCodeGrant($authParams, $params);
break;
case 'refresh_token': // Refresh token
case 'password': // Resource owner password credentials grant
case 'client_credentials': // Client credentials grant
return $this->_completeClientCredentialsGrant($authParams, $params);
break;
case 'password': // Resource owner password credentials grant
return $this->_completeUserCredentialsGrant($authParams, $params);
break;
case 'refresh_token': // Refresh token grant
return $this->_completeRefreshTokenGrant($authParams, $params);
break;
// @codeCoverageIgnoreStart
default: // Unsupported
throw new ServerException($this->errors['server_error'] . 'Tried to process an unsuppported grant type.', 5);
break;
}
// @codeCoverageIgnoreEnd
}
/**
@@ -391,47 +391,35 @@ class Server
*
* @return array Authorise request parameters
*/
private function completeAuthCodeGrant($authParams = array(), $params = array())
private function _completeAuthCodeGrant($authParams = array(), $params = array())
{
// Client ID
if ( ! isset($authParams['client_id']) && ! isset($_POST['client_id'])) {
throw new ClientException(sprintf($this->errors['invalid_request'], 'client_id'), 0);
} else {
}
$params['client_id'] = (isset($authParams['client_id'])) ?
$authParams['client_id'] :
$_POST['client_id'];
}
// Client secret
if ( ! isset($authParams['client_secret']) && ! isset($_POST['client_secret'])) {
throw new ClientException(sprintf($this->errors['invalid_request'], 'client_secret'), 0);
} else {
}
$params['client_secret'] = (isset($authParams['client_secret'])) ?
$authParams['client_secret'] :
$_POST['client_secret'];
}
// Redirect URI
if ( ! isset($authParams['redirect_uri']) && ! isset($_POST['redirect_uri'])) {
throw new ClientException(sprintf($this->errors['invalid_request'], 'redirect_uri'), 0);
} else {
}
$params['redirect_uri'] = (isset($authParams['redirect_uri'])) ?
$authParams['redirect_uri'] :
$_POST['redirect_uri'];
}
// Validate client ID and redirect URI
$clientDetails = $this->_dbCall(
'validateClient',
@@ -441,25 +429,19 @@ class Server
);
if ($clientDetails === false) {
throw new ClientException($this->errors['invalid_client'], 8);
}
// The authorization code
if ( ! isset($authParams['code']) && ! isset($_POST['code'])) {
throw new ClientException(sprintf($this->errors['invalid_request'], 'code'), 0);
} else {
}
$params['code'] = (isset($authParams['code'])) ?
$authParams['code'] :
$_POST['code'];
}
// 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 = $this->_dbCall(
'validateAuthCode',
$params['client_id'],
@@ -468,25 +450,26 @@ class Server
);
if ( ! $session) {
throw new ClientException(sprintf($this->errors['invalid_grant'], 'code'), 9);
} else {
}
// A session ID was returned so update it with an access token,
// remove the authorisation code, change the stage to 'granted'
$accessToken = $this->generateCode();
$accessToken = $this->_generateCode();
$refreshToken = ($this->_grantTypes['refresh_token']) ?
$this->_generateCode() :
null;
$accessTokenExpires = ($this->_config['access_token_ttl'] === null) ?
null :
time() + $this->_config['access_token_ttl'];
$accessTokenExpires = time() + $this->_config['access_token_ttl'];
$accessTokenExpiresIn = $this->_config['access_token_ttl'];
$this->_dbCall(
'updateSession',
$session['id'],
null,
$accessToken,
$refreshToken,
$accessTokenExpires,
'granted'
);
@@ -495,16 +478,279 @@ class Server
$this->_dbCall(
'updateSessionScopeAccessToken',
$session['id'],
$accessToken
$accessToken,
$refreshToken
);
$response = array(
'access_token' => $accessToken,
'token_type' => 'bearer',
'expires' => $accessTokenExpires,
'expires_in' => $accessTokenExpiresIn
);
if ($this->_grantTypes['refresh_token']) {
$response['refresh_token'] = $refreshToken;
}
return $response;
}
/**
* Complete the resource owner password credentials grant
*
* @access private
* @param array $authParams Array of parsed $_POST keys
* @param array $params Generated parameters from issueAccessToken()
* @return array Authorise request parameters
*/
private function _completeClientCredentialsGrant($authParams = array(), $params = array())
{
// Client ID
if ( ! isset($authParams['client_id']) && ! isset($_POST['client_id'])) {
// @codeCoverageIgnoreStart
throw new ClientException(sprintf($this->errors['invalid_request'], 'client_id'), 0);
// @codeCoverageIgnoreEnd
}
$params['client_id'] = (isset($authParams['client_id'])) ?
$authParams['client_id'] :
$_POST['client_id'];
// Client secret
if ( ! isset($authParams['client_secret']) && ! isset($_POST['client_secret'])) {
// @codeCoverageIgnoreStart
throw new ClientException(sprintf($this->errors['invalid_request'], 'client_secret'), 0);
// @codeCoverageIgnoreEnd
}
$params['client_secret'] = (isset($authParams['client_secret'])) ?
$authParams['client_secret'] :
$_POST['client_secret'];
// Validate client ID and client secret
$clientDetails = $this->_dbCall(
'validateClient',
$params['client_id'],
$params['client_secret'],
null
);
if ($clientDetails === false) {
// @codeCoverageIgnoreStart
throw new ClientException($this->errors['invalid_client'], 8);
// @codeCoverageIgnoreEnd
}
// Generate an access token
$accessToken = $this->_generateCode();
$refreshToken = ($this->_grantTypes['refresh_token']) ?
$this->_generateCode() :
null;
$accessTokenExpires = time() + $this->_config['access_token_ttl'];
$accessTokenExpiresIn = $this->_config['access_token_ttl'];
// Delete any existing sessions just to be sure
$this->_dbCall('deleteSession', $params['client_id'], 'client', $params['client_id']);
// Create a new session
$this->_dbCall('newSession', $params['client_id'], null, 'client', $params['client_id'], null, $accessToken, $refreshToken, $accessTokenExpires, 'granted');
$response = array(
'access_token' => $accessToken,
'token_type' => 'bearer',
'expires' => $accessTokenExpires,
'expires_in' => $accessTokenExpiresIn
);
if ($this->_grantTypes['refresh_token']) {
$response['refresh_token'] = $refreshToken;
}
return $response;
}
/**
* Complete the resource owner password credentials grant
*
* @access private
* @param array $authParams Array of parsed $_POST keys
* @param array $params Generated parameters from issueAccessToken()
* @return array Authorise request parameters
*/
private function _completeUserCredentialsGrant($authParams = array(), $params = array())
{
// Client ID
if ( ! isset($authParams['client_id']) && ! isset($_POST['client_id'])) {
// @codeCoverageIgnoreStart
throw new ClientException(sprintf($this->errors['invalid_request'], 'client_id'), 0);
// @codeCoverageIgnoreEnd
}
$params['client_id'] = (isset($authParams['client_id'])) ?
$authParams['client_id'] :
$_POST['client_id'];
// Client secret
if ( ! isset($authParams['client_secret']) && ! isset($_POST['client_secret'])) {
// @codeCoverageIgnoreStart
throw new ClientException(sprintf($this->errors['invalid_request'], 'client_secret'), 0);
// @codeCoverageIgnoreEnd
}
$params['client_secret'] = (isset($authParams['client_secret'])) ?
$authParams['client_secret'] :
$_POST['client_secret'];
// Validate client ID and client secret
$clientDetails = $this->_dbCall(
'validateClient',
$params['client_id'],
$params['client_secret'],
null
);
if ($clientDetails === false) {
// @codeCoverageIgnoreStart
throw new ClientException($this->errors['invalid_client'], 8);
// @codeCoverageIgnoreEnd
}
// User's username
if ( ! isset($authParams['username']) && ! isset($_POST['username'])) {
throw new ClientException(sprintf($this->errors['invalid_request'], 'username'), 0);
}
$params['username'] = (isset($authParams['username'])) ?
$authParams['username'] :
$_POST['username'];
// User's password
if ( ! isset($authParams['password']) && ! isset($_POST['password'])) {
throw new ClientException(sprintf($this->errors['invalid_request'], 'password'), 0);
}
$params['password'] = (isset($authParams['password'])) ?
$authParams['password'] :
$_POST['password'];
// Check if user's username and password are correct
$userId = call_user_func($this->_grantTypeCallbacks['password'], $params['username'], $params['password']);
if ($userId === false) {
throw new \Oauth2\Authentication\ClientException($this->errors['invalid_credentials'], 0);
}
// Generate an access token
$accessToken = $this->_generateCode();
$refreshToken = ($this->_grantTypes['refresh_token']) ?
$this->_generateCode() :
null;
$accessTokenExpires = time() + $this->_config['access_token_ttl'];
$accessTokenExpiresIn = $this->_config['access_token_ttl'];
// Delete any existing sessions just to be sure
$this->_dbCall('deleteSession', $params['client_id'], 'user', $userId);
// Create a new session
$this->_dbCall('newSession', $params['client_id'], null, 'user', $userId, null, $accessToken, $refreshToken, $accessTokenExpires, 'granted');
$response = array(
'access_token' => $accessToken,
'token_type' => 'bearer',
'expires' => $accessTokenExpires,
'expires_in' => $accessTokenExpiresIn
);
if ($this->_grantTypes['refresh_token']) {
$response['refresh_token'] = $refreshToken;
}
return $response;
}
/**
* Complete the refresh token grant
*
* @access private
* @param array $authParams Array of parsed $_POST keys
* @param array $params Generated parameters from issueAccessToken()
* @return array Authorise request parameters
*/
private function _completeRefreshTokenGrant($authParams = array(), $params = array())
{
// Client ID
if ( ! isset($authParams['client_id']) && ! isset($_POST['client_id'])) {
// @codeCoverageIgnoreStart
throw new ClientException(sprintf($this->errors['invalid_request'], 'client_id'), 0);
// @codeCoverageIgnoreEnd
}
$params['client_id'] = (isset($authParams['client_id'])) ?
$authParams['client_id'] :
$_POST['client_id'];
// Client secret
if ( ! isset($authParams['client_secret']) && ! isset($_POST['client_secret'])) {
// @codeCoverageIgnoreStart
throw new ClientException(sprintf($this->errors['invalid_request'], 'client_secret'), 0);
// @codeCoverageIgnoreEnd
}
$params['client_secret'] = (isset($authParams['client_secret'])) ?
$authParams['client_secret'] :
$_POST['client_secret'];
// Validate client ID and client secret
$clientDetails = $this->_dbCall(
'validateClient',
$params['client_id'],
$params['client_secret'],
null
);
if ($clientDetails === false) {
// @codeCoverageIgnoreStart
throw new ClientException($this->errors['invalid_client'], 8);
// @codeCoverageIgnoreEnd
}
// Refresh token
if ( ! isset($authParams['refresh_token']) && ! isset($_POST['refresh_token'])) {
throw new ClientException(sprintf($this->errors['invalid_request'], 'refresh_token'), 0);
}
$params['refresh_token'] = (isset($authParams['refresh_token'])) ?
$authParams['refresh_token'] :
$_POST['refresh_token'];
// Validate refresh token
$sessionId = $this->_dbCall('validateRefreshToken', $params['refresh_token'], $params['client_id']);
if ($sessionId === false) {
throw new \Oauth2\Authentication\ClientException($this->errors['invalid_refresh'], 0);
}
// Generate new tokens
$accessToken = $this->_generateCode();
$refreshToken = $this->_generateCode();
$accessTokenExpires = time() + $this->_config['access_token_ttl'];
$accessTokenExpiresIn = $this->_config['access_token_ttl'];
// Update the tokens
$this->_dbCall('updateRefreshToken', $sessionId, $accessToken, $refreshToken, $accessTokenExpires);
return array(
'access_token' => $accessToken,
'refresh_token' => $refreshToken,
'token_type' => 'bearer',
'expires_in' => $this->_config['access_token_ttl']
'expires' => $accessTokenExpires,
'expires_in' => $accessTokenExpiresIn
);
}
}
/**
* Generates the redirect uri with appended params
@@ -517,19 +763,7 @@ class Server
*/
public function redirectUri($redirectUri, $params = array(), $queryDelimeter = '?')
{
if (strstr($redirectUri, $queryDelimeter)) {
$redirectUri = $redirectUri . '&' . http_build_query($params);
} else {
$redirectUri = $redirectUri . $queryDelimeter . http_build_query($params);
}
return $redirectUri;
return (strstr($redirectUri, $queryDelimeter)) ? $redirectUri . '&' . http_build_query($params) : $redirectUri . $queryDelimeter . http_build_query($params);
}
/**

19
src/Oauth2/Client/Provider.php Executable file
View File

@@ -0,0 +1,19 @@
<?php
namespace OAuth2\Client;
class Provider
{
private function __constuct() {}
public static function factory($name, array $options = null)
{
if ( ! class_exists($name)) {
throw new OAuth2\Client\Exception('There is no identity provider called: '.$name);
}
return new $name($options);
}
}

View File

@@ -37,8 +37,8 @@ interface Database
* Database query:
*
* <code>
* SELECT scope FROM oauth_session_scopes WHERE access_token =
* '291dca1c74900f5f252de351e0105aa3fc91b90b'
* SELECT scope FROM oauth_session_scopes WHERE session_id =
* $sessionId
* </code>
*
* Response:

View File

@@ -75,7 +75,7 @@ class Server
public function __construct($options = null)
{
if ($options !== null) {
$this->config = array_merge($this->config, $options);
$this->_config = array_merge($this->_config, $options);
}
}

6
tests/Bootstrap.php Normal file
View File

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

View File

@@ -23,40 +23,24 @@ class OAuthdb implements Database
'description' => 'test'
));
public function validateClient(
$clientId,
$clientSecret = null,
$redirectUri = null
)
{
if ($clientId !== $this->clients[0]['client_id'])
public function validateClient($clientId, $clientSecret = null, $redirectUri = null)
{
if ($clientId !== $this->clients[0]['client_id']) {
return false;
}
if ($clientSecret !== null && $clientSecret !== $this->clients[0]['client_secret'])
{
if ($clientSecret !== null && $clientSecret !== $this->clients[0]['client_secret']) {
return false;
}
if ($redirectUri !== null && $redirectUri !== $this->clients[0]['redirect_uri'])
{
if ($redirectUri !== null && $redirectUri !== $this->clients[0]['redirect_uri']) {
return false;
}
return $this->clients[0];
}
public function newSession(
$clientId,
$redirectUri,
$type = 'user',
$typeId = null,
$authCode = null,
$accessToken = null,
$accessTokenExpire = null,
$stage = 'requested'
)
public function newSession($clientId, $redirectUri, $type = 'user', $typeId = null, $authCode = null, $accessToken = null, $refreshToken = null, $accessTokenExpire = null, $stage = 'requested')
{
$id = count($this->sessions);
@@ -68,6 +52,7 @@ class OAuthdb implements Database
'owner_id' => $typeId,
'auth_code' => $authCode,
'access_token' => $accessToken,
'refresh_token' => $refreshToken,
'access_token_expire' => $accessTokenExpire,
'stage' => $stage
);
@@ -75,60 +60,46 @@ class OAuthdb implements Database
$this->sessions_client_type_id[$clientId . ':' . $type . ':' . $typeId] = $id;
$this->sessions_code[$clientId . ':' . $redirectUri . ':' . $authCode] = $id;
return true;
return $id;
}
public function updateSession(
$sessionId,
$authCode = null,
$accessToken = null,
$accessTokenExpire = null,
$stage = 'requested'
)
public function updateSession($sessionId, $authCode = null, $accessToken = null, $refreshToken = null, $accessTokenExpire = null, $stage = 'requested')
{
$this->sessions[$sessionId]['auth_code'] = $authCode;
$this->sessions[$sessionId]['access_token'] = $accessToken;
$this->sessions[$sessionId]['refresh_token'] = $refreshToken;
$this->sessions[$sessionId]['access_token_expire'] = $accessTokenExpire;
$this->sessions[$sessionId]['stage'] = $stage;
return true;
}
public function deleteSession(
$clientId,
$type,
$typeId
)
public function deleteSession($clientId, $type, $typeId)
{
$key = $clientId . ':' . $type . ':' . $typeId;
if (isset($this->sessions_client_type_id[$key]))
{
if (isset($this->sessions_client_type_id[$key])) {
unset($this->sessions[$this->sessions_client_type_id[$key]]);
}
return true;
}
public function validateAuthCode(
$clientId,
$redirectUri,
$authCode
)
public function refreshToken($currentRefreshToken, $newAccessToken, $newRefreshToken, $accessTokenExpires)
{
die('not implemented refreshToken');
}
public function validateAuthCode($clientId, $redirectUri, $authCode)
{
$key = $clientId . ':' . $redirectUri . ':' . $authCode;
if (isset($this->sessions_code[$key]))
{
if (isset($this->sessions_code[$key])) {
return $this->sessions[$this->sessions_code[$key]];
}
return false;
}
public function hasSession(
$type,
$typeId,
$clientId
)
public function hasSession($type, $typeId, $clientId)
{
die('not implemented hasSession');
}
@@ -143,21 +114,14 @@ class OAuthdb implements Database
die('not implemented removeAuthCode');
}
public function setAccessToken(
$sessionId,
$accessToken
)
public function setAccessToken($sessionId, $accessToken)
{
die('not implemented setAccessToken');
}
public function addSessionScope(
$sessionId,
$scope
)
{
if ( ! isset($this->session_scopes[$sessionId]))
public function addSessionScope($sessionId, $scope)
{
if ( ! isset($this->session_scopes[$sessionId])) {
$this->session_scopes[$sessionId] = array();
}
@@ -168,18 +132,14 @@ class OAuthdb implements Database
public function getScope($scope)
{
if ( ! isset($this->scopes[$scope]))
{
if ( ! isset($this->scopes[$scope])) {
return false;
}
return $this->scopes[$scope];
}
public function updateSessionScopeAccessToken(
$sessionId,
$accessToken
)
public function updateSessionScopeAccessToken($sessionId, $accessToken)
{
return true;
}
@@ -188,4 +148,21 @@ class OAuthdb implements Database
{
die('not implemented accessTokenScopes');
}
public function validateRefreshToken($refreshToken, $clientId)
{
if ($refreshToken !== $this->sessions[0]['refresh_token'])
{
return false;
}
return true;
}
public function updateRefreshToken($sessionId, $newAccessToken, $newRefreshToken, $accessTokenExpires)
{
$this->sessions[$sessionId]['access_token'] = $newAccessToken;
$this->sessions[$sessionId]['refresh_token'] = $newRefreshToken;
$this->sessions[$sessionId]['access_token_expire'] = $accessTokenExpires;
}
}

View File

@@ -1,21 +1,35 @@
<?php
class Authentication_Server_test extends PHPUnit_Framework_TestCase {
function setUp()
class Authentication_Server_test extends PHPUnit_Framework_TestCase
{
public function setUp()
{
$this->oauth = new Oauth2\Authentication\Server();
require_once('database_mock.php');
require_once 'database_mock.php';
$this->oauthdb = new OAuthdb();
$this->assertInstanceOf('Oauth2\Authentication\Database', $this->oauthdb);
$this->oauth->registerDbAbstractor($this->oauthdb);
}
function test_generateCode()
public function test_setupWithOptions()
{
$o = new Oauth2\Authentication\Server(array(
'access_token_ttl' => 86400
));
$reflector = new ReflectionClass($o);
$param = $reflector->getProperty('_config');
$param->setAccessible(true);
$array = $param->getValue($o);
$this->assertEquals(86400, $array['access_token_ttl']);
}
public function test_generateCode()
{
$reflector = new ReflectionClass($this->oauth);
$method = $reflector->getMethod('generateCode');
$method = $reflector->getMethod('_generateCode');
$method->setAccessible(true);
$result = $method->invoke($this->oauth);
@@ -25,7 +39,7 @@ class Authentication_Server_test extends PHPUnit_Framework_TestCase {
$this->assertNotEquals($result, $result2);
}
function test_redirectUri()
public function test_redirectUri()
{
$result1 = $this->oauth->redirectUri('http://example.com/foo');
$result2 = $this->oauth->redirectUri('http://example.com/foo', array('foo' => 'bar'));
@@ -36,7 +50,7 @@ class Authentication_Server_test extends PHPUnit_Framework_TestCase {
$this->assertEquals('http://example.com/foo#foo=bar', $result3);
}
function test_checkClientAuthoriseParams_GET()
public function test_checkClientAuthoriseParams_GET()
{
$_GET['client_id'] = 'test';
$_GET['redirect_uri'] = 'http://example.com/test';
@@ -46,6 +60,12 @@ class Authentication_Server_test extends PHPUnit_Framework_TestCase {
$expect = array(
'client_id' => 'test',
'redirect_uri' => 'http://example.com/test',
'client_details' => array(
'client_id' => 'test',
'client_secret' => 'test',
'redirect_uri' => 'http://example.com/test',
'name' => 'Test Client'
),
'response_type' => 'code',
'scopes' => array(
0 => array(
@@ -62,7 +82,7 @@ class Authentication_Server_test extends PHPUnit_Framework_TestCase {
$this->assertEquals($expect, $result);
}
function test_checkClientAuthoriseParams_PassedParams()
public function test_checkClientAuthoriseParams_PassedParams()
{
unset($_GET['client_id']);
unset($_GET['redirect_uri']);
@@ -79,6 +99,12 @@ class Authentication_Server_test extends PHPUnit_Framework_TestCase {
$this->assertEquals(array(
'client_id' => 'test',
'redirect_uri' => 'http://example.com/test',
'client_details' => array(
'client_id' => 'test',
'client_secret' => 'test',
'redirect_uri' => 'http://example.com/test',
'name' => 'Test Client'
),
'response_type' => 'code',
'scopes' => array(0 => array(
'id' => 1,
@@ -93,7 +119,7 @@ class Authentication_Server_test extends PHPUnit_Framework_TestCase {
* @expectedException Oauth2\Authentication\ClientException
* @expectedExceptionCode 0
*/
function test_checkClientAuthoriseParams_missingClientId()
public function test_checkClientAuthoriseParams_missingClientId()
{
$this->oauth->checkClientAuthoriseParams();
}
@@ -102,7 +128,7 @@ class Authentication_Server_test extends PHPUnit_Framework_TestCase {
* @expectedException Oauth2\Authentication\ClientException
* @expectedExceptionCode 0
*/
function test_checkClientAuthoriseParams_missingRedirectUri()
public function test_checkClientAuthoriseParams_missingRedirectUri()
{
$_GET['client_id'] = 'test';
@@ -113,7 +139,7 @@ class Authentication_Server_test extends PHPUnit_Framework_TestCase {
* @expectedException Oauth2\Authentication\ClientException
* @expectedExceptionCode 0
*/
function test_checkClientAuthoriseParams_missingResponseType()
public function test_checkClientAuthoriseParams_missingResponseType()
{
$_GET['client_id'] = 'test';
$_GET['redirect_uri'] = 'http://example.com/test';
@@ -125,7 +151,7 @@ class Authentication_Server_test extends PHPUnit_Framework_TestCase {
* @expectedException Oauth2\Authentication\ClientException
* @expectedExceptionCode 0
*/
function test_checkClientAuthoriseParams_missingScopes()
public function test_checkClientAuthoriseParams_missingScopes()
{
$_GET['client_id'] = 'test';
$_GET['redirect_uri'] = 'http://example.com/test';
@@ -139,7 +165,7 @@ class Authentication_Server_test extends PHPUnit_Framework_TestCase {
* @expectedException Oauth2\Authentication\ClientException
* @expectedExceptionCode 4
*/
function test_checkClientAuthoriseParams_invalidScopes()
public function test_checkClientAuthoriseParams_invalidScopes()
{
$_GET['client_id'] = 'test';
$_GET['redirect_uri'] = 'http://example.com/test';
@@ -149,7 +175,35 @@ class Authentication_Server_test extends PHPUnit_Framework_TestCase {
$this->oauth->checkClientAuthoriseParams();
}
function test_newAuthoriseRequest()
/**
* @expectedException Oauth2\Authentication\ClientException
* @expectedExceptionCode 8
*/
public function test_checkClientAuthoriseParams_invalidClient()
{
$_GET['client_id'] = 'test';
$_GET['redirect_uri'] = 'http://example.com/test2';
$_GET['response_type'] = 'code';
$_GET['scope'] = 'blah';
$this->oauth->checkClientAuthoriseParams();
}
/**
* @expectedException Oauth2\Authentication\ClientException
* @expectedExceptionCode 3
*/
public function test_checkClientAuthoriseParams_invalidResponseType()
{
$_GET['client_id'] = 'test';
$_GET['redirect_uri'] = 'http://example.com/test';
$_GET['response_type'] = 'blah';
$_GET['scope'] = 'blah';
$this->oauth->checkClientAuthoriseParams();
}
public function test_newAuthoriseRequest()
{
$result = $this->oauth->newAuthoriseRequest('user', '123', array(
'client_id' => 'test',
@@ -165,7 +219,7 @@ class Authentication_Server_test extends PHPUnit_Framework_TestCase {
$this->assertEquals(40, strlen($result));
}
function test_newAuthoriseRequest_isUnique()
public function test_newAuthoriseRequest_isUnique()
{
$result1 = $this->oauth->newAuthoriseRequest('user', '123', array(
'client_id' => 'test',
@@ -192,7 +246,11 @@ class Authentication_Server_test extends PHPUnit_Framework_TestCase {
$this->assertNotEquals($result1, $result2);
}
function test_issueAccessToken_POST()
/**
* @expectedException Oauth2\Authentication\ClientException
* @expectedExceptionCode 7
*/
public function test_issueAccessTokenNoRegisteredGrant()
{
$auth_code = $this->oauth->newAuthoriseRequest('user', '123', array(
'client_id' => 'test',
@@ -212,14 +270,38 @@ class Authentication_Server_test extends PHPUnit_Framework_TestCase {
$_POST['code'] = $auth_code;
$result = $this->oauth->issueAccessToken();
}
$this->assertCount(3, $result);
public function test_issueAccessToken_POST_authorization_code()
{
$auth_code = $this->oauth->newAuthoriseRequest('user', '123', array(
'client_id' => 'test',
'redirect_uri' => 'http://example.com/test',
'scopes' => array(array(
'id' => 1,
'scope' => 'test',
'name' => 'test',
'description' => 'test'
))
));
$_POST['client_id'] = 'test';
$_POST['client_secret'] = 'test';
$_POST['redirect_uri'] = 'http://example.com/test';
$_POST['grant_type'] = 'authorization_code';
$_POST['code'] = $auth_code;
$this->oauth->enableGrantType('authorization_code');
$result = $this->oauth->issueAccessToken();
$this->assertCount(4, $result);
$this->assertArrayHasKey('access_token', $result);
$this->assertArrayHasKey('token_type', $result);
$this->assertArrayHasKey('expires_in', $result);
$this->assertArrayHasKey('expires', $result);
}
function test_issueAccessToken_PassedParams()
public function test_issueAccessToken_PassedParams_authorization_code()
{
$auth_code = $this->oauth->newAuthoriseRequest('user', '123', array(
'client_id' => 'test',
@@ -238,19 +320,451 @@ class Authentication_Server_test extends PHPUnit_Framework_TestCase {
$params['grant_type'] = 'authorization_code';
$params['code'] = $auth_code;
$this->oauth->enableGrantType('authorization_code');
$result = $this->oauth->issueAccessToken($params);
$this->assertCount(4, $result);
$this->assertArrayHasKey('access_token', $result);
$this->assertArrayHasKey('token_type', $result);
$this->assertArrayHasKey('expires_in', $result);
$this->assertArrayHasKey('expires', $result);
}
public function test_issueAccessToken_refresh_token()
{
$this->oauth->enableGrantType('authorization_code');
$this->oauth->enableGrantType('refresh_token');
$auth_code = $this->oauth->newAuthoriseRequest('user', '123', array(
'client_id' => 'test',
'redirect_uri' => 'http://example.com/test',
'scopes' => array(array(
'id' => 1,
'scope' => 'test',
'name' => 'test',
'description' => 'test'
))
));
$params['client_id'] = 'test';
$params['client_secret'] = 'test';
$params['redirect_uri'] = 'http://example.com/test';
$params['grant_type'] = 'authorization_code';
$params['code'] = $auth_code;
$result = $this->oauth->issueAccessToken($params);
$this->assertCount(3, $result);
$this->assertCount(5, $result);
$this->assertArrayHasKey('access_token', $result);
$this->assertArrayHasKey('token_type', $result);
$this->assertArrayHasKey('expires_in', $result);
$this->assertArrayHasKey('expires', $result);
$this->assertArrayHasKey('refresh_token', $result);
// Wait for a few seconds for the access token to age
sleep(1);
// Refresh the token
$params2['client_id'] = 'test';
$params2['client_secret'] = 'test';
$params2['redirect_uri'] = 'http://example.com/test';
$params2['grant_type'] = 'refresh_token';
$params2['refresh_token'] = $result['refresh_token'];
$result2 = $this->oauth->issueAccessToken($params2);
$this->assertCount(5, $result2);
$this->assertArrayHasKey('access_token', $result2);
$this->assertArrayHasKey('token_type', $result2);
$this->assertArrayHasKey('expires_in', $result2);
$this->assertArrayHasKey('expires', $result2);
$this->assertArrayHasKey('refresh_token', $result2);
$this->assertNotEquals($result['access_token'], $result2['access_token']);
$this->assertNotEquals($result['refresh_token'], $result2['refresh_token']);
$this->assertNotEquals($result['expires'], $result2['expires']);
$this->assertEquals($result['expires_in'], $result2['expires_in']);
$this->assertEquals($result['token_type'], $result2['token_type']);
}
public function test_issueAccessToken_client_credentials()
{
$this->oauth->enableGrantType('client_credentials');
$auth_code = $this->oauth->newAuthoriseRequest('user', '123', array(
'client_id' => 'test',
'redirect_uri' => 'http://example.com/test',
'scopes' => array(array(
'id' => 1,
'scope' => 'test',
'name' => 'test',
'description' => 'test'
))
));
$params['client_id'] = 'test';
$params['client_secret'] = 'test';
$params['redirect_uri'] = 'http://example.com/test';
$params['grant_type'] = 'client_credentials';
$params['code'] = $auth_code;
$result = $this->oauth->issueAccessToken($params);
$this->assertCount(4, $result);
$this->assertArrayHasKey('access_token', $result);
$this->assertArrayHasKey('token_type', $result);
$this->assertArrayHasKey('expires_in', $result);
$this->assertArrayHasKey('expires', $result);
}
public function test_issueAccessToken_client_credentialsPOST()
{
$this->oauth->enableGrantType('client_credentials');
$auth_code = $this->oauth->newAuthoriseRequest('user', '123', array(
'client_id' => 'test',
'redirect_uri' => 'http://example.com/test',
'scopes' => array(array(
'id' => 1,
'scope' => 'test',
'name' => 'test',
'description' => 'test'
))
));
$_POST['client_id'] = 'test';
$_POST['client_secret'] = 'test';
$_POST['redirect_uri'] = 'http://example.com/test';
$_POST['grant_type'] = 'client_credentials';
$_POST['code'] = $auth_code;
$result = $this->oauth->issueAccessToken();
$this->assertCount(4, $result);
$this->assertArrayHasKey('access_token', $result);
$this->assertArrayHasKey('token_type', $result);
$this->assertArrayHasKey('expires_in', $result);
$this->assertArrayHasKey('expires', $result);
}
public function test_issueAccessToken_client_credentials_withRefreshToken()
{
$this->oauth->enableGrantType('client_credentials');
$this->oauth->enableGrantType('refresh_token');
$auth_code = $this->oauth->newAuthoriseRequest('user', '123', array(
'client_id' => 'test',
'redirect_uri' => 'http://example.com/test',
'scopes' => array(array(
'id' => 1,
'scope' => 'test',
'name' => 'test',
'description' => 'test'
))
));
$params['client_id'] = 'test';
$params['client_secret'] = 'test';
$params['redirect_uri'] = 'http://example.com/test';
$params['grant_type'] = 'client_credentials';
$params['code'] = $auth_code;
$result = $this->oauth->issueAccessToken($params);
$this->assertCount(5, $result);
$this->assertArrayHasKey('access_token', $result);
$this->assertArrayHasKey('token_type', $result);
$this->assertArrayHasKey('expires_in', $result);
$this->assertArrayHasKey('expires', $result);
$this->assertArrayHasKey('refresh_token', $result);
}
public function test_issueAccessToken_refresh_tokenPOST()
{
$this->oauth->enableGrantType('authorization_code');
$this->oauth->enableGrantType('refresh_token');
$auth_code = $this->oauth->newAuthoriseRequest('user', '123', array(
'client_id' => 'test',
'redirect_uri' => 'http://example.com/test',
'scopes' => array(array(
'id' => 1,
'scope' => 'test',
'name' => 'test',
'description' => 'test'
))
));
$_POST['client_id'] = 'test';
$_POST['client_secret'] = 'test';
$_POST['redirect_uri'] = 'http://example.com/test';
$_POST['grant_type'] = 'authorization_code';
$_POST['code'] = $auth_code;
$result = $this->oauth->issueAccessToken();
$this->assertCount(5, $result);
$this->assertArrayHasKey('access_token', $result);
$this->assertArrayHasKey('token_type', $result);
$this->assertArrayHasKey('expires_in', $result);
$this->assertArrayHasKey('expires', $result);
$this->assertArrayHasKey('refresh_token', $result);
// Wait for a few seconds for the access token to age
sleep(1);
// Refresh the token
$_POST['client_id'] = 'test';
$_POST['client_secret'] = 'test';
$_POST['redirect_uri'] = 'http://example.com/test';
$_POST['grant_type'] = 'refresh_token';
$_POST['refresh_token'] = $result['refresh_token'];
$result2 = $this->oauth->issueAccessToken();
$this->assertCount(5, $result2);
$this->assertArrayHasKey('access_token', $result2);
$this->assertArrayHasKey('token_type', $result2);
$this->assertArrayHasKey('expires_in', $result2);
$this->assertArrayHasKey('expires', $result2);
$this->assertArrayHasKey('refresh_token', $result2);
$this->assertNotEquals($result['access_token'], $result2['access_token']);
$this->assertNotEquals($result['refresh_token'], $result2['refresh_token']);
$this->assertNotEquals($result['expires'], $result2['expires']);
$this->assertEquals($result['expires_in'], $result2['expires_in']);
$this->assertEquals($result['token_type'], $result2['token_type']);
}
/**
* @expectedException Oauth2\Authentication\ClientException
* @expectedExceptionCode 0
*/
function test_issueAccessToken_missingGrantType()
public function test_issueAccessToken_refresh_tokenMissingToken()
{
$this->oauth->enableGrantType('authorization_code');
$this->oauth->enableGrantType('refresh_token');
$auth_code = $this->oauth->newAuthoriseRequest('user', '123', array(
'client_id' => 'test',
'redirect_uri' => 'http://example.com/test',
'scopes' => array(array(
'id' => 1,
'scope' => 'test',
'name' => 'test',
'description' => 'test'
))
));
$_POST['client_id'] = 'test';
$_POST['client_secret'] = 'test';
$_POST['redirect_uri'] = 'http://example.com/test';
$_POST['grant_type'] = 'authorization_code';
$_POST['code'] = $auth_code;
$result = $this->oauth->issueAccessToken();
$this->assertCount(5, $result);
$this->assertArrayHasKey('access_token', $result);
$this->assertArrayHasKey('token_type', $result);
$this->assertArrayHasKey('expires_in', $result);
$this->assertArrayHasKey('expires', $result);
$this->assertArrayHasKey('refresh_token', $result);
// Wait for a few seconds for the access token to age
sleep(1);
// Refresh the token
$_POST['client_id'] = 'test';
$_POST['client_secret'] = 'test';
$_POST['redirect_uri'] = 'http://example.com/test';
$_POST['grant_type'] = 'refresh_token';
$result2 = $this->oauth->issueAccessToken();
}
/**
* @expectedException Oauth2\Authentication\ClientException
* @expectedExceptionCode 0
*/
public function test_issueAccessToken_invalid_refresh_token()
{
$this->oauth->enableGrantType('authorization_code');
$this->oauth->enableGrantType('refresh_token');
$auth_code = $this->oauth->newAuthoriseRequest('user', '123', array(
'client_id' => 'test',
'redirect_uri' => 'http://example.com/test',
'scopes' => array(array(
'id' => 1,
'scope' => 'test',
'name' => 'test',
'description' => 'test'
))
));
$params['client_id'] = 'test';
$params['client_secret'] = 'test';
$params['redirect_uri'] = 'http://example.com/test';
$params['grant_type'] = 'authorization_code';
$params['code'] = $auth_code;
$result = $this->oauth->issueAccessToken($params);
$this->assertCount(5, $result);
$this->assertArrayHasKey('access_token', $result);
$this->assertArrayHasKey('token_type', $result);
$this->assertArrayHasKey('expires_in', $result);
$this->assertArrayHasKey('expires', $result);
$this->assertArrayHasKey('refresh_token', $result);
// Wait for a few seconds for the access token to age
sleep(1);
// Refresh the token
$params2['client_id'] = 'test';
$params2['client_secret'] = 'test';
$params2['redirect_uri'] = 'http://example.com/test';
$params2['grant_type'] = 'refresh_token';
$params2['refresh_token'] = 'blah';
$result2 = $this->oauth->issueAccessToken($params2);
}
/**
* @expectedException Oauth2\Authentication\ServerException
* @expectedExceptionCode 0
*/
public function test_issueAccessToken_password_grant_Missing_Callback()
{
$this->oauth->enableGrantType('password');
}
public function test_issueAccessToken_password_grant()
{
$this->oauth->enableGrantType('password', function(){
return true;
});
$params['client_id'] = 'test';
$params['client_secret'] = 'test';
$params['grant_type'] = 'password';
$params['username'] = 'alexbilbie';
$params['password'] = 'helloworld';
$result = $this->oauth->issueAccessToken($params);
$this->assertCount(4, $result);
$this->assertArrayHasKey('access_token', $result);
$this->assertArrayHasKey('token_type', $result);
$this->assertArrayHasKey('expires_in', $result);
$this->assertArrayHasKey('expires', $result);
}
public function test_issueAccessToken_password_grantPOST()
{
$this->oauth->enableGrantType('password', function(){
return true;
});
$_POST['client_id'] = 'test';
$_POST['client_secret'] = 'test';
$_POST['grant_type'] = 'password';
$_POST['username'] = 'alexbilbie';
$_POST['password'] = 'helloworld';
$result = $this->oauth->issueAccessToken();
$this->assertCount(4, $result);
$this->assertArrayHasKey('access_token', $result);
$this->assertArrayHasKey('token_type', $result);
$this->assertArrayHasKey('expires_in', $result);
$this->assertArrayHasKey('expires', $result);
}
public function test_issueAccessToken_password_grant_withRefreshToken()
{
$this->oauth->enableGrantType('password', function(){
return true;
});
$this->oauth->enableGrantType('refresh_token');
$params['client_id'] = 'test';
$params['client_secret'] = 'test';
$params['grant_type'] = 'password';
$params['username'] = 'alexbilbie';
$params['password'] = 'helloworld';
$result = $this->oauth->issueAccessToken($params);
$this->assertCount(5, $result);
$this->assertArrayHasKey('access_token', $result);
$this->assertArrayHasKey('token_type', $result);
$this->assertArrayHasKey('expires_in', $result);
$this->assertArrayHasKey('expires', $result);
$this->assertArrayHasKey('refresh_token', $result);
}
/**
* @expectedException Oauth2\Authentication\ClientException
* @expectedExceptionCode 0
*/
public function test_issueAccessToken_password_grant_wrongCreds()
{
$this->oauth->enableGrantType('password', function(){
return false;
});
$params['client_id'] = 'test';
$params['client_secret'] = 'test';
$params['grant_type'] = 'password';
$params['username'] = 'alexbilbie';
$params['password'] = 'helloworld';
$result = $this->oauth->issueAccessToken($params);
}
/**
* @expectedException Oauth2\Authentication\ClientException
* @expectedExceptionCode 0
*/
public function test_issueAccessToken_password_grant_missingUsername()
{
$this->oauth->enableGrantType('password', function(){
return true;
});
$params['client_id'] = 'test';
$params['client_secret'] = 'test';
$params['grant_type'] = 'password';
$result = $this->oauth->issueAccessToken($params);
}
/**
* @expectedException Oauth2\Authentication\ClientException
* @expectedExceptionCode 0
*/
public function test_issueAccessToken_password_grant_missingPassword()
{
$this->oauth->enableGrantType('password', function(){
return true;
});
$params['client_id'] = 'test';
$params['client_secret'] = 'test';
$params['grant_type'] = 'password';
$params['username'] = 'alexbilbie';
$result = $this->oauth->issueAccessToken($params);
}
/**
* @expectedException Oauth2\Authentication\ClientException
* @expectedExceptionCode 0
*/
public function test_issueAccessToken_missingGrantType()
{
$this->oauth->issueAccessToken();
}
@@ -259,7 +773,7 @@ class Authentication_Server_test extends PHPUnit_Framework_TestCase {
* @expectedException Oauth2\Authentication\ClientException
* @expectedExceptionCode 7
*/
function test_issueAccessToken_unsupportedGrantType()
public function test_issueAccessToken_unsupportedGrantType()
{
$params['grant_type'] = 'blah';
@@ -270,10 +784,10 @@ class Authentication_Server_test extends PHPUnit_Framework_TestCase {
* @expectedException Oauth2\Authentication\ClientException
* @expectedExceptionCode 0
*/
function test_completeAuthCodeGrant_missingClientId()
public function test_completeAuthCodeGrant_missingClientId()
{
$reflector = new ReflectionClass($this->oauth);
$method = $reflector->getMethod('completeAuthCodeGrant');
$method = $reflector->getMethod('_completeAuthCodeGrant');
$method->setAccessible(true);
$method->invoke($this->oauth);
@@ -283,10 +797,10 @@ class Authentication_Server_test extends PHPUnit_Framework_TestCase {
* @expectedException Oauth2\Authentication\ClientException
* @expectedExceptionCode 0
*/
function test_completeAuthCodeGrant_missingClientSecret()
public function test_completeAuthCodeGrant_missingClientSecret()
{
$reflector = new ReflectionClass($this->oauth);
$method = $reflector->getMethod('completeAuthCodeGrant');
$method = $reflector->getMethod('_completeAuthCodeGrant');
$method->setAccessible(true);
$authParams['client_id'] = 'test';
@@ -298,10 +812,10 @@ class Authentication_Server_test extends PHPUnit_Framework_TestCase {
* @expectedException Oauth2\Authentication\ClientException
* @expectedExceptionCode 0
*/
function test_completeAuthCodeGrant_missingRedirectUri()
public function test_completeAuthCodeGrant_missingRedirectUri()
{
$reflector = new ReflectionClass($this->oauth);
$method = $reflector->getMethod('completeAuthCodeGrant');
$method = $reflector->getMethod('_completeAuthCodeGrant');
$method->setAccessible(true);
$authParams['client_id'] = 'test';
@@ -314,10 +828,10 @@ class Authentication_Server_test extends PHPUnit_Framework_TestCase {
* @expectedException Oauth2\Authentication\ClientException
* @expectedExceptionCode 8
*/
function test_completeAuthCodeGrant_invalidClient()
public function test_completeAuthCodeGrant_invalidClient()
{
$reflector = new ReflectionClass($this->oauth);
$method = $reflector->getMethod('completeAuthCodeGrant');
$method = $reflector->getMethod('_completeAuthCodeGrant');
$method->setAccessible(true);
$authParams['client_id'] = 'test';
@@ -331,10 +845,10 @@ class Authentication_Server_test extends PHPUnit_Framework_TestCase {
* @expectedException Oauth2\Authentication\ClientException
* @expectedExceptionCode 0
*/
function test_completeAuthCodeGrant_missingCode()
public function test_completeAuthCodeGrant_missingCode()
{
$reflector = new ReflectionClass($this->oauth);
$method = $reflector->getMethod('completeAuthCodeGrant');
$method = $reflector->getMethod('_completeAuthCodeGrant');
$method->setAccessible(true);
$authParams['client_id'] = 'test';
@@ -348,10 +862,10 @@ class Authentication_Server_test extends PHPUnit_Framework_TestCase {
* @expectedException Oauth2\Authentication\ClientException
* @expectedExceptionCode 9
*/
function test_completeAuthCodeGrant_invalidCode()
public function test_completeAuthCodeGrant_invalidCode()
{
$reflector = new ReflectionClass($this->oauth);
$method = $reflector->getMethod('completeAuthCodeGrant');
$method = $reflector->getMethod('_completeAuthCodeGrant');
$method->setAccessible(true);
$authParams['client_id'] = 'test';
@@ -366,7 +880,7 @@ class Authentication_Server_test extends PHPUnit_Framework_TestCase {
* @expectedException Oauth2\Authentication\ServerException
* @expectedExceptionMessage No registered database abstractor
*/
function test_noRegisteredDatabaseAbstractor()
public function test_noRegisteredDatabaseAbstractor()
{
$reflector = new ReflectionClass($this->oauth);
$method = $reflector->getMethod('_dbCall');
@@ -383,7 +897,7 @@ class Authentication_Server_test extends PHPUnit_Framework_TestCase {
* @expectedException Oauth2\Authentication\ServerException
* @expectedExceptionMessage Registered database abstractor is not an instance of Oauth2\Authentication\Database
*/
function test_invalidRegisteredDatabaseAbstractor()
public function test_invalidRegisteredDatabaseAbstractor()
{
$fake = new stdClass;
$this->oauth->registerDbAbstractor($fake);