Updated refresh token grant

This commit is contained in:
Alex Bilbie 2016-01-12 23:53:03 +00:00
parent a2bbb17483
commit 6fb3fb5110

View File

@ -11,12 +11,23 @@
namespace League\OAuth2\Server\Grant; namespace League\OAuth2\Server\Grant;
use League\OAuth2\Server\Entity\AccessTokenEntity; use DateInterval;
use League\OAuth2\Server\Entity\ClientEntity; use Lcobucci\JWT\Parser;
use League\OAuth2\Server\Entity\RefreshTokenEntity; use Lcobucci\JWT\Signer\Key;
use League\OAuth2\Server\Event; use Lcobucci\JWT\Signer\Rsa\Sha256;
use League\OAuth2\Server\Exception; use Lcobucci\JWT\ValidationData;
use League\OAuth2\Server\Util\SecureKey; use League\OAuth2\Server\Entities\AccessTokenEntity;
use League\OAuth2\Server\Entities\Interfaces\ClientEntityInterface;
use League\OAuth2\Server\Entities\RefreshTokenEntity;
use League\OAuth2\Server\Exception\OAuthServerException;
use League\OAuth2\Server\Repositories\AccessTokenRepositoryInterface;
use League\OAuth2\Server\Repositories\ClientRepositoryInterface;
use League\OAuth2\Server\Repositories\RefreshTokenRepositoryInterface;
use League\OAuth2\Server\Repositories\ScopeRepositoryInterface;
use League\OAuth2\Server\ResponseTypes\ResponseTypeInterface;
use League\OAuth2\Server\Utils\SecureKey;
use Psr\Http\Message\ServerRequestInterface;
use Symfony\Component\EventDispatcher\Event;
/** /**
* Refresh token grant * Refresh token grant
@ -24,120 +35,105 @@ use League\OAuth2\Server\Util\SecureKey;
class RefreshTokenGrant extends AbstractGrant class RefreshTokenGrant extends AbstractGrant
{ {
/** /**
* {@inheritdoc} * @var \League\OAuth2\Server\Repositories\RefreshTokenRepositoryInterface
*/ */
protected $identifier = 'refresh_token'; private $refreshTokenRepository;
/**
* @var string
*/
private $pathToPublicKey;
/** /**
* Refresh token TTL (default = 604800 | 1 week) * @param string $pathToPublicKey
* * @param \League\OAuth2\Server\Repositories\ClientRepositoryInterface $clientRepository
* @var integer * @param \League\OAuth2\Server\Repositories\ScopeRepositoryInterface $scopeRepository
* @param \League\OAuth2\Server\Repositories\AccessTokenRepositoryInterface $accessTokenRepository
* @param \League\OAuth2\Server\Repositories\RefreshTokenRepositoryInterface $refreshTokenRepository
*/ */
protected $refreshTokenTTL = 604800; public function __construct(
$pathToPublicKey,
/** ClientRepositoryInterface $clientRepository,
* Rotate token (default = true) ScopeRepositoryInterface $scopeRepository,
* AccessTokenRepositoryInterface $accessTokenRepository,
* @var integer RefreshTokenRepositoryInterface $refreshTokenRepository
*/ ) {
protected $refreshTokenRotate = true; $this->pathToPublicKey = $pathToPublicKey;
$this->refreshTokenRepository = $refreshTokenRepository;
/** parent::__construct($clientRepository, $scopeRepository, $accessTokenRepository);
* Set the TTL of the refresh token
*
* @param int $refreshTokenTTL
*
* @return void
*/
public function setRefreshTokenTTL($refreshTokenTTL)
{
$this->refreshTokenTTL = $refreshTokenTTL;
} }
/** /**
* Get the TTL of the refresh token * @inheritdoc
*
* @return int
*/ */
public function getRefreshTokenTTL() public function respondToRequest(
{ ServerRequestInterface $request,
return $this->refreshTokenTTL; ResponseTypeInterface $responseType,
} DateInterval $tokenTTL,
$scopeDelimiter = ' '
) {
// Get the required params
$clientId = isset($request->getParsedBody()['client_id'])
? $request->getParsedBody()['client_id'] // $_POST['client_id']
: (isset($request->getServerParams()['PHP_AUTH_USER'])
? $request->getServerParams()['PHP_AUTH_USER'] // $_SERVER['PHP_AUTH_USER']
: null);
/**
* Set the rotation boolean of the refresh token
* @param bool $refreshTokenRotate
*/
public function setRefreshTokenRotation($refreshTokenRotate = true)
{
$this->refreshTokenRotate = $refreshTokenRotate;
}
/**
* Get rotation boolean of the refresh token
*
* @return bool
*/
public function shouldRotateRefreshTokens()
{
return $this->refreshTokenRotate;
}
/**
* {@inheritdoc}
*/
public function completeFlow()
{
$clientId = $this->server->getRequest()->request->get('client_id', $this->server->getRequest()->getUser());
if (is_null($clientId)) { if (is_null($clientId)) {
throw new Exception\InvalidRequestException('client_id'); throw OAuthServerException::invalidRequest('client_id', null, '`%s` parameter is missing');
} }
$clientSecret = $this->server->getRequest()->request->get('client_secret', $clientSecret = isset($request->getParsedBody()['client_secret'])
$this->server->getRequest()->getPassword()); ? $request->getParsedBody()['client_secret'] // $_POST['client_id']
: (isset($request->getServerParams()['PHP_AUTH_PW'])
? $request->getServerParams()['PHP_AUTH_PW'] // $_SERVER['PHP_AUTH_USER']
: null);
if (is_null($clientSecret)) { if (is_null($clientSecret)) {
throw new Exception\InvalidRequestException('client_secret'); throw OAuthServerException::invalidRequest('client_secret', null, '`%s` parameter is missing');
}
$refreshTokenJwt = isset($request->getParsedBody()['refresh_token'])
? $request->getParsedBody()['refresh_token']
: null;
if ($refreshTokenJwt === null) {
throw OAuthServerException::invalidRequest('refresh_token', null, '`%s` parameter is missing');
} }
// Validate client ID and client secret // Validate client ID and client secret
$client = $this->server->getClientStorage()->get( $client = $this->clientRepository->getClientEntity(
$clientId, $clientId,
$clientSecret, $clientSecret,
null, null,
$this->getIdentifier() $this->getIdentifier()
); );
if (($client instanceof ClientEntity) === false) { if (($client instanceof ClientEntityInterface) === false) {
$this->server->getEventEmitter()->emit(new Event\ClientAuthenticationFailedEvent($this->server->getRequest())); $this->emitter->emit(new Event('client.authentication.failed', $request));
throw new Exception\InvalidClientException(); throw OAuthServerException::invalidClient();
}
$oldRefreshTokenParam = $this->server->getRequest()->request->get('refresh_token', null);
if ($oldRefreshTokenParam === null) {
throw new Exception\InvalidRequestException('refresh_token');
} }
// Validate refresh token // Validate refresh token
$oldRefreshToken = $this->server->getRefreshTokenStorage()->get($oldRefreshTokenParam); $oldRefreshToken = (new Parser())->parse($refreshTokenJwt);
if ($oldRefreshToken->verify(new Sha256(), new Key($this->pathToPublicKey)) === false) {
if (($oldRefreshToken instanceof RefreshTokenEntity) === false) { throw OAuthServerException::invalidRefreshToken();
throw new Exception\InvalidRefreshException();
} }
// Ensure the old refresh token hasn't expired $validation = new ValidationData();
if ($oldRefreshToken->isExpired() === true) { $validation->setAudience($client->getIdentifier());
throw new Exception\InvalidRefreshException(); $validation->setCurrentTime(time());
if ($oldRefreshToken->validate($validation) === false) {
throw OAuthServerException::invalidRefreshToken();
} }
$oldAccessToken = $oldRefreshToken->getAccessToken();
// Get the scopes for the original session // Get the scopes for the original session
$session = $oldAccessToken->getSession(); $scopes = $oldRefreshToken->getClaim('scopes');
$scopes = $this->formatScopes($session->getScopes());
// Get and validate any requested scopes // Get and validate any requested scopes
$requestedScopesString = $this->server->getRequest()->request->get('scope', ''); $scopeParam = isset($request->getParsedBody()['scope'])
$requestedScopes = $this->validateScopes($requestedScopesString, $client); ? $request->getParsedBody()['scope'] // $_POST['scope']
: '';
$requestedScopes = $this->validateScopes($scopeParam, $scopeDelimiter, $client);
// If no new scopes are requested then give the access token the original session scopes // If no new scopes are requested then give the access token the original session scopes
if (count($requestedScopes) === 0) { if (count($requestedScopes) === 0) {
@ -146,48 +142,52 @@ class RefreshTokenGrant extends AbstractGrant
// The OAuth spec says that a refreshed access token can have the original scopes or fewer so ensure // 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 // the request doesn't include any new scopes
foreach ($requestedScopes as $requestedScope) { foreach ($requestedScopes as $requestedScope) {
if (!isset($scopes[$requestedScope->getId()])) { if (!isset($scopes[$requestedScope->getIdentifier()])) {
throw new Exception\InvalidScopeException($requestedScope->getId()); throw OAuthServerException::invalidScope($requestedScope->getIdentifier());
} }
} }
$newScopes = $requestedScopes; $newScopes = $requestedScopes;
} }
// Generate a new access token and assign it the correct sessions // Generate a new access token
$newAccessToken = new AccessTokenEntity($this->server); $accessToken = new AccessTokenEntity();
$newAccessToken->setId(SecureKey::generate()); $accessToken->setIdentifier(SecureKey::generate());
$newAccessToken->setExpireTime($this->getAccessTokenTTL() + time()); $accessToken->setExpiryDateTime((new \DateTime())->add($tokenTTL));
$newAccessToken->setSession($session); $accessToken->setClient($client);
$accessToken->setUserIdentifier($oldRefreshToken->getClaim('uid'));
foreach ($newScopes as $newScope) { foreach ($newScopes as $scope) {
$newAccessToken->associateScope($newScope); $accessToken->addScope($scope);
} }
// Expire the old token and save the new one // Expire the old token and save the new one
$oldAccessToken->expire(); $this->accessTokenRepository->revokeAccessToken($oldRefreshToken->getClaim('accessToken'));
$newAccessToken->save();
$this->server->getTokenType()->setSession($session);
$this->server->getTokenType()->setParam('access_token', $newAccessToken->getId());
$this->server->getTokenType()->setParam('expires_in', $this->getAccessTokenTTL());
if ($this->shouldRotateRefreshTokens()) {
// Expire the old refresh token
$oldRefreshToken->expire();
// Generate a new refresh token // Generate a new refresh token
$newRefreshToken = new RefreshTokenEntity($this->server); $refreshToken = new RefreshTokenEntity();
$newRefreshToken->setId(SecureKey::generate()); $refreshToken->setIdentifier(SecureKey::generate());
$newRefreshToken->setExpireTime($this->getRefreshTokenTTL() + time()); $refreshToken->setExpiryDateTime((new \DateTime())->add(new DateInterval('P1M')));
$newRefreshToken->setAccessToken($newAccessToken); $refreshToken->setAccessToken($accessToken);
$newRefreshToken->save();
$this->server->getTokenType()->setParam('refresh_token', $newRefreshToken->getId()); // Persist the tokens
} else { $this->accessTokenRepository->persistNewAccessToken($accessToken);
$this->server->getTokenType()->setParam('refresh_token', $oldRefreshToken->getId()); $this->refreshTokenRepository->persistNewRefreshToken($refreshToken);
// Inject tokens into response
$responseType->setAccessToken($accessToken);
$responseType->setRefreshToken($refreshToken);
return $responseType;
} }
return $this->server->getTokenType()->generateResponse(); /**
* @inheritdoc
*/
public function canRespondToRequest(ServerRequestInterface $request)
{
return (
isset($request->getParsedBody()['grant_type'])
&& $request->getParsedBody()['grant_type'] === 'refresh_token'
);
} }
} }