Updated abstract grant and client credentials grant

This commit is contained in:
Alex Bilbie 2015-04-05 17:01:19 +01:00
parent 36a1a430b5
commit f964fd2962
2 changed files with 102 additions and 178 deletions

View File

@ -11,10 +11,13 @@
namespace League\OAuth2\Server\Grant; namespace League\OAuth2\Server\Grant;
use League\OAuth2\Server\AuthorizationServer; use League\Event\Emitter;
use League\OAuth2\Server\Entity\ClientEntity; use League\OAuth2\Server\Entities\Interfaces\ClientEntityInterface;
use League\OAuth2\Server\Entity\ScopeEntity; use League\OAuth2\Server\Entities\ScopeEntity;
use League\OAuth2\Server\Exception; use League\OAuth2\Server\Exception;
use League\OAuth2\Server\Repositories\AccessTokenRepositoryInterface;
use League\OAuth2\Server\Repositories\ClientRepositoryInterface;
use League\OAuth2\Server\Repositories\ScopeRepositoryInterface;
/** /**
* Abstract grant class * Abstract grant class
@ -29,32 +32,54 @@ abstract class AbstractGrant implements GrantTypeInterface
protected $identifier = ''; protected $identifier = '';
/** /**
* Response type * Grant responds with
* *
* @var string * @var string
*/ */
protected $responseType; protected $respondsWith = 'token';
/** /**
* Callback to authenticate a user's name and password * @var \Symfony\Component\HttpFoundation\Request
*
* @var callable
*/ */
protected $callback; protected $request;
/** /**
* AuthServer instance * @var ClientRepositoryInterface
*
* @var \League\OAuth2\Server\AuthorizationServer
*/ */
protected $server; protected $clientRepository;
/** /**
* Access token expires in override * @var AccessTokenRepositoryInterface
*
* @var int
*/ */
protected $accessTokenTTL; protected $accessTokenRepository;
/**
* @var \League\Event\Emitter
*/
protected $emitter;
/**
* @var ScopeRepositoryInterface
*/
protected $scopeRepository;
/**
* @param \League\Event\Emitter $emitter
* @param \League\OAuth2\Server\Repositories\ClientRepositoryInterface $clientRepository
* @param \League\OAuth2\Server\Repositories\ScopeRepositoryInterface $scopeRepository
* @param \League\OAuth2\Server\Repositories\AccessTokenRepositoryInterface $accessTokenRepository
*/
public function __construct(
Emitter $emitter,
ClientRepositoryInterface $clientRepository,
ScopeRepositoryInterface $scopeRepository,
AccessTokenRepositoryInterface $accessTokenRepository
) {
$this->emitter = $emitter;
$this->clientRepository = $clientRepository;
$this->scopeRepository = $scopeRepository;
$this->accessTokenRepository = $accessTokenRepository;
}
/** /**
* {@inheritdoc} * {@inheritdoc}
@ -67,74 +92,27 @@ abstract class AbstractGrant implements GrantTypeInterface
/** /**
* {@inheritdoc} * {@inheritdoc}
*/ */
public function setIdentifier($identifier) public function respondsWith()
{ {
$this->identifier = $identifier; return $this->respondsWith;
return $this;
} }
/** /**
* {@inheritdoc} * @param string $scopeParamValue A string containing a delimited set of scope identifiers
* @param string $scopeDelimiter The delimiter between the scopes in the value string
* @param ClientEntityInterface $client
* @param string $redirectUri
*
* @return \League\OAuth2\Server\Entities\ScopeEntity[]
* @throws \League\OAuth2\Server\Exception\InvalidScopeException
*/ */
public function getResponseType() public function validateScopes(
{ $scopeParamValue,
return $this->responseType; $scopeDelimiter,
} ClientEntityInterface $client,
$redirectUri = null
/** ) {
* Get the TTL for an access token $scopesList = explode($scopeDelimiter, trim($scopeParamValue));
*
* @return int The TTL
*/
public function getAccessTokenTTL()
{
if ($this->accessTokenTTL) {
return $this->accessTokenTTL;
}
return $this->server->getAccessTokenTTL();
}
/**
* Override the default access token expire time
*
* @param int $accessTokenTTL
*
* @return self
*/
public function setAccessTokenTTL($accessTokenTTL)
{
$this->accessTokenTTL = $accessTokenTTL;
return $this;
}
/**
* {@inheritdoc}
*/
public function setAuthorizationServer(AuthorizationServer $server)
{
$this->server = $server;
return $this;
}
/**
* Given a list of scopes, validate them and return an array of Scope entities
*
* @param string $scopeParam A string of scopes (e.g. "profile email birthday")
* @param \League\OAuth2\Server\Entity\ClientEntity $client Client entity
* @param string|null $redirectUri The redirect URI to return the user to
*
* @return \League\OAuth2\Server\Entity\ScopeEntity[]
*
* @throws \League\OAuth2\Server\Exception\InvalidScopeException If scope is invalid, or no scopes passed when required
* @throws
*/
public function validateScopes($scopeParam = '', ClientEntity $client, $redirectUri = null)
{
$scopesList = explode($this->server->getScopeDelimiter(), $scopeParam);
for ($i = 0; $i < count($scopesList); $i++) { for ($i = 0; $i < count($scopesList); $i++) {
$scopesList[$i] = trim($scopesList[$i]); $scopesList[$i] = trim($scopesList[$i]);
@ -143,53 +121,19 @@ abstract class AbstractGrant implements GrantTypeInterface
} }
} }
if (
$this->server->scopeParamRequired() === true
&& $this->server->getDefaultScope() === null
&& count($scopesList) === 0
) {
throw new Exception\InvalidRequestException('scope');
} elseif (count($scopesList) === 0 && $this->server->getDefaultScope() !== null) {
if (is_array($this->server->getDefaultScope())) {
$scopesList = $this->server->getDefaultScope();
} else {
$scopesList = [0 => $this->server->getDefaultScope()];
}
}
$scopes = []; $scopes = [];
foreach ($scopesList as $scopeItem) { foreach ($scopesList as $scopeItem) {
$scope = $this->server->getScopeStorage()->get( $scope = $this->scopeRepository->get(
$scopeItem, $scopeItem,
$this->getIdentifier(), $this->getIdentifier(),
$client->getId() $client->getIdentifier()
); );
if (($scope instanceof ScopeEntity) === false) { if (($scope instanceof ScopeEntity) === false) {
throw new Exception\InvalidScopeException($scopeItem, $redirectUri); throw new Exception\InvalidScopeException($scopeItem, $redirectUri);
} }
$scopes[$scope->getId()] = $scope; $scopes[] = $scope;
}
return $scopes;
}
/**
* Format the local scopes array
*
* @param \League\OAuth2\Server\Entity\ScopeEntity[]
*
* @return array
*/
protected function formatScopes($unformated = [])
{
$scopes = [];
foreach ($unformated as $scope) {
if ($scope instanceof ScopeEntity) {
$scopes[$scope->getId()] = $scope;
}
} }
return $scopes; return $scopes;

View File

@ -11,12 +11,14 @@
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 League\Event\Event;
use League\OAuth2\Server\Entity\SessionEntity; use League\OAuth2\Server\Entities\AccessTokenEntity;
use League\OAuth2\Server\Event; use League\OAuth2\Server\Entities\Interfaces\ClientEntityInterface;
use League\OAuth2\Server\Exception; use League\OAuth2\Server\Exception;
use League\OAuth2\Server\Util\SecureKey; use League\OAuth2\Server\ResponseTypes\ResponseTypeInterface;
use League\OAuth2\Server\Utils\SecureKey;
use Symfony\Component\HttpFoundation\Request;
/** /**
* Client credentials grant class * Client credentials grant class
@ -31,92 +33,70 @@ class ClientCredentialsGrant extends AbstractGrant
protected $identifier = 'client_credentials'; protected $identifier = 'client_credentials';
/** /**
* Response type * Return an access token
* *
* @var string * @param \Symfony\Component\HttpFoundation\Request $request
* @param \League\OAuth2\Server\ResponseTypes\ResponseTypeInterface $responseType
* @param \DateInterval $accessTokenTTL
* @param string $scopeDelimiter
*
* @return \League\OAuth2\Server\ResponseTypes\ResponseTypeInterface
* @throws \League\OAuth2\Server\Exception\InvalidClientException
* @throws \League\OAuth2\Server\Exception\InvalidRequestException
* @throws \League\OAuth2\Server\Exception\InvalidScopeException
*/ */
protected $responseType = null; public function getAccessTokenAsType(
Request $request,
/** ResponseTypeInterface $responseType,
* AuthServer instance DateInterval $accessTokenTTL,
* $scopeDelimiter = ' '
* @var \League\OAuth2\Server\AuthorizationServer ) {
*/
protected $server = null;
/**
* Access token expires in override
*
* @var int
*/
protected $accessTokenTTL = null;
/**
* Complete the client credentials grant
*
* @return array
*
* @throws
*/
public function completeFlow()
{
// Get the required params // Get the required params
$clientId = $this->server->getRequest()->request->get('client_id', $this->server->getRequest()->getUser()); $clientId = $request->request->get('client_id', $request->getUser());
if (is_null($clientId)) { if (is_null($clientId)) {
throw new Exception\InvalidRequestException('client_id'); throw new Exception\InvalidRequestException('client_id');
} }
$clientSecret = $this->server->getRequest()->request->get('client_secret', $clientSecret = $request->request->get('client_secret', $request->getPassword());
$this->server->getRequest()->getPassword());
if (is_null($clientSecret)) { if (is_null($clientSecret)) {
throw new Exception\InvalidRequestException('client_secret'); throw new Exception\InvalidRequestException('client_secret');
} }
// Validate client ID and client secret // Validate client ID and client secret
$client = $this->server->getClientStorage()->get( $client = $this->clientRepository->get(
$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 new Exception\InvalidClientException();
} }
// Validate any scopes that are in the request // Validate any scopes that are in the request
$scopeParam = $this->server->getRequest()->request->get('scope', ''); $scopeParam = $request->request->get('scope', '');
$scopes = $this->validateScopes($scopeParam, $client); $scopes = $this->validateScopes($scopeParam, $scopeDelimiter, $client);
// Create a new session
$session = new SessionEntity($this->server);
$session->setOwner('client', $client->getId());
$session->associateClient($client);
// Generate an access token // Generate an access token
$accessToken = new AccessTokenEntity($this->server); $accessToken = new AccessTokenEntity();
$accessToken->setId(SecureKey::generate()); $accessToken->setIdentifier(SecureKey::generate());
$accessToken->setExpireTime($this->getAccessTokenTTL() + time()); $accessToken->setExpiryDateTime((new \DateTime())->add($accessTokenTTL));
$accessToken->setClient($client);
$accessToken->setOwner('client', $client->getIdentifier());
// Associate scopes with the session and access token // Associate scopes with the session and access token
foreach ($scopes as $scope) { foreach ($scopes as $scope) {
$session->associateScope($scope); $accessToken->addScope($scope);
} }
foreach ($session->getScopes() as $scope) { // Save the token
$accessToken->associateScope($scope); $this->accessTokenRepository->create($accessToken);
}
// Save everything // Inject access token into token type
$session->save(); $responseType->setAccessToken($accessToken);
$accessToken->setSession($session);
$accessToken->save();
$this->server->getTokenType()->setSession($session); return $responseType;
$this->server->getTokenType()->setParam('access_token', $accessToken->getId());
$this->server->getTokenType()->setParam('expires_in', $this->getAccessTokenTTL());
return $this->server->getTokenType()->generateResponse();
} }
} }