Merge remote-tracking branch 'upstream/master'

This commit is contained in:
Andrew Millington
2018-02-28 19:45:41 +00:00
34 changed files with 746 additions and 383 deletions

View File

@@ -17,6 +17,7 @@ use League\OAuth2\Server\Repositories\AccessTokenRepositoryInterface;
use League\OAuth2\Server\Repositories\ClientRepositoryInterface;
use League\OAuth2\Server\Repositories\ScopeRepositoryInterface;
use League\OAuth2\Server\RequestTypes\AuthorizationRequest;
use League\OAuth2\Server\ResponseTypes\AbstractResponseType;
use League\OAuth2\Server\ResponseTypes\BearerTokenResponse;
use League\OAuth2\Server\ResponseTypes\ResponseTypeInterface;
use Psr\Http\Message\ResponseInterface;
@@ -190,7 +191,6 @@ class AuthorizationServer implements EmitterAwareInterface
if ($tokenResponse instanceof ResponseTypeInterface) {
return $tokenResponse->generateHttpResponse($response);
}
}
throw OAuthServerException::unsupportedGrantType();
@@ -207,7 +207,9 @@ class AuthorizationServer implements EmitterAwareInterface
$this->responseType = new BearerTokenResponse();
}
$this->responseType->setPrivateKey($this->privateKey);
if ($this->responseType instanceof AbstractResponseType === true) {
$this->responseType->setPrivateKey($this->privateKey);
}
$this->responseType->setEncryptionKey($this->encryptionKey);
return $this->responseType;

View File

@@ -14,7 +14,7 @@ namespace League\OAuth2\Server;
class CryptKey
{
const RSA_KEY_PATTERN =
'/^(-----BEGIN (RSA )?(PUBLIC|PRIVATE) KEY-----\n)(.|\n)+(-----END (RSA )?(PUBLIC|PRIVATE) KEY-----)$/';
'/^(-----BEGIN (RSA )?(PUBLIC|PRIVATE) KEY-----)\R.*(-----END (RSA )?(PUBLIC|PRIVATE) KEY-----)\R?$/s';
/**
* @var string
@@ -48,9 +48,9 @@ class CryptKey
if ($keyPermissionsCheck === true) {
// Verify the permissions of the key
$keyPathPerms = decoct(fileperms($keyPath) & 0777);
if (in_array($keyPathPerms, ['600', '660'], true) === false) {
if (in_array($keyPathPerms, ['400', '440', '600', '660'], true) === false) {
trigger_error(sprintf(
'Key file "%s" permissions are not correct, should be 600 or 660 instead of %s',
'Key file "%s" permissions are not correct, recommend changing to 600 or 660 instead of %s',
$keyPath,
$keyPathPerms
), E_USER_NOTICE);
@@ -73,7 +73,11 @@ class CryptKey
$tmpDir = sys_get_temp_dir();
$keyPath = $tmpDir . '/' . sha1($key) . '.key';
if (!file_exists($keyPath) && !touch($keyPath)) {
if (file_exists($keyPath)) {
return 'file://' . $keyPath;
}
if (!touch($keyPath)) {
// @codeCoverageIgnoreStart
throw new \RuntimeException(sprintf('"%s" key file could not be created', $keyPath));
// @codeCoverageIgnoreEnd

View File

@@ -9,6 +9,7 @@
namespace League\OAuth2\Server\Entities;
use Lcobucci\JWT\Token;
use League\OAuth2\Server\CryptKey;
interface AccessTokenEntityInterface extends TokenInterface
@@ -18,7 +19,7 @@ interface AccessTokenEntityInterface extends TokenInterface
*
* @param CryptKey $privateKey
*
* @return string
* @return Token
*/
public function convertToJWT(CryptKey $privateKey);
}

View File

@@ -21,7 +21,7 @@ interface RefreshTokenEntityInterface
/**
* Set the token's identifier.
*
* @param $identifier
* @param mixed $identifier
*/
public function setIdentifier($identifier);

View File

@@ -21,7 +21,7 @@ interface TokenInterface
/**
* Set the token's identifier.
*
* @param $identifier
* @param mixed $identifier
*/
public function setIdentifier($identifier);
@@ -42,14 +42,14 @@ interface TokenInterface
/**
* Set the identifier of the user associated with the token.
*
* @param string|int $identifier The identifier of the user
* @param string|int|null $identifier The identifier of the user
*/
public function setUserIdentifier($identifier);
/**
* Get the token user's identifier.
*
* @return string|int
* @return string|int|null
*/
public function getUserIdentifier();

View File

@@ -12,6 +12,7 @@ namespace League\OAuth2\Server\Entities\Traits;
use Lcobucci\JWT\Builder;
use Lcobucci\JWT\Signer\Key;
use Lcobucci\JWT\Signer\Rsa\Sha256;
use Lcobucci\JWT\Token;
use League\OAuth2\Server\CryptKey;
use League\OAuth2\Server\Entities\ClientEntityInterface;
use League\OAuth2\Server\Entities\ScopeEntityInterface;
@@ -23,7 +24,7 @@ trait AccessTokenTrait
*
* @param CryptKey $privateKey
*
* @return string
* @return Token
*/
public function convertToJWT(CryptKey $privateKey)
{

View File

@@ -11,7 +11,7 @@ namespace League\OAuth2\Server\Entities\Traits;
trait EntityTrait
{
/*
/**
* @var string
*/
protected $identifier;

View File

@@ -25,7 +25,7 @@ trait TokenEntityTrait
protected $expiryDateTime;
/**
* @var string|int
* @var string|int|null
*/
protected $userIdentifier;
@@ -77,7 +77,7 @@ trait TokenEntityTrait
/**
* Set the identifier of the user associated with the token.
*
* @param string|int $identifier The identifier of the user
* @param string|int|null $identifier The identifier of the user
*/
public function setUserIdentifier($identifier)
{
@@ -87,7 +87,7 @@ trait TokenEntityTrait
/**
* Get the token user's identifier.
*
* @return string|int
* @return string|int|null
*/
public function getUserIdentifier()
{

View File

@@ -33,6 +33,11 @@ class OAuthServerException extends \Exception
*/
private $redirectUri;
/**
* @var array
*/
private $payload;
/**
* Throw a new exception.
*
@@ -50,6 +55,33 @@ class OAuthServerException extends \Exception
$this->errorType = $errorType;
$this->hint = $hint;
$this->redirectUri = $redirectUri;
$this->payload = [
'error' => $errorType,
'message' => $message,
];
if ($hint !== null) {
$this->payload['hint'] = $hint;
}
}
/**
* Returns the current payload.
*
* @return array
*/
public function getPayload()
{
return $this->payload;
}
/**
* Updates the current payload.
*
* @param array $payload
*/
public function setPayload(array $payload)
{
$this->payload = $payload;
}
/**
@@ -131,7 +163,7 @@ class OAuthServerException extends \Exception
/**
* Server error.
*
* @param $hint
* @param string $hint
*
* @return static
*
@@ -213,21 +245,15 @@ class OAuthServerException extends \Exception
*
* @param ResponseInterface $response
* @param bool $useFragment True if errors should be in the URI fragment instead of query string
* @param int $jsonOptions options passed to json_encode
*
* @return ResponseInterface
*/
public function generateHttpResponse(ResponseInterface $response, $useFragment = false)
public function generateHttpResponse(ResponseInterface $response, $useFragment = false, $jsonOptions = 0)
{
$headers = $this->getHttpHeaders();
$payload = [
'error' => $this->getErrorType(),
'message' => $this->getMessage(),
];
if ($this->hint !== null) {
$payload['hint'] = $this->hint;
}
$payload = $this->getPayload();
if ($this->redirectUri !== null) {
if ($useFragment === true) {
@@ -243,7 +269,7 @@ class OAuthServerException extends \Exception
$response = $response->withHeader($header, $content);
}
$response->getBody()->write(json_encode($payload));
$response->getBody()->write(json_encode($payload, $jsonOptions));
return $response->withStatus($this->getHttpStatusCode());
}

View File

@@ -204,7 +204,7 @@ abstract class AbstractGrant implements GrantTypeInterface
throw OAuthServerException::invalidClient();
} elseif (
is_array($client->getRedirectUri())
&& in_array($redirectUri, $client->getRedirectUri()) === false
&& in_array($redirectUri, $client->getRedirectUri(), true) === false
) {
$this->getEmitter()->emit(new RequestEvent(RequestEvent::CLIENT_AUTHENTICATION_FAILED, $request));
throw OAuthServerException::invalidClient();
@@ -341,7 +341,7 @@ abstract class AbstractGrant implements GrantTypeInterface
*
* @param \DateInterval $accessTokenTTL
* @param ClientEntityInterface $client
* @param string $userIdentifier
* @param string|null $userIdentifier
* @param ScopeEntityInterface[] $scopes
*
* @throws OAuthServerException

View File

@@ -134,6 +134,15 @@ class AuthCodeGrant extends AbstractAuthorizeGrant
throw OAuthServerException::invalidRequest('code_verifier');
}
// Validate code_verifier according to RFC-7636
// @see: https://tools.ietf.org/html/rfc7636#section-4.1
if (preg_match('/^[A-Za-z0-9-._~]{43,128}$/', $codeVerifier) !== 1) {
throw OAuthServerException::invalidRequest(
'code_verifier',
'Code Verifier must follow the specifications of RFC-7636.'
);
}
switch ($authCodePayload->code_challenge_method) {
case 'plain':
if (hash_equals($codeVerifier, $authCodePayload->code_challenge) === false) {
@@ -144,7 +153,7 @@ class AuthCodeGrant extends AbstractAuthorizeGrant
case 'S256':
if (
hash_equals(
hash('sha256', strtr(rtrim(base64_encode($codeVerifier), '='), '+/', '-_')),
strtr(rtrim(base64_encode(hash('sha256', $codeVerifier, true)), '='), '+/', '-_'),
$authCodePayload->code_challenge
) === false
) {
@@ -167,6 +176,10 @@ class AuthCodeGrant extends AbstractAuthorizeGrant
$accessToken = $this->issueAccessToken($accessTokenTTL, $client, $authCodePayload->user_id, $scopes);
$refreshToken = $this->issueRefreshToken($accessToken);
// Send events to emitter
$this->getEmitter()->emit(new RequestEvent(RequestEvent::ACCESS_TOKEN_ISSUED, $request));
$this->getEmitter()->emit(new RequestEvent(RequestEvent::REFRESH_TOKEN_ISSUED, $request));
// Inject tokens into response type
$responseType->setAccessToken($accessToken);
$responseType->setRefreshToken($refreshToken);
@@ -187,6 +200,27 @@ class AuthCodeGrant extends AbstractAuthorizeGrant
return 'authorization_code';
}
/**
* Fetch the client_id parameter from the query string.
*
* @return string|null
* @throws OAuthServerException
*/
protected function getClientIdFromRequest($request)
{
$clientId = $this->getQueryStringParameter(
'client_id',
$request,
$this->getServerParameter('PHP_AUTH_USER', $request)
);
if (is_null($clientId)) {
throw OAuthServerException::invalidRequest('client_id');
}
return $clientId;
}
/**
* {@inheritdoc}
*/
@@ -195,7 +229,7 @@ class AuthCodeGrant extends AbstractAuthorizeGrant
return (
array_key_exists('response_type', $request->getQueryParams())
&& $request->getQueryParams()['response_type'] === 'code'
&& isset($request->getQueryParams()['client_id'])
&& $this->getClientIdFromRequest($request) !== null
);
}
@@ -204,14 +238,7 @@ class AuthCodeGrant extends AbstractAuthorizeGrant
*/
public function validateAuthorizationRequest(ServerRequestInterface $request)
{
$clientId = $this->getQueryStringParameter(
'client_id',
$request,
$this->getServerParameter('PHP_AUTH_USER', $request)
);
if (is_null($clientId)) {
throw OAuthServerException::invalidRequest('client_id');
}
$clientId = $this->getClientIdFromRequest($request);
$client = $this->clientRepository->getClientEntity(
$clientId,
@@ -235,23 +262,24 @@ class AuthCodeGrant extends AbstractAuthorizeGrant
throw OAuthServerException::invalidClient();
} elseif (
is_array($client->getRedirectUri())
&& in_array($redirectUri, $client->getRedirectUri()) === false
&& in_array($redirectUri, $client->getRedirectUri(), true) === false
) {
$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())
) {
|| empty($client->getRedirectUri())) {
$this->getEmitter()->emit(new RequestEvent(RequestEvent::CLIENT_AUTHENTICATION_FAILED, $request));
throw OAuthServerException::invalidClient();
} else {
$redirectUri = is_array($client->getRedirectUri())
? $client->getRedirectUri()[0]
: $client->getRedirectUri();
}
$scopes = $this->validateScopes(
$this->getQueryStringParameter('scope', $request, $this->defaultScope),
is_array($client->getRedirectUri())
? $client->getRedirectUri()[0]
: $client->getRedirectUri()
$redirectUri
);
$stateParameter = $this->getQueryStringParameter('state', $request);
@@ -269,21 +297,23 @@ class AuthCodeGrant extends AbstractAuthorizeGrant
throw OAuthServerException::invalidRequest('code_challenge');
}
if (preg_match('/^[A-Za-z0-9-._~]{43,128}$/', $codeChallenge) !== 1) {
throw OAuthServerException::invalidRequest(
'code_challenge',
'The code_challenge must be between 43 and 128 characters'
);
}
$codeChallengeMethod = $this->getQueryStringParameter('code_challenge_method', $request, 'plain');
if (in_array($codeChallengeMethod, ['plain', 'S256']) === false) {
if (in_array($codeChallengeMethod, ['plain', 'S256'], true) === false) {
throw OAuthServerException::invalidRequest(
'code_challenge_method',
'Code challenge method must be `plain` or `S256`'
);
}
// Validate code_challenge according to RFC-7636
// @see: https://tools.ietf.org/html/rfc7636#section-4.2
if (preg_match('/^[A-Za-z0-9-._~]{43,128}$/', $codeChallenge) !== 1) {
throw OAuthServerException::invalidRequest(
'code_challenged',
'Code challenge must follow the specifications of RFC-7636.'
);
}
$authorizationRequest->setCodeChallenge($codeChallenge);
$authorizationRequest->setCodeChallengeMethod($codeChallengeMethod);
}

View File

@@ -11,6 +11,7 @@
namespace League\OAuth2\Server\Grant;
use League\OAuth2\Server\RequestEvent;
use League\OAuth2\Server\ResponseTypes\ResponseTypeInterface;
use Psr\Http\Message\ServerRequestInterface;
@@ -37,6 +38,9 @@ class ClientCredentialsGrant extends AbstractGrant
// Issue and persist access token
$accessToken = $this->issueAccessToken($accessTokenTTL, $client, null, $finalizedScopes);
// Send event to emitter
$this->getEmitter()->emit(new RequestEvent(RequestEvent::ACCESS_TOKEN_ISSUED, $request));
// Inject access token into response type
$responseType->setAccessToken($accessToken);

View File

@@ -33,7 +33,7 @@ class ImplicitGrant extends AbstractAuthorizeGrant
/**
* @param \DateInterval $accessTokenTTL
* @param string $queryDelimiter
* @param string $queryDelimiter
*/
public function __construct(\DateInterval $accessTokenTTL, $queryDelimiter = '#')
{
@@ -144,23 +144,24 @@ class ImplicitGrant extends AbstractAuthorizeGrant
throw OAuthServerException::invalidClient();
} elseif (
is_array($client->getRedirectUri())
&& in_array($redirectUri, $client->getRedirectUri()) === false
&& in_array($redirectUri, $client->getRedirectUri(), true) === false
) {
$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())
) {
|| empty($client->getRedirectUri())) {
$this->getEmitter()->emit(new RequestEvent(RequestEvent::CLIENT_AUTHENTICATION_FAILED, $request));
throw OAuthServerException::invalidClient();
} else {
$redirectUri = is_array($client->getRedirectUri())
? $client->getRedirectUri()[0]
: $client->getRedirectUri();
}
$scopes = $this->validateScopes(
$this->getQueryStringParameter('scope', $request, $this->defaultScope),
is_array($client->getRedirectUri())
? $client->getRedirectUri()[0]
: $client->getRedirectUri()
$redirectUri
);
// Finalize the requested scopes

View File

@@ -59,6 +59,10 @@ class PasswordGrant extends AbstractGrant
$accessToken = $this->issueAccessToken($accessTokenTTL, $client, $user->getIdentifier(), $finalizedScopes);
$refreshToken = $this->issueRefreshToken($accessToken);
// Send events to emitter
$this->getEmitter()->emit(new RequestEvent(RequestEvent::ACCESS_TOKEN_ISSUED, $request));
$this->getEmitter()->emit(new RequestEvent(RequestEvent::REFRESH_TOKEN_ISSUED, $request));
// Inject tokens into response
$responseType->setAccessToken($accessToken);
$responseType->setRefreshToken($refreshToken);

View File

@@ -11,7 +11,6 @@
namespace League\OAuth2\Server\Grant;
use League\OAuth2\Server\Entities\ScopeEntityInterface;
use League\OAuth2\Server\Exception\OAuthServerException;
use League\OAuth2\Server\Repositories\RefreshTokenRepositoryInterface;
use League\OAuth2\Server\RequestEvent;
@@ -53,7 +52,7 @@ class RefreshTokenGrant extends AbstractGrant
// 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) {
if (in_array($scope->getIdentifier(), $oldRefreshToken['scopes'], true) === false) {
throw OAuthServerException::invalidScope($scope->getIdentifier());
}
}
@@ -66,6 +65,10 @@ class RefreshTokenGrant extends AbstractGrant
$accessToken = $this->issueAccessToken($accessTokenTTL, $client, $oldRefreshToken['user_id'], $scopes);
$refreshToken = $this->issueRefreshToken($accessToken);
// Send events to emitter
$this->getEmitter()->emit(new RequestEvent(RequestEvent::ACCESS_TOKEN_ISSUED, $request));
$this->getEmitter()->emit(new RequestEvent(RequestEvent::REFRESH_TOKEN_ISSUED, $request));
// Inject tokens into response
$responseType->setAccessToken($accessToken);
$responseType->setRefreshToken($refreshToken);

View File

@@ -20,12 +20,12 @@ interface ClientRepositoryInterface extends RepositoryInterface
* Get a client.
*
* @param string $clientIdentifier The client's identifier
* @param string $grantType The grant type used
* @param null|string $grantType The grant type used (if sent)
* @param null|string $clientSecret The client's secret (if sent)
* @param bool $mustValidateSecret If true the client must attempt to validate the secret if the client
* is confidential
*
* @return ClientEntityInterface
*/
public function getClientEntity($clientIdentifier, $grantType, $clientSecret = null, $mustValidateSecret = true);
public function getClientEntity($clientIdentifier, $grantType = null, $clientSecret = null, $mustValidateSecret = true);
}

View File

@@ -18,6 +18,9 @@ class RequestEvent extends Event
const USER_AUTHENTICATION_FAILED = 'user.authentication.failed';
const REFRESH_TOKEN_CLIENT_FAILED = 'refresh_token.client.failed';
const REFRESH_TOKEN_ISSUED = 'refresh_token.issued';
const ACCESS_TOKEN_ISSUED = 'access_token.issued';
/**
* @var ServerRequestInterface
*/

View File

@@ -53,7 +53,7 @@ class AuthorizationRequest
/**
* The redirect URI used in the request
*
* @var string
* @var string|null
*/
protected $redirectUri;
@@ -159,7 +159,7 @@ class AuthorizationRequest
}
/**
* @return string
* @return string|null
*/
public function getRedirectUri()
{
@@ -167,7 +167,7 @@ class AuthorizationRequest
}
/**
* @param string $redirectUri
* @param string|null $redirectUri
*/
public function setRedirectUri($redirectUri)
{

View File

@@ -63,7 +63,9 @@ class ResourceServer
$this->authorizationValidator = new BearerTokenValidator($this->accessTokenRepository);
}
$this->authorizationValidator->setPublicKey($this->publicKey);
if ($this->authorizationValidator instanceof BearerTokenValidator === true) {
$this->authorizationValidator->setPublicKey($this->publicKey);
}
return $this->authorizationValidator;
}