Merge branch 'release/0.4'

This commit is contained in:
Alex Bilbie 2013-01-02 19:17:01 +00:00
commit 5772a2f12f
10 changed files with 1558 additions and 753 deletions

7
.travis.yml Normal file
View File

@ -0,0 +1,7 @@
language: php
php:
- 5.3
- 5.4
script: phpunit --coverage-text --configuration build/phpunit.xml

View File

@ -8,8 +8,8 @@ The framework is provided as a Composer package which can be installed by adding
```javascript ```javascript
{ {
"require": { "require": {
"lncd\Oauth2": "*" "lncd\Oauth2": "*"
} }
} }
``` ```
@ -22,7 +22,12 @@ Check out the [wiki](https://github.com/lncd/OAuth2/wiki)
### Authentication Server ### 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 ### Resource Server

View File

@ -13,6 +13,7 @@
<directory suffix=".php">PEAR_INSTALL_DIR</directory> <directory suffix=".php">PEAR_INSTALL_DIR</directory>
<directory suffix=".php">PHP_LIBDIR</directory> <directory suffix=".php">PHP_LIBDIR</directory>
<directory suffix=".php">../vendor/composer</directory> <directory suffix=".php">../vendor/composer</directory>
<directory suffix=".php">../tests</directory>
</blacklist> </blacklist>
</filter> </filter>
<logging> <logging>

View File

@ -1,7 +1,7 @@
{ {
"name": "lncd/oauth2", "name": "lncd/oauth2",
"description": "OAuth 2.0 Framework", "description": "OAuth 2.0 Framework",
"version": "0.3.5", "version": "0.4",
"homepage": "https://github.com/lncd/OAuth2", "homepage": "https://github.com/lncd/OAuth2",
"license": "MIT", "license": "MIT",
"require": { "require": {

View File

@ -21,11 +21,12 @@ CREATE TABLE `client_endpoints` (
CREATE TABLE `oauth_sessions` ( CREATE TABLE `oauth_sessions` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT, `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`client_id` varchar(40) NOT NULL DEFAULT '', `client_id` varchar(40) NOT NULL DEFAULT '',
`redirect_uri` varchar(250) NOT NULL DEFAULT '', `redirect_uri` varchar(250) DEFAULT '',
`owner_type` enum('user','client') NOT NULL DEFAULT 'user', `owner_type` enum('user','client') NOT NULL DEFAULT 'user',
`owner_id` varchar(255) DEFAULT NULL, `owner_id` varchar(255) DEFAULT NULL,
`auth_code` varchar(40) DEFAULT '', `auth_code` varchar(40) DEFAULT '',
`access_token` varchar(40) DEFAULT '', `access_token` varchar(40) DEFAULT '',
`refresh_token` varchar(40) NOT NULL,
`access_token_expires` int(10) DEFAULT NULL, `access_token_expires` int(10) DEFAULT NULL,
`stage` enum('requested','granted') NOT NULL DEFAULT 'requested', `stage` enum('requested','granted') NOT NULL DEFAULT 'requested',
`first_requested` int(10) unsigned NOT NULL, `first_requested` int(10) unsigned NOT NULL,
@ -56,4 +57,4 @@ CREATE TABLE `oauth_session_scopes` (
KEY `scope` (`scope`), KEY `scope` (`scope`),
CONSTRAINT `oauth_session_scopes_ibfk_3` FOREIGN KEY (`scope`) REFERENCES `scopes` (`scope`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `oauth_session_scopes_ibfk_3` FOREIGN KEY (`scope`) REFERENCES `scopes` (`scope`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `oauth_session_scopes_ibfk_4` FOREIGN KEY (`session_id`) REFERENCES `oauth_sessions` (`id`) ON DELETE CASCADE CONSTRAINT `oauth_session_scopes_ibfk_4` FOREIGN KEY (`session_id`) REFERENCES `oauth_sessions` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8; ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

View File

@ -56,18 +56,19 @@ interface Database
* *
* <code> * <code>
* INSERT INTO oauth_sessions (client_id, redirect_uri, owner_type, * INSERT INTO oauth_sessions (client_id, redirect_uri, owner_type,
* owner_id, auth_code, access_token, stage, first_requested, last_updated) * owner_id, auth_code, access_token, refresh_token, stage, first_requested,
* VALUES ($clientId, $redirectUri, $type, $typeId, $authCode, * last_updated) VALUES ($clientId, $redirectUri, $type, $typeId, $authCode,
* $accessToken, $stage, UNIX_TIMESTAMP(NOW()), UNIX_TIMESTAMP(NOW())) * $accessToken, $stage, UNIX_TIMESTAMP(NOW()), UNIX_TIMESTAMP(NOW()))
* </code> * </code>
* *
* @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 $type The session owner's type (default = "user") * @param string $type The session owner's type (default = "user")
* @param string $typeId The session owner's ID (default = "null") * @param string $typeId The session owner's ID (default = "null")
* @param string $authCode The authorisation code (default = "null") * @param string $authCode The authorisation code (default = "null")
* @param string $accessToken The access token (default = "null") * @param string $accessToken The access token (default = "null")
* @param string $stage The stage of the session (default ="request") * @param string $refreshToken The refresh token (default = "null")
* @param string $stage The stage of the session (default ="request")
* @return int The session ID * @return int The session ID
*/ */
public function newSession( public function newSession(
@ -77,6 +78,7 @@ interface Database
$typeId = null, $typeId = null,
$authCode = null, $authCode = null,
$accessToken = null, $accessToken = null,
$refreshToken = null,
$accessTokenExpire = null, $accessTokenExpire = null,
$stage = 'requested' $stage = 'requested'
); );
@ -92,16 +94,18 @@ interface Database
* id = $sessionId * id = $sessionId
* </code> * </code>
* *
* @param string $sessionId The session ID * @param string $sessionId The session ID
* @param string $authCode The authorisation code (default = "null") * @param string $authCode The authorisation code (default = "null")
* @param string $accessToken The access token (default = "null") * @param string $accessToken The access token (default = "null")
* @param string $stage The stage of the session (default ="request") * @param string $refreshToken The refresh token (default = "null")
* @param string $stage The stage of the session (default ="request")
* @return void * @return void
*/ */
public function updateSession( public function updateSession(
$sessionId, $sessionId,
$authCode = null, $authCode = null,
$accessToken = null, $accessToken = null,
$refreshToken = null,
$accessTokenExpire = null, $accessTokenExpire = null,
$stage = 'requested' $stage = 'requested'
); );
@ -125,6 +129,27 @@ interface Database
$typeId $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 * Validate that an authorisation code is valid
* *

View File

@ -30,15 +30,15 @@ class Server
* @var array * @var array
*/ */
private $_config = array( private $_config = array(
'scope_delimeter' => ',', 'scope_delimeter' => ',',
'access_token_ttl' => null 'access_token_ttl' => 3600
); );
/** /**
* Supported response types * Supported response types
* @var array * @var array
*/ */
private $_responseTypes = array( private $_responseTypes = array(
'code' 'code'
); );
@ -46,8 +46,15 @@ class Server
* Supported grant types * Supported grant types
* @var array * @var array
*/ */
private $_grantTypes = array( private $_grantTypes = array(
'authorization_code' 'authorization_code' => false,
'client_credentials' => false,
'password' => false,
'refresh_token' => false,
);
private $_grantTypeCallbacks = array(
'password' => null
); );
/** /**
@ -75,16 +82,18 @@ class Server
* @var array * @var array
*/ */
public $errors = array( public $errors = 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.',
'unsupported_response_type' => 'The authorization server does not support obtaining an access token using this method.', 'unsupported_response_type' => 'The authorization server does not support obtaining an access token using this method.',
'invalid_scope' => 'The requested scope is invalid, unknown, or malformed. Check the "%s" scope.', '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.', '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.', '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_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) public function __construct($options = null)
{ {
if ($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; $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 * Check client authorise parameters
* *
@ -126,30 +156,22 @@ class Server
// Client ID // Client ID
if ( ! isset($authParams['client_id']) && ! isset($_GET['client_id'])) { if ( ! isset($authParams['client_id']) && ! isset($_GET['client_id'])) {
throw new ClientException(sprintf($this->errors['invalid_request'], 'client_id'), 0); 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'];
} }
$params['client_id'] = (isset($authParams['client_id'])) ?
$authParams['client_id'] :
$_GET['client_id'];
// Redirect URI // Redirect URI
if ( ! isset($authParams['redirect_uri']) && ! isset($_GET['redirect_uri'])) { if ( ! isset($authParams['redirect_uri']) && ! isset($_GET['redirect_uri'])) {
throw new ClientException(sprintf($this->errors['invalid_request'], 'redirect_uri'), 0); 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'];
} }
$params['redirect_uri'] = (isset($authParams['redirect_uri'])) ?
$authParams['redirect_uri'] :
$_GET['redirect_uri'];
// Validate client ID and redirect URI // Validate client ID and redirect URI
$clientDetails = $this->_dbCall( $clientDetails = $this->_dbCall(
'validateClient', 'validateClient',
@ -159,7 +181,6 @@ class Server
); );
if ($clientDetails === false) { if ($clientDetails === false) {
throw new ClientException($this->errors['invalid_client'], 8); throw new ClientException($this->errors['invalid_client'], 8);
} }
@ -167,29 +188,24 @@ class Server
// Response type // Response type
if ( ! isset($authParams['response_type']) && ! isset($_GET['response_type'])) { if ( ! isset($authParams['response_type']) && ! isset($_GET['response_type'])) {
throw new ClientException(sprintf($this->errors['invalid_request'], 'response_type'), 0); throw new ClientException(sprintf($this->errors['invalid_request'], 'response_type'), 0);
}
} else { $params['response_type'] = (isset($authParams['response_type'])) ?
$authParams['response_type'] :
$_GET['response_type'];
$params['response_type'] = (isset($authParams['response_type'])) ? // Ensure response type is one that is recognised
$authParams['response_type'] : if ( ! in_array($params['response_type'], $this->_responseTypes)) {
$_GET['response_type']; throw new ClientException($this->errors['unsupported_response_type'], 3);
// 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 // Get and validate scopes
if (isset($authParams['scope']) || isset($_GET['scope'])) { if (isset($authParams['scope']) || isset($_GET['scope'])) {
$scopes = (isset($_GET['scope'])) ? $scopes = (isset($_GET['scope'])) ?
$_GET['scope'] : $_GET['scope'] :
$authParams['scope']; $authParams['scope'];
$scopes = explode($this->_config['scope_delimeter'], $scopes); $scopes = explode($this->_config['scope_delimeter'], $scopes);
@ -204,7 +220,6 @@ class Server
} }
if (count($scopes) === 0) { if (count($scopes) === 0) {
throw new ClientException(sprintf($this->errors['invalid_request'], 'scope'), 0); throw new ClientException(sprintf($this->errors['invalid_request'], 'scope'), 0);
} }
@ -218,9 +233,7 @@ class Server
); );
if ($scopeDetails === false) { if ($scopeDetails === false) {
throw new ClientException(sprintf($this->errors['invalid_scope'], $scope), 4); throw new ClientException(sprintf($this->errors['invalid_scope'], $scope), 4);
} }
$params['scopes'][] = $scopeDetails; $params['scopes'][] = $scopeDetails;
@ -250,7 +263,7 @@ class Server
); );
// Create the new auth code // Create the new auth code
$authCode = $this->newAuthCode( $authCode = $this->_newAuthCode(
$authoriseParams['client_id'], $authoriseParams['client_id'],
'user', 'user',
$typeId, $typeId,
@ -268,7 +281,7 @@ class Server
* *
* @return string A unique code * @return string A unique code
*/ */
private function generateCode() private function _generateCode()
{ {
return sha1(uniqid(microtime())); return sha1(uniqid(microtime()));
} }
@ -284,53 +297,35 @@ class Server
* @param string $accessToken The access token (default = null) * @param string $accessToken The access token (default = null)
* @return string An authorisation code * @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(); $authCode = $this->_generateCode();
// If an access token exists then update the existing session with the // Delete any existing sessions just to be sure
// new authorisation code otherwise create a new session $this->_dbCall('deleteSession', $clientId, $type, $typeId);
if ($accessToken !== null) {
// Create a new session
$sessionId = $this->_dbCall(
'newSession',
$clientId,
$redirectUri,
$type,
$typeId,
$authCode,
null,
null,
'requested'
);
// Add the scopes
foreach ($scopes as $key => $scope) {
$this->_dbCall( $this->_dbCall(
'updateSession', 'addSessionScope',
$clientId, $sessionId,
$type, $scope['scope']
$typeId,
$authCode,
$accessToken,
'requested'
); );
} else {
// Delete any existing sessions just to be sure
$this->_dbCall('deleteSession', $clientId, $type, $typeId);
// Create a new session
$sessionId = $this->_dbCall(
'newSession',
$clientId,
$redirectUri,
$type,
$typeId,
$authCode,
null,
null,
'requested'
);
// Add the scopes
foreach ($scopes as $key => $scope) {
$this->_dbCall(
'addSessionScope',
$sessionId,
$scope['scope']
);
}
} }
return $authCode; return $authCode;
@ -347,40 +342,43 @@ class Server
*/ */
public function issueAccessToken($authParams = null) public function issueAccessToken($authParams = null)
{ {
$params = array();
if ( ! isset($authParams['grant_type']) && ! isset($_POST['grant_type'])) { if ( ! isset($authParams['grant_type']) && ! isset($_POST['grant_type'])) {
throw new ClientException(sprintf($this->errors['invalid_request'], 'grant_type'), 0); 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'];
$params['grant_type'] = (isset($authParams['grant_type'])) ? // Ensure grant type is one that is recognised and is enabled
$authParams['grant_type'] : if ( ! in_array($params['grant_type'], array_keys($this->_grantTypes)) || $this->_grantTypes[$params['grant_type']] !== true) {
$_POST['grant_type']; throw new ClientException(sprintf($this->errors['unsupported_grant_type'], $params['grant_type']), 7);
// 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);
}
} }
switch ($params['grant_type']) switch ($params['grant_type'])
{ {
case 'authorization_code': // Authorization code grant case 'authorization_code': // Authorization code grant
return $this->completeAuthCodeGrant($authParams, $params); return $this->_completeAuthCodeGrant($authParams, $params);
break; break;
case 'refresh_token': // Refresh token
case 'password': // Resource owner password credentials grant
case 'client_credentials': // Client 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 default: // Unsupported
throw new ServerException($this->errors['server_error'] . 'Tried to process an unsuppported grant type.', 5); throw new ServerException($this->errors['server_error'] . 'Tried to process an unsuppported grant type.', 5);
break; break;
} }
// @codeCoverageIgnoreEnd
} }
/** /**
@ -393,47 +391,35 @@ class Server
* *
* @return array Authorise request parameters * @return array Authorise request parameters
*/ */
private function completeAuthCodeGrant($authParams = array(), $params = array()) private function _completeAuthCodeGrant($authParams = array(), $params = array())
{ {
// Client ID // Client ID
if ( ! isset($authParams['client_id']) && ! isset($_POST['client_id'])) { if ( ! isset($authParams['client_id']) && ! isset($_POST['client_id'])) {
throw new ClientException(sprintf($this->errors['invalid_request'], 'client_id'), 0); 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'];
} }
$params['client_id'] = (isset($authParams['client_id'])) ?
$authParams['client_id'] :
$_POST['client_id'];
// Client secret // Client secret
if ( ! isset($authParams['client_secret']) && ! isset($_POST['client_secret'])) { if ( ! isset($authParams['client_secret']) && ! isset($_POST['client_secret'])) {
throw new ClientException(sprintf($this->errors['invalid_request'], 'client_secret'), 0); 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'];
} }
$params['client_secret'] = (isset($authParams['client_secret'])) ?
$authParams['client_secret'] :
$_POST['client_secret'];
// Redirect URI // Redirect URI
if ( ! isset($authParams['redirect_uri']) && ! isset($_POST['redirect_uri'])) { if ( ! isset($authParams['redirect_uri']) && ! isset($_POST['redirect_uri'])) {
throw new ClientException(sprintf($this->errors['invalid_request'], 'redirect_uri'), 0); 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'];
} }
$params['redirect_uri'] = (isset($authParams['redirect_uri'])) ?
$authParams['redirect_uri'] :
$_POST['redirect_uri'];
// Validate client ID and redirect URI // Validate client ID and redirect URI
$clientDetails = $this->_dbCall( $clientDetails = $this->_dbCall(
'validateClient', 'validateClient',
@ -443,25 +429,19 @@ class Server
); );
if ($clientDetails === false) { if ($clientDetails === false) {
throw new ClientException($this->errors['invalid_client'], 8); throw new ClientException($this->errors['invalid_client'], 8);
} }
// The authorization code // The authorization code
if ( ! isset($authParams['code']) && ! isset($_POST['code'])) { if ( ! isset($authParams['code']) && ! isset($_POST['code'])) {
throw new ClientException(sprintf($this->errors['invalid_request'], 'code'), 0); 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 $params['code'] = (isset($authParams['code'])) ?
// request_uri $authParams['code'] :
$_POST['code'];
// Verify the authorization code matches the client_id and the request_uri
$session = $this->_dbCall( $session = $this->_dbCall(
'validateAuthCode', 'validateAuthCode',
$params['client_id'], $params['client_id'],
@ -470,42 +450,306 @@ class Server
); );
if ( ! $session) { if ( ! $session) {
throw new ClientException(sprintf($this->errors['invalid_grant'], 'code'), 9); 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();
$accessTokenExpires = ($this->_config['access_token_ttl'] === null) ?
null :
time() + $this->_config['access_token_ttl'];
$this->_dbCall(
'updateSession',
$session['id'],
null,
$accessToken,
$accessTokenExpires,
'granted'
);
// Update the session's scopes to reference the access token
$this->_dbCall(
'updateSessionScopeAccessToken',
$session['id'],
$accessToken
);
return array(
'access_token' => $accessToken,
'token_type' => 'bearer',
'expires_in' => $this->_config['access_token_ttl']
);
} }
// A session ID was returned so update it with an access token,
// remove the authorisation code, change the stage to 'granted'
$accessToken = $this->_generateCode();
$refreshToken = ($this->_grantTypes['refresh_token']) ?
$this->_generateCode() :
null;
$accessTokenExpires = time() + $this->_config['access_token_ttl'];
$accessTokenExpiresIn = $this->_config['access_token_ttl'];
$this->_dbCall(
'updateSession',
$session['id'],
null,
$accessToken,
$refreshToken,
$accessTokenExpires,
'granted'
);
// Update the session's scopes to reference the access token
$this->_dbCall(
'updateSessionScopeAccessToken',
$session['id'],
$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' => $accessTokenExpires,
'expires_in' => $accessTokenExpiresIn
);
} }
/** /**
@ -519,19 +763,7 @@ class Server
*/ */
public function redirectUri($redirectUri, $params = array(), $queryDelimeter = '?') public function redirectUri($redirectUri, $params = array(), $queryDelimeter = '?')
{ {
return (strstr($redirectUri, $queryDelimeter)) ? $redirectUri . '&' . http_build_query($params) : $redirectUri . $queryDelimeter . http_build_query($params);
if (strstr($redirectUri, $queryDelimeter)) {
$redirectUri = $redirectUri . '&' . http_build_query($params);
} else {
$redirectUri = $redirectUri . $queryDelimeter . http_build_query($params);
}
return $redirectUri;
} }
/** /**

View File

@ -4,151 +4,165 @@ use Oauth2\Authentication\Database;
class OAuthdb implements Database class OAuthdb implements Database
{ {
private $sessions = array(); private $sessions = array();
private $sessions_client_type_id = array(); private $sessions_client_type_id = array();
private $sessions_code = array(); private $sessions_code = array();
private $session_scopes = array(); private $session_scopes = array();
private $clients = array(0 => array( private $clients = array(0 => array(
'client_id' => 'test', 'client_id' => 'test',
'client_secret' => 'test', 'client_secret' => 'test',
'redirect_uri' => 'http://example.com/test', 'redirect_uri' => 'http://example.com/test',
'name' => 'Test Client' 'name' => 'Test Client'
)); ));
private $scopes = array('test' => array( private $scopes = array('test' => array(
'id' => 1, 'id' => 1,
'scope' => 'test', 'scope' => 'test',
'name' => 'test', 'name' => 'test',
'description' => 'test' 'description' => 'test'
)); ));
public function validateClient($clientId, $clientSecret = null, $redirectUri = null) public function validateClient($clientId, $clientSecret = null, $redirectUri = null)
{ {
if ($clientId !== $this->clients[0]['client_id']) if ($clientId !== $this->clients[0]['client_id']) {
{ return false;
return false; }
}
if ($clientSecret !== null && $clientSecret !== $this->clients[0]['client_secret']) if ($clientSecret !== null && $clientSecret !== $this->clients[0]['client_secret']) {
{ return false;
return false; }
}
if ($redirectUri !== null && $redirectUri !== $this->clients[0]['redirect_uri']) if ($redirectUri !== null && $redirectUri !== $this->clients[0]['redirect_uri']) {
{ return false;
return false; }
}
return $this->clients[0]; 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); $id = count($this->sessions);
$this->sessions[$id] = array( $this->sessions[$id] = array(
'id' => $id, 'id' => $id,
'client_id' => $clientId, 'client_id' => $clientId,
'redirect_uri' => $redirectUri, 'redirect_uri' => $redirectUri,
'owner_type' => $type, 'owner_type' => $type,
'owner_id' => $typeId, 'owner_id' => $typeId,
'auth_code' => $authCode, 'auth_code' => $authCode,
'access_token' => $accessToken, 'access_token' => $accessToken,
'access_token_expire' => $accessTokenExpire, 'refresh_token' => $refreshToken,
'stage' => $stage 'access_token_expire' => $accessTokenExpire,
); 'stage' => $stage
);
$this->sessions_client_type_id[$clientId . ':' . $type . ':' . $typeId] = $id; $this->sessions_client_type_id[$clientId . ':' . $type . ':' . $typeId] = $id;
$this->sessions_code[$clientId . ':' . $redirectUri . ':' . $authCode] = $id; $this->sessions_code[$clientId . ':' . $redirectUri . ':' . $authCode] = $id;
return $id; 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]['auth_code'] = $authCode;
$this->sessions[$sessionId]['access_token'] = $accessToken; $this->sessions[$sessionId]['access_token'] = $accessToken;
$this->sessions[$sessionId]['access_token_expire'] = $accessTokenExpire; $this->sessions[$sessionId]['refresh_token'] = $refreshToken;
$this->sessions[$sessionId]['stage'] = $stage; $this->sessions[$sessionId]['access_token_expire'] = $accessTokenExpire;
$this->sessions[$sessionId]['stage'] = $stage;
return true; return true;
} }
public function deleteSession($clientId, $type, $typeId) public function deleteSession($clientId, $type, $typeId)
{ {
$key = $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]]);
unset($this->sessions[$this->sessions_client_type_id[$key]]); }
} return true;
return true; }
}
public function validateAuthCode($clientId, $redirectUri, $authCode) public function refreshToken($currentRefreshToken, $newAccessToken, $newRefreshToken, $accessTokenExpires)
{ {
$key = $clientId . ':' . $redirectUri . ':' . $authCode; die('not implemented refreshToken');
}
if (isset($this->sessions_code[$key])) public function validateAuthCode($clientId, $redirectUri, $authCode)
{ {
return $this->sessions[$this->sessions_code[$key]]; $key = $clientId . ':' . $redirectUri . ':' . $authCode;
}
return false; if (isset($this->sessions_code[$key])) {
} return $this->sessions[$this->sessions_code[$key]];
}
public function hasSession($type, $typeId, $clientId) return false;
{ }
die('not implemented hasSession');
}
public function getAccessToken($sessionId) public function hasSession($type, $typeId, $clientId)
{ {
die('not implemented getAccessToken'); die('not implemented hasSession');
} }
public function removeAuthCode($sessionId) public function getAccessToken($sessionId)
{ {
die('not implemented removeAuthCode'); die('not implemented getAccessToken');
} }
public function setAccessToken( public function removeAuthCode($sessionId)
$sessionId, {
$accessToken die('not implemented removeAuthCode');
) }
{
die('not implemented setAccessToken');
}
public function addSessionScope($sessionId, $scope) public function setAccessToken($sessionId, $accessToken)
{ {
if ( ! isset($this->session_scopes[$sessionId])) die('not implemented setAccessToken');
{ }
$this->session_scopes[$sessionId] = array();
}
$this->session_scopes[$sessionId][] = $scope; public function addSessionScope($sessionId, $scope)
{
if ( ! isset($this->session_scopes[$sessionId])) {
$this->session_scopes[$sessionId] = array();
}
return true; $this->session_scopes[$sessionId][] = $scope;
}
public function getScope($scope) return true;
{ }
if ( ! isset($this->scopes[$scope]))
{
return false;
}
return $this->scopes[$scope]; public function getScope($scope)
} {
if ( ! isset($this->scopes[$scope])) {
return false;
}
public function updateSessionScopeAccessToken($sessionId, $accessToken) return $this->scopes[$scope];
{ }
return true;
}
public function accessTokenScopes($accessToken) public function updateSessionScopeAccessToken($sessionId, $accessToken)
{ {
die('not implemented accessTokenScopes'); return true;
} }
public function accessTokenScopes($accessToken)
{
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;
}
} }

File diff suppressed because it is too large Load Diff

View File

@ -2,120 +2,123 @@
class Resource_Server_test extends PHPUnit_Framework_TestCase { class Resource_Server_test extends PHPUnit_Framework_TestCase {
function setUp() function setUp()
{ {
require_once('database_mock.php'); require_once 'src/OAuth2/Resource/Server.php';
$this->server = new Oauth2\Resource\Server(); require_once 'src/OAuth2/Resource/Database.php';
$this->db = new ResourceDB();
$this->assertInstanceOf('Oauth2\Resource\Database', $this->db); require_once('database_mock.php');
$this->server->registerDbAbstractor($this->db); $this->server = new Oauth2\Resource\Server();
} $this->db = new ResourceDB();
function test_init_POST() $this->assertInstanceOf('Oauth2\Resource\Database', $this->db);
{ $this->server->registerDbAbstractor($this->db);
$_SERVER['REQUEST_METHOD'] = 'POST'; }
$_POST['oauth_token'] = 'test12345';
$this->server->init(); function test_init_POST()
{
$_SERVER['REQUEST_METHOD'] = 'POST';
$_POST['oauth_token'] = 'test12345';
$reflector = new ReflectionClass($this->server); $this->server->init();
$_accessToken = $reflector->getProperty('_accessToken'); $reflector = new ReflectionClass($this->server);
$_accessToken->setAccessible(true);
$_type = $reflector->getProperty('_type'); $_accessToken = $reflector->getProperty('_accessToken');
$_type->setAccessible(true); $_accessToken->setAccessible(true);
$_typeId = $reflector->getProperty('_typeId'); $_type = $reflector->getProperty('_type');
$_typeId->setAccessible(true); $_type->setAccessible(true);
$_scopes = $reflector->getProperty('_scopes'); $_typeId = $reflector->getProperty('_typeId');
$_scopes->setAccessible(true); $_typeId->setAccessible(true);
$this->assertEquals($_accessToken->getValue($this->server), $_POST['oauth_token']); $_scopes = $reflector->getProperty('_scopes');
$this->assertEquals($_type->getValue($this->server), 'user'); $_scopes->setAccessible(true);
$this->assertEquals($_typeId->getValue($this->server), 123);
$this->assertEquals($_scopes->getValue($this->server), array('foo', 'bar'));
}
function test_init_GET() $this->assertEquals($_accessToken->getValue($this->server), $_POST['oauth_token']);
{ $this->assertEquals($_type->getValue($this->server), 'user');
$_GET['oauth_token'] = 'test12345'; $this->assertEquals($_typeId->getValue($this->server), 123);
$this->assertEquals($_scopes->getValue($this->server), array('foo', 'bar'));
}
$this->server->init(); function test_init_GET()
{
$_GET['oauth_token'] = 'test12345';
$reflector = new ReflectionClass($this->server); $this->server->init();
$_accessToken = $reflector->getProperty('_accessToken'); $reflector = new ReflectionClass($this->server);
$_accessToken->setAccessible(true);
$_type = $reflector->getProperty('_type'); $_accessToken = $reflector->getProperty('_accessToken');
$_type->setAccessible(true); $_accessToken->setAccessible(true);
$_typeId = $reflector->getProperty('_typeId'); $_type = $reflector->getProperty('_type');
$_typeId->setAccessible(true); $_type->setAccessible(true);
$_scopes = $reflector->getProperty('_scopes'); $_typeId = $reflector->getProperty('_typeId');
$_scopes->setAccessible(true); $_typeId->setAccessible(true);
$this->assertEquals($_accessToken->getValue($this->server), $_GET['oauth_token']); $_scopes = $reflector->getProperty('_scopes');
$this->assertEquals($_type->getValue($this->server), 'user'); $_scopes->setAccessible(true);
$this->assertEquals($_typeId->getValue($this->server), 123);
$this->assertEquals($_scopes->getValue($this->server), array('foo', 'bar'));
}
function test_init_header() $this->assertEquals($_accessToken->getValue($this->server), $_GET['oauth_token']);
{ $this->assertEquals($_type->getValue($this->server), 'user');
// Test with authorisation header $this->assertEquals($_typeId->getValue($this->server), 123);
$this->markTestIncomplete('Authorisation header test has not been implemented yet.'); $this->assertEquals($_scopes->getValue($this->server), array('foo', 'bar'));
} }
/** function test_init_header()
* @expectedException \Oauth2\Resource\ClientException {
* @expectedExceptionMessage An access token was not presented with the request // Test with authorisation header
*/ $this->markTestIncomplete('Authorisation header test has not been implemented yet.');
function test_init_missingToken() }
{
$this->server->init();
}
/** /**
* @expectedException \Oauth2\Resource\ClientException * @expectedException \Oauth2\Resource\ClientException
* @expectedExceptionMessage The access token is not registered with the resource server * @expectedExceptionMessage An access token was not presented with the request
*/ */
function test_init_wrongToken() function test_init_missingToken()
{ {
$_POST['oauth_token'] = 'blah'; $this->server->init();
$_SERVER['REQUEST_METHOD'] = 'POST'; }
$this->server->init(); /**
} * @expectedException \Oauth2\Resource\ClientException
* @expectedExceptionMessage The access token is not registered with the resource server
*/
function test_init_wrongToken()
{
$_POST['oauth_token'] = 'blah';
$_SERVER['REQUEST_METHOD'] = 'POST';
function test_hasScope() $this->server->init();
{ }
$_POST['oauth_token'] = 'test12345';
$_SERVER['REQUEST_METHOD'] = 'POST';
$this->server->init(); function test_hasScope()
{
$_POST['oauth_token'] = 'test12345';
$_SERVER['REQUEST_METHOD'] = 'POST';
$this->assertEquals(true, $this->server->hasScope('foo')); $this->server->init();
$this->assertEquals(true, $this->server->hasScope('bar'));
$this->assertEquals(true, $this->server->hasScope(array('foo', 'bar')));
$this->assertEquals(false, $this->server->hasScope('foobar')); $this->assertEquals(true, $this->server->hasScope('foo'));
$this->assertEquals(false, $this->server->hasScope(array('foobar'))); $this->assertEquals(true, $this->server->hasScope('bar'));
} $this->assertEquals(true, $this->server->hasScope(array('foo', 'bar')));
function test___call() $this->assertEquals(false, $this->server->hasScope('foobar'));
{ $this->assertEquals(false, $this->server->hasScope(array('foobar')));
$_POST['oauth_token'] = 'test12345'; }
$_SERVER['REQUEST_METHOD'] = 'POST';
$this->server->init(); function test___call()
{
$_POST['oauth_token'] = 'test12345';
$_SERVER['REQUEST_METHOD'] = 'POST';
$this->assertEquals(123, $this->server->isUser()); $this->server->init();
$this->assertEquals(false, $this->server->isMachine());
} $this->assertEquals(123, $this->server->isUser());
$this->assertEquals(false, $this->server->isMachine());
}
} }