Merge branch 'master' into fix-pkce-implementation

This commit is contained in:
Andrew Millington
2017-12-28 16:37:37 +00:00
committed by GitHub
30 changed files with 331 additions and 154 deletions

View File

@@ -3,6 +3,7 @@
* @author Alex Bilbie <hello@alexbilbie.com>
* @copyright Copyright (c) Alex Bilbie
* @license http://mit-license.org/
*
* @link https://github.com/thephpleague/oauth2-server
*/
@@ -70,6 +71,11 @@ class AuthorizationServer implements EmitterAwareInterface
*/
private $encryptionKey;
/**
* @var string
*/
private $defaultScope = '';
/**
* New server instance.
*
@@ -96,7 +102,6 @@ class AuthorizationServer implements EmitterAwareInterface
$privateKey = new CryptKey($privateKey);
}
$this->privateKey = $privateKey;
$this->encryptionKey = $encryptionKey;
$this->responseType = $responseType;
}
@@ -116,6 +121,7 @@ class AuthorizationServer implements EmitterAwareInterface
$grantType->setAccessTokenRepository($this->accessTokenRepository);
$grantType->setClientRepository($this->clientRepository);
$grantType->setScopeRepository($this->scopeRepository);
$grantType->setDefaultScope($this->defaultScope);
$grantType->setPrivateKey($this->privateKey);
$grantType->setEmitter($this->getEmitter());
$grantType->setEncryptionKey($this->encryptionKey);
@@ -172,17 +178,19 @@ class AuthorizationServer implements EmitterAwareInterface
public function respondToAccessTokenRequest(ServerRequestInterface $request, ResponseInterface $response)
{
foreach ($this->enabledGrantTypes as $grantType) {
if ($grantType->canRespondToAccessTokenRequest($request)) {
$tokenResponse = $grantType->respondToAccessTokenRequest(
$request,
$this->getResponseType(),
$this->grantTypeAccessTokenTTL[$grantType->getIdentifier()]
);
if ($tokenResponse instanceof ResponseTypeInterface) {
return $tokenResponse->generateHttpResponse($response);
}
if (!$grantType->canRespondToAccessTokenRequest($request)) {
continue;
}
$tokenResponse = $grantType->respondToAccessTokenRequest(
$request,
$this->getResponseType(),
$this->grantTypeAccessTokenTTL[$grantType->getIdentifier()]
);
if ($tokenResponse instanceof ResponseTypeInterface) {
return $tokenResponse->generateHttpResponse($response);
}
}
throw OAuthServerException::unsupportedGrantType();
@@ -204,4 +212,14 @@ class AuthorizationServer implements EmitterAwareInterface
return $this->responseType;
}
/**
* Set the default scope for the authorization server.
*
* @param string $defaultScope
*/
public function setDefaultScope($defaultScope)
{
$this->defaultScope = $defaultScope;
}
}

View File

@@ -41,7 +41,7 @@ class BearerTokenValidator implements AuthorizationValidatorInterface
}
/**
* Set the private key
* Set the public key
*
* @param \League\OAuth2\Server\CryptKey $key
*/

View File

@@ -1,9 +1,11 @@
<?php
/**
* Public/private key encryption.
*
* @author Alex Bilbie <hello@alexbilbie.com>
* @copyright Copyright (c) Alex Bilbie
* @license http://mit-license.org/
*
* @link https://github.com/thephpleague/oauth2-server
*/
@@ -24,6 +26,7 @@ trait CryptTrait
* @param string $unencryptedData
*
* @throws \LogicException
*
* @return string
*/
protected function encrypt($unencryptedData)
@@ -41,6 +44,7 @@ trait CryptTrait
* @param string $encryptedData
*
* @throws \LogicException
*
* @return string
*/
protected function decrypt($encryptedData)

View File

@@ -105,10 +105,15 @@ class OAuthServerException extends \Exception
public static function invalidScope($scope, $redirectUri = null)
{
$errorMessage = 'The requested scope is invalid, unknown, or malformed';
$hint = sprintf(
'Check the `%s` scope',
htmlspecialchars($scope, ENT_QUOTES, 'UTF-8', false)
);
if (empty($scope)) {
$hint = 'Specify a scope in the request or set a default scope';
} else {
$hint = sprintf(
'Check the `%s` scope',
htmlspecialchars($scope, ENT_QUOTES, 'UTF-8', false)
);
}
return new static($errorMessage, 5, 'invalid_scope', 400, $hint, $redirectUri);
}

View File

@@ -81,6 +81,11 @@ abstract class AbstractGrant implements GrantTypeInterface
*/
protected $privateKey;
/**
* @string
*/
protected $defaultScope;
/**
* @param ClientRepositoryInterface $clientRepository
*/
@@ -147,6 +152,14 @@ abstract class AbstractGrant implements GrantTypeInterface
$this->privateKey = $key;
}
/**
* @param string $scope
*/
public function setDefaultScope($scope)
{
$this->defaultScope = $scope;
}
/**
* Validate the client.
*
@@ -211,18 +224,14 @@ abstract class AbstractGrant implements GrantTypeInterface
*
* @return ScopeEntityInterface[]
*/
public function validateScopes(
$scopes,
$redirectUri = null
) {
$scopesList = array_filter(
explode(self::SCOPE_DELIMITER_STRING, trim($scopes)),
function ($scope) {
return !empty($scope);
}
);
public function validateScopes($scopes, $redirectUri = null)
{
$scopesList = array_filter(explode(self::SCOPE_DELIMITER_STRING, trim($scopes)), function ($scope) {
return !empty($scope);
});
$validScopes = [];
$scopes = [];
foreach ($scopesList as $scopeItem) {
$scope = $this->scopeRepository->getScopeEntityByIdentifier($scopeItem);
@@ -230,10 +239,10 @@ abstract class AbstractGrant implements GrantTypeInterface
throw OAuthServerException::invalidScope($scopeItem, $redirectUri);
}
$scopes[] = $scope;
$validScopes[] = $scope;
}
return $scopes;
return $validScopes;
}
/**

View File

@@ -153,7 +153,7 @@ class AuthCodeGrant extends AbstractAuthorizeGrant
case 'S256':
if (
hash_equals(
rtrim(strtr(base64_encode(hash('sha256', $codeVerifier, true)), '+/', '-_'), '='),
hash('sha256', strtr(rtrim(base64_encode($codeVerifier), '='), '+/', '-_')),
$authCodePayload->code_challenge
) === false
) {
@@ -249,10 +249,15 @@ class AuthCodeGrant extends AbstractAuthorizeGrant
$this->getEmitter()->emit(new RequestEvent(RequestEvent::CLIENT_AUTHENTICATION_FAILED, $request));
throw OAuthServerException::invalidClient();
}
} elseif (is_array($client->getRedirectUri()) && count($client->getRedirectUri()) !== 1
|| empty($client->getRedirectUri())
) {
$this->getEmitter()->emit(new RequestEvent(RequestEvent::CLIENT_AUTHENTICATION_FAILED, $request));
throw OAuthServerException::invalidClient();
}
$scopes = $this->validateScopes(
$this->getQueryStringParameter('scope', $request),
$this->getQueryStringParameter('scope', $request, $this->defaultScope),
is_array($client->getRedirectUri())
? $client->getRedirectUri()[0]
: $client->getRedirectUri()

View File

@@ -29,13 +29,13 @@ class ClientCredentialsGrant extends AbstractGrant
) {
// Validate request
$client = $this->validateClient($request);
$scopes = $this->validateScopes($this->getRequestParameter('scope', $request));
$scopes = $this->validateScopes($this->getRequestParameter('scope', $request, $this->defaultScope));
// Finalize the requested scopes
$scopes = $this->scopeRepository->finalizeScopes($scopes, $this->getIdentifier(), $client);
$finalizedScopes = $this->scopeRepository->finalizeScopes($scopes, $this->getIdentifier(), $client);
// Issue and persist access token
$accessToken = $this->issueAccessToken($accessTokenTTL, $client, null, $scopes);
$accessToken = $this->issueAccessToken($accessTokenTTL, $client, null, $finalizedScopes);
// Inject access token into response type
$responseType->setAccessToken($accessToken);

View File

@@ -119,6 +119,13 @@ interface GrantTypeInterface extends EmitterAwareInterface
*/
public function setScopeRepository(ScopeRepositoryInterface $scopeRepository);
/**
* Set the default scope.
*
* @param string $scope
*/
public function setDefaultScope($scope);
/**
* Set the path to the private key.
*

View File

@@ -27,11 +27,18 @@ class ImplicitGrant extends AbstractAuthorizeGrant
private $accessTokenTTL;
/**
* @param \DateInterval $accessTokenTTL
* @var string
*/
public function __construct(\DateInterval $accessTokenTTL)
private $queryDelimiter;
/**
* @param \DateInterval $accessTokenTTL
* @param string $queryDelimiter
*/
public function __construct(\DateInterval $accessTokenTTL, $queryDelimiter = '#')
{
$this->accessTokenTTL = $accessTokenTTL;
$this->queryDelimiter = $queryDelimiter;
}
/**
@@ -95,7 +102,7 @@ class ImplicitGrant extends AbstractAuthorizeGrant
public function canRespondToAuthorizationRequest(ServerRequestInterface $request)
{
return (
array_key_exists('response_type', $request->getQueryParams())
isset($request->getQueryParams()['response_type'])
&& $request->getQueryParams()['response_type'] === 'token'
&& isset($request->getQueryParams()['client_id'])
);
@@ -142,17 +149,22 @@ class ImplicitGrant extends AbstractAuthorizeGrant
$this->getEmitter()->emit(new RequestEvent(RequestEvent::CLIENT_AUTHENTICATION_FAILED, $request));
throw OAuthServerException::invalidClient();
}
} elseif (is_array($client->getRedirectUri()) && count($client->getRedirectUri()) !== 1
|| empty($client->getRedirectUri())
) {
$this->getEmitter()->emit(new RequestEvent(RequestEvent::CLIENT_AUTHENTICATION_FAILED, $request));
throw OAuthServerException::invalidClient();
}
$scopes = $this->validateScopes(
$this->getQueryStringParameter('scope', $request),
$this->getQueryStringParameter('scope', $request, $this->defaultScope),
is_array($client->getRedirectUri())
? $client->getRedirectUri()[0]
: $client->getRedirectUri()
);
// Finalize the requested scopes
$scopes = $this->scopeRepository->finalizeScopes(
$finalizedScopes = $this->scopeRepository->finalizeScopes(
$scopes,
$this->getIdentifier(),
$client
@@ -165,7 +177,7 @@ class ImplicitGrant extends AbstractAuthorizeGrant
$authorizationRequest->setClient($client);
$authorizationRequest->setRedirectUri($redirectUri);
$authorizationRequest->setState($stateParameter);
$authorizationRequest->setScopes($scopes);
$authorizationRequest->setScopes($finalizedScopes);
return $authorizationRequest;
}
@@ -204,7 +216,7 @@ class ImplicitGrant extends AbstractAuthorizeGrant
'expires_in' => $accessToken->getExpiryDateTime()->getTimestamp() - (new \DateTime())->getTimestamp(),
'state' => $authorizationRequest->getState(),
],
'#'
$this->queryDelimiter
)
);

View File

@@ -49,14 +49,14 @@ class PasswordGrant extends AbstractGrant
) {
// Validate request
$client = $this->validateClient($request);
$scopes = $this->validateScopes($this->getRequestParameter('scope', $request));
$scopes = $this->validateScopes($this->getRequestParameter('scope', $request, $this->defaultScope));
$user = $this->validateUser($request, $client);
// Finalize the requested scopes
$scopes = $this->scopeRepository->finalizeScopes($scopes, $this->getIdentifier(), $client, $user->getIdentifier());
$finalizedScopes = $this->scopeRepository->finalizeScopes($scopes, $this->getIdentifier(), $client, $user->getIdentifier());
// Issue and persist new tokens
$accessToken = $this->issueAccessToken($accessTokenTTL, $client, $user->getIdentifier(), $scopes);
$accessToken = $this->issueAccessToken($accessTokenTTL, $client, $user->getIdentifier(), $finalizedScopes);
$refreshToken = $this->issueRefreshToken($accessToken);
// Inject tokens into response

View File

@@ -44,28 +44,17 @@ class RefreshTokenGrant extends AbstractGrant
// Validate request
$client = $this->validateClient($request);
$oldRefreshToken = $this->validateOldRefreshToken($request, $client->getIdentifier());
$scopes = $this->validateScopes($this->getRequestParameter('scope', $request));
$scopes = $this->validateScopes($this->getRequestParameter(
'scope',
$request,
implode(self::SCOPE_DELIMITER_STRING, $oldRefreshToken['scopes']))
);
// If no new scopes are requested then give the access token the original session scopes
if (count($scopes) === 0) {
$scopes = array_map(function ($scopeId) use ($client) {
$scope = $this->scopeRepository->getScopeEntityByIdentifier($scopeId);
if ($scope instanceof ScopeEntityInterface === false) {
// @codeCoverageIgnoreStart
throw OAuthServerException::invalidScope($scopeId);
// @codeCoverageIgnoreEnd
}
return $scope;
}, $oldRefreshToken['scopes']);
} else {
// The OAuth spec says that a refreshed access token can have the original scopes or fewer so ensure
// the request doesn't include any new scopes
foreach ($scopes as $scope) {
if (in_array($scope->getIdentifier(), $oldRefreshToken['scopes']) === false) {
throw OAuthServerException::invalidScope($scope->getIdentifier());
}
// The OAuth spec says that a refreshed access token can have the original scopes or fewer so ensure
// the request doesn't include any new scopes
foreach ($scopes as $scope) {
if (in_array($scope->getIdentifier(), $oldRefreshToken['scopes']) === false) {
throw OAuthServerException::invalidScope($scope->getIdentifier());
}
}

View File

@@ -60,5 +60,4 @@ abstract class AbstractResponseType implements ResponseTypeInterface
{
$this->privateKey = $key;
}
}